Skip to main content

alef_e2e/codegen/
elixir.rs

1//! Elixir e2e test generator using ExUnit.
2
3use crate::config::E2eConfig;
4use crate::escape::{escape_elixir, sanitize_filename, sanitize_ident};
5use crate::field_access::FieldResolver;
6use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
7use alef_core::backend::GeneratedFile;
8use alef_core::config::ResolvedCrateConfig;
9use alef_core::hash::{self, CommentStyle};
10use alef_core::template_versions as tv;
11use anyhow::Result;
12use heck::ToSnakeCase;
13use std::collections::HashMap;
14use std::fmt::Write as FmtWrite;
15use std::path::PathBuf;
16
17use super::E2eCodegen;
18use super::client;
19
20/// Elixir e2e code generator.
21pub struct ElixirCodegen;
22
23impl E2eCodegen for ElixirCodegen {
24    fn generate(
25        &self,
26        groups: &[FixtureGroup],
27        e2e_config: &E2eConfig,
28        config: &ResolvedCrateConfig,
29        _type_defs: &[alef_core::ir::TypeDef],
30        _enums: &[alef_core::ir::EnumDef],
31    ) -> Result<Vec<GeneratedFile>> {
32        let lang = self.language_name();
33        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
34
35        let mut files = Vec::new();
36
37        // Resolve call config with overrides.
38        let call = &e2e_config.call;
39        let overrides = call.overrides.get(lang);
40        let raw_module = overrides
41            .and_then(|o| o.module.as_ref())
42            .cloned()
43            .unwrap_or_else(|| call.module.clone());
44        // Convert module path to Elixir PascalCase if it looks like snake_case
45        // (e.g., "html_to_markdown" -> "HtmlToMarkdown").
46        // If the override already contains "." (e.g., "Elixir.HtmlToMarkdown"), use as-is.
47        let module_path = if raw_module.contains('.') || raw_module.chars().next().is_some_and(|c| c.is_uppercase()) {
48            raw_module.clone()
49        } else {
50            elixir_module_name(&raw_module)
51        };
52        let base_function_name = overrides
53            .and_then(|o| o.function.as_ref())
54            .cloned()
55            .unwrap_or_else(|| call.function.clone());
56        // Elixir facade exports async variants with `_async` suffix when the call is async.
57        // Append the suffix only if not already present and the function isn't a streaming
58        // entry-point — streaming wrappers (e.g. `defaultclient_chat_stream`) drive the
59        // FFI iterator handle and aren't async-callable in the OpenAI sense.
60        let function_name =
61            if call.r#async && !base_function_name.ends_with("_async") && !base_function_name.ends_with("_stream") {
62                format!("{base_function_name}_async")
63            } else {
64                base_function_name
65            };
66        let options_type = overrides.and_then(|o| o.options_type.clone());
67        let options_default_fn = overrides.and_then(|o| o.options_via.clone());
68        let empty_enum_fields = HashMap::new();
69        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
70        let handle_struct_type = overrides.and_then(|o| o.handle_struct_type.clone());
71        let empty_atom_fields = std::collections::HashSet::new();
72        let handle_atom_list_fields = overrides
73            .map(|o| &o.handle_atom_list_fields)
74            .unwrap_or(&empty_atom_fields);
75        let result_var = &call.result_var;
76
77        // Check if any fixture in any group is an HTTP test.
78        let has_http_tests = groups.iter().any(|g| g.fixtures.iter().any(|f| f.is_http_test()));
79        let has_nif_tests = groups.iter().any(|g| g.fixtures.iter().any(|f| !f.is_http_test()));
80        // Check if any fixture needs the mock server (either via http or mock_response or client_factory).
81        let has_mock_server_tests = groups.iter().any(|g| {
82            g.fixtures.iter().any(|f| {
83                if f.needs_mock_server() {
84                    return true;
85                }
86                let cc = e2e_config.resolve_call_for_fixture(
87                    f.call.as_deref(),
88                    &f.id,
89                    &f.resolved_category(),
90                    &f.tags,
91                    &f.input,
92                );
93                let elixir_override = cc
94                    .overrides
95                    .get("elixir")
96                    .or_else(|| e2e_config.call.overrides.get("elixir"));
97                elixir_override.and_then(|o| o.client_factory.as_deref()).is_some()
98            })
99        });
100
101        // Resolve package reference (path or version) for the NIF dependency.
102        let pkg_ref = e2e_config.resolve_package(lang);
103        let pkg_dep_ref = if has_nif_tests {
104            match e2e_config.dep_mode {
105                crate::config::DependencyMode::Local => pkg_ref
106                    .as_ref()
107                    .and_then(|p| p.path.as_deref())
108                    .unwrap_or("../../packages/elixir")
109                    .to_string(),
110                crate::config::DependencyMode::Registry => pkg_ref
111                    .as_ref()
112                    .and_then(|p| p.version.clone())
113                    .or_else(|| config.resolved_version())
114                    .unwrap_or_else(|| "0.1.0".to_string()),
115            }
116        } else {
117            String::new()
118        };
119
120        // Generate mix.exs. The dep atom must match the binding package's
121        // mix `app:` value, not the crate name. Use the configured
122        // `[elixir].app_name` (the same source the package's own mix.exs
123        // uses); fall back to the crate name only when unset. Without this,
124        // mix's path-dep resolution silently misroutes — the path-dep's
125        // own deps (notably `:rustler_precompiled`) never load during its
126        // compilation and the parent build fails with `RustlerPrecompiled
127        // is not loaded`.
128        let pkg_atom = config.elixir_app_name();
129        files.push(GeneratedFile {
130            path: output_base.join("mix.exs"),
131            content: render_mix_exs(
132                &pkg_atom,
133                &pkg_dep_ref,
134                e2e_config.dep_mode,
135                has_http_tests,
136                has_nif_tests,
137            ),
138            generated_header: false,
139        });
140
141        // Generate lib/e2e_elixir.ex — required so the mix project compiles.
142        files.push(GeneratedFile {
143            path: output_base.join("lib").join("e2e_elixir.ex"),
144            content: "defmodule E2eElixir do\n  @moduledoc false\nend\n".to_string(),
145            generated_header: false,
146        });
147
148        // Generate test_helper.exs.
149        files.push(GeneratedFile {
150            path: output_base.join("test").join("test_helper.exs"),
151            content: render_test_helper(has_http_tests || has_mock_server_tests),
152            generated_header: false,
153        });
154
155        // Generate test files per category.
156        for group in groups {
157            let active: Vec<&Fixture> = group
158                .fixtures
159                .iter()
160                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
161                .collect();
162
163            if active.is_empty() {
164                continue;
165            }
166
167            let filename = format!("{}_test.exs", sanitize_filename(&group.category));
168            let content = render_test_file(
169                &group.category,
170                &active,
171                e2e_config,
172                &module_path,
173                &function_name,
174                result_var,
175                &e2e_config.call.args,
176                options_type.as_deref(),
177                options_default_fn.as_deref(),
178                enum_fields,
179                handle_struct_type.as_deref(),
180                handle_atom_list_fields,
181                &config.adapters,
182            );
183            files.push(GeneratedFile {
184                path: output_base.join("test").join(filename),
185                content,
186                generated_header: true,
187            });
188        }
189
190        Ok(files)
191    }
192
193    fn language_name(&self) -> &'static str {
194        "elixir"
195    }
196}
197
198fn render_test_helper(has_http_tests: bool) -> String {
199    if has_http_tests {
200        r#"ExUnit.start()
201
202# Spawn mock-server binary and set MOCK_SERVER_URL for all tests.
203mock_server_bin = Path.expand("../../rust/target/release/mock-server", __DIR__)
204fixtures_dir = Path.expand("../../../fixtures", __DIR__)
205
206if File.exists?(mock_server_bin) do
207  port = Port.open({:spawn_executable, mock_server_bin}, [
208    :binary,
209    # Use a large line buffer (default 1024 truncates `MOCK_SERVERS={...}` lines for
210    # fixture sets with many host-root routes, splitting them into `:noeol` chunks
211    # that the prefix-match clauses below would never see).
212    {:line, 65_536},
213    args: [fixtures_dir]
214  ])
215  # Read startup lines: MOCK_SERVER_URL= then MOCK_SERVERS= (always emitted, possibly `{}`).
216  # The standalone mock-server prints noisy stderr lines BEFORE the stdout sentinels;
217  # selective receive ignores anything that doesn't match the two prefix patterns.
218  # Each iteration only halts after the MOCK_SERVERS= line is processed.
219  {url, _} =
220    Enum.reduce_while(1..16, {nil, port}, fn _, {url_acc, p} ->
221      receive do
222        {^p, {:data, {:eol, "MOCK_SERVER_URL=" <> u}}} ->
223          {:cont, {u, p}}
224
225        {^p, {:data, {:eol, "MOCK_SERVERS=" <> json_val}}} ->
226          System.put_env("MOCK_SERVERS", json_val)
227          case Jason.decode(json_val) do
228            {:ok, servers} ->
229              Enum.each(servers, fn {fid, furl} ->
230                System.put_env("MOCK_SERVER_#{String.upcase(fid)}", furl)
231              end)
232
233            _ ->
234              :ok
235          end
236
237          {:halt, {url_acc, p}}
238      after
239        30_000 ->
240          raise "mock-server startup timeout"
241      end
242    end)
243
244  if url != nil do
245    System.put_env("MOCK_SERVER_URL", url)
246  end
247end
248"#
249        .to_string()
250    } else {
251        "ExUnit.start()\n".to_string()
252    }
253}
254
255fn render_mix_exs(
256    pkg_name: &str,
257    pkg_path: &str,
258    dep_mode: crate::config::DependencyMode,
259    has_http_tests: bool,
260    has_nif_tests: bool,
261) -> String {
262    let mut out = String::new();
263    let _ = writeln!(out, "defmodule E2eElixir.MixProject do");
264    let _ = writeln!(out, "  use Mix.Project");
265    let _ = writeln!(out);
266    let _ = writeln!(out, "  def project do");
267    let _ = writeln!(out, "    [");
268    let _ = writeln!(out, "      app: :e2e_elixir,");
269    let _ = writeln!(out, "      version: \"0.1.0\",");
270    let _ = writeln!(out, "      elixir: \"~> 1.14\",");
271    let _ = writeln!(out, "      deps: deps()");
272    let _ = writeln!(out, "    ]");
273    let _ = writeln!(out, "  end");
274    let _ = writeln!(out);
275    let _ = writeln!(out, "  defp deps do");
276    let _ = writeln!(out, "    [");
277
278    // Build the list of deps, then join with commas to avoid double-commas.
279    let mut deps: Vec<String> = Vec::new();
280
281    // Add the binding NIF dependency when there are non-HTTP tests.
282    if has_nif_tests && !pkg_path.is_empty() {
283        let pkg_atom = pkg_name;
284        let nif_dep = match dep_mode {
285            crate::config::DependencyMode::Local => {
286                format!("      {{:{pkg_atom}, path: \"{pkg_path}\"}}")
287            }
288            crate::config::DependencyMode::Registry => {
289                // Registry mode: pkg_path is repurposed as the version string.
290                format!("      {{:{pkg_atom}, \"{pkg_path}\"}}")
291            }
292        };
293        deps.push(nif_dep);
294        // rustler_precompiled provides the precompiled NIF loader.
295        deps.push(format!(
296            "      {{:rustler_precompiled, \"{rp}\"}}",
297            rp = tv::hex::RUSTLER_PRECOMPILED
298        ));
299        // rustler must be a direct, non-optional dep in the consumer project for
300        // `force_build: Mix.env() in [:test, :dev]` to actually fetch the rustler hex
301        // package. With `optional: true` mix omits it when no other dep declares it as
302        // required, breaking the build-from-source path used by the e2e suite.
303        deps.push(format!(
304            "      {{:rustler, \"{rustler}\", runtime: false}}",
305            rustler = tv::hex::RUSTLER
306        ));
307    }
308
309    // Add Req + Jason for HTTP testing.
310    if has_http_tests {
311        deps.push(format!("      {{:req, \"{req}\"}}", req = tv::hex::REQ));
312        deps.push(format!("      {{:jason, \"{jason}\"}}", jason = tv::hex::JASON));
313    }
314
315    let _ = writeln!(out, "{}", deps.join(",\n"));
316    let _ = writeln!(out, "    ]");
317    let _ = writeln!(out, "  end");
318    let _ = writeln!(out, "end");
319    out
320}
321
322#[allow(clippy::too_many_arguments)]
323fn render_test_file(
324    category: &str,
325    fixtures: &[&Fixture],
326    e2e_config: &E2eConfig,
327    module_path: &str,
328    function_name: &str,
329    result_var: &str,
330    args: &[crate::config::ArgMapping],
331    options_type: Option<&str>,
332    options_default_fn: Option<&str>,
333    enum_fields: &HashMap<String, String>,
334    handle_struct_type: Option<&str>,
335    handle_atom_list_fields: &std::collections::HashSet<String>,
336    adapters: &[alef_core::config::extras::AdapterConfig],
337) -> String {
338    let mut out = String::new();
339    out.push_str(&hash::header(CommentStyle::Hash));
340    let _ = writeln!(out, "# E2e tests for category: {category}");
341    let _ = writeln!(out, "defmodule E2e.{}Test do", elixir_module_name(category));
342
343    // Add client helper when there are HTTP fixtures in this group.
344    let has_http = fixtures.iter().any(|f| f.is_http_test());
345
346    // Use async: false for NIF tests — concurrent Tokio runtimes created by DirtyCpu NIFs
347    // on ARM64 macOS cause SIGBUS when tests run in parallel. HTTP-only tests can stay async.
348    let async_flag = if has_http { "true" } else { "false" };
349    let _ = writeln!(out, "  use ExUnit.Case, async: {async_flag}");
350
351    if has_http {
352        let _ = writeln!(out);
353        let _ = writeln!(out, "  defp mock_server_url do");
354        let _ = writeln!(
355            out,
356            "    System.get_env(\"MOCK_SERVER_URL\") || \"http://localhost:8080\""
357        );
358        let _ = writeln!(out, "  end");
359    }
360
361    // Emit a shared helper for array field contains assertions — extracts string
362    // representations from each item's attributes so String.contains? works on struct lists.
363    let has_array_contains = fixtures.iter().any(|fixture| {
364        let cc = e2e_config.resolve_call_for_fixture(
365            fixture.call.as_deref(),
366            &fixture.id,
367            &fixture.resolved_category(),
368            &fixture.tags,
369            &fixture.input,
370        );
371        let fr = FieldResolver::new(
372            e2e_config.effective_fields(cc),
373            e2e_config.effective_fields_optional(cc),
374            e2e_config.effective_result_fields(cc),
375            e2e_config.effective_fields_array(cc),
376            &std::collections::HashSet::new(),
377        );
378        fixture.assertions.iter().any(|a| {
379            matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
380                && a.field
381                    .as_deref()
382                    .is_some_and(|f| !f.is_empty() && fr.is_array(fr.resolve(f)))
383        })
384    });
385    if has_array_contains {
386        let _ = writeln!(out);
387        let _ = writeln!(out, "  defp alef_e2e_item_texts(item) when is_binary(item), do: [item]");
388        let _ = writeln!(out, "  defp alef_e2e_item_texts(item) do");
389        let _ = writeln!(out, "    [:kind, :name, :signature, :path, :alias, :text, :source]");
390        let _ = writeln!(out, "    |> Enum.filter(&Map.has_key?(item, &1))");
391        let _ = writeln!(out, "    |> Enum.flat_map(fn attr ->");
392        let _ = writeln!(out, "      case Map.get(item, attr) do");
393        let _ = writeln!(out, "        nil -> []");
394        let _ = writeln!(
395            out,
396            "        atom when is_atom(atom) -> [atom |> to_string() |> String.capitalize()]"
397        );
398        let _ = writeln!(out, "        str -> [inspect(str)]");
399        let _ = writeln!(out, "      end");
400        let _ = writeln!(out, "    end)");
401        let _ = writeln!(out, "  end");
402    }
403
404    let _ = writeln!(out);
405
406    for (i, fixture) in fixtures.iter().enumerate() {
407        if let Some(http) = &fixture.http {
408            render_http_test_case(&mut out, fixture, http);
409        } else {
410            render_test_case(
411                &mut out,
412                fixture,
413                e2e_config,
414                module_path,
415                function_name,
416                result_var,
417                args,
418                options_type,
419                options_default_fn,
420                enum_fields,
421                handle_struct_type,
422                handle_atom_list_fields,
423                adapters,
424            );
425        }
426        if i + 1 < fixtures.len() {
427            let _ = writeln!(out);
428        }
429    }
430
431    let _ = writeln!(out, "end");
432    out
433}
434
435// ---------------------------------------------------------------------------
436// HTTP test rendering
437// ---------------------------------------------------------------------------
438
439/// HTTP methods that Finch (Req's underlying HTTP client) does not support.
440/// Tests using these methods are emitted with `@tag :skip` so they don't fail.
441const FINCH_UNSUPPORTED_METHODS: &[&str] = &["TRACE", "CONNECT"];
442
443/// HTTP methods that Req exposes as convenience functions.
444/// All others must be called via `Req.request(method: :METHOD, ...)`.
445const REQ_CONVENIENCE_METHODS: &[&str] = &["get", "post", "put", "patch", "delete", "head"];
446
447/// Thin renderer that emits ExUnit `describe` + `test` blocks targeting a mock
448/// server via `Req`. Satisfies [`client::TestClientRenderer`] so the shared
449/// [`client::http_call::render_http_test`] driver drives the call sequence.
450struct ElixirTestClientRenderer<'a> {
451    /// The fixture id is needed in [`render_call`] to build the mock server URL
452    /// (`mock_server_url()/fixtures/<id>`).
453    fixture_id: &'a str,
454    /// Expected response status, needed to disable Req's redirect-following for 3xx.
455    expected_status: u16,
456}
457
458impl<'a> client::TestClientRenderer for ElixirTestClientRenderer<'a> {
459    fn language_name(&self) -> &'static str {
460        "elixir"
461    }
462
463    /// Emit `describe "{fn_name}" do` + inner `test "METHOD PATH - description" do`.
464    ///
465    /// When `skip_reason` is `Some`, emit `@tag :skip` before the test block so
466    /// ExUnit skips it; the shared driver short-circuits before emitting any
467    /// assertions and then calls `render_test_close` for symmetry.
468    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
469        let escaped_description = description.replace('"', "\\\"");
470        let _ = writeln!(out, "  describe \"{fn_name}\" do");
471        if skip_reason.is_some() {
472            let _ = writeln!(out, "    @tag :skip");
473        }
474        let _ = writeln!(out, "    test \"{escaped_description}\" do");
475    }
476
477    /// Close the inner `test` block and the outer `describe` block.
478    fn render_test_close(&self, out: &mut String) {
479        let _ = writeln!(out, "    end");
480        let _ = writeln!(out, "  end");
481    }
482
483    /// Emit a `Req` request to the mock server using `mock_server_url()/fixtures/<id>`.
484    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
485        let method = ctx.method.to_lowercase();
486        let mut opts: Vec<String> = Vec::new();
487
488        if let Some(body) = ctx.body {
489            let elixir_val = json_to_elixir(body);
490            opts.push(format!("json: {elixir_val}"));
491        }
492
493        if !ctx.headers.is_empty() {
494            let header_pairs: Vec<String> = ctx
495                .headers
496                .iter()
497                .map(|(k, v)| format!("{{\"{}\", \"{}\"}}", escape_elixir(k), escape_elixir(v)))
498                .collect();
499            opts.push(format!("headers: [{}]", header_pairs.join(", ")));
500        }
501
502        if !ctx.cookies.is_empty() {
503            let cookie_str = ctx
504                .cookies
505                .iter()
506                .map(|(k, v)| format!("{k}={v}"))
507                .collect::<Vec<_>>()
508                .join("; ");
509            opts.push(format!("headers: [{{\"cookie\", \"{}\"}}]", escape_elixir(&cookie_str)));
510        }
511
512        if !ctx.query_params.is_empty() {
513            let pairs: Vec<String> = ctx
514                .query_params
515                .iter()
516                .map(|(k, v)| {
517                    let val_str = match v {
518                        serde_json::Value::String(s) => s.clone(),
519                        other => other.to_string(),
520                    };
521                    format!("{{\"{}\", \"{}\"}}", escape_elixir(k), escape_elixir(&val_str))
522                })
523                .collect();
524            opts.push(format!("params: [{}]", pairs.join(", ")));
525        }
526
527        // When the expected response is a redirect (3xx), disable automatic redirect
528        // following so the test can assert the redirect status and Location header.
529        if (300..400).contains(&self.expected_status) {
530            opts.push("redirect: false".to_string());
531        }
532
533        let fixture_id = escape_elixir(self.fixture_id);
534        let url_expr = format!("\"#{{mock_server_url()}}/fixtures/{fixture_id}\"");
535
536        if REQ_CONVENIENCE_METHODS.contains(&method.as_str()) {
537            if opts.is_empty() {
538                let _ = writeln!(out, "      {{:ok, response}} = Req.{method}(url: {url_expr})");
539            } else {
540                let opts_str = opts.join(", ");
541                let _ = writeln!(
542                    out,
543                    "      {{:ok, response}} = Req.{method}(url: {url_expr}, {opts_str})"
544                );
545            }
546        } else {
547            opts.insert(0, format!("method: :{method}"));
548            opts.insert(1, format!("url: {url_expr}"));
549            let opts_str = opts.join(", ");
550            let _ = writeln!(out, "      {{:ok, response}} = Req.request({opts_str})");
551        }
552    }
553
554    fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
555        let _ = writeln!(out, "      assert {response_var}.status == {status}");
556    }
557
558    /// Emit a header assertion.
559    ///
560    /// Handles the special tokens `<<present>>`, `<<absent>>`, `<<uuid>>`.
561    /// Skips the `connection` header (hop-by-hop, stripped by Req/Mint).
562    fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
563        let header_key = name.to_lowercase();
564        // Req (via Mint) strips hop-by-hop headers; asserting on them is meaningless.
565        if header_key == "connection" {
566            return;
567        }
568        let key_lit = format!("\"{}\"", escape_elixir(&header_key));
569        let get_header_expr = format!(
570            "Enum.find_value({response_var}.headers, fn {{k, v}} -> if String.downcase(k) == {key_lit}, do: List.first(List.wrap(v)) end)"
571        );
572        match expected {
573            "<<present>>" => {
574                let _ = writeln!(out, "      assert {get_header_expr} != nil");
575            }
576            "<<absent>>" => {
577                let _ = writeln!(out, "      assert {get_header_expr} == nil");
578            }
579            "<<uuid>>" => {
580                let var = sanitize_ident(&header_key);
581                let _ = writeln!(out, "      header_val_{var} = {get_header_expr}");
582                let _ = writeln!(
583                    out,
584                    "      assert Regex.match?(~r/^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$/i, to_string(header_val_{var}))"
585                );
586            }
587            literal => {
588                let val_lit = format!("\"{}\"", escape_elixir(literal));
589                let _ = writeln!(out, "      assert {get_header_expr} == {val_lit}");
590            }
591        }
592    }
593
594    /// Emit a full JSON body equality assertion.
595    ///
596    /// Req auto-decodes `application/json` bodies; when the response body is a
597    /// binary (non-JSON content type), decode it with `Jason.decode!` first.
598    fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
599        let elixir_val = json_to_elixir(expected);
600        match expected {
601            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
602                let _ = writeln!(
603                    out,
604                    "      body_decoded = if is_binary({response_var}.body), do: Jason.decode!({response_var}.body), else: {response_var}.body"
605                );
606                let _ = writeln!(out, "      assert body_decoded == {elixir_val}");
607            }
608            _ => {
609                let _ = writeln!(out, "      assert {response_var}.body == {elixir_val}");
610            }
611        }
612    }
613
614    /// Emit partial body assertions: one assertion per key in `expected`.
615    fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
616        if let Some(obj) = expected.as_object() {
617            let _ = writeln!(
618                out,
619                "      decoded_body = if is_binary({response_var}.body), do: Jason.decode!({response_var}.body), else: {response_var}.body"
620            );
621            for (key, val) in obj {
622                let key_lit = format!("\"{}\"", escape_elixir(key));
623                let elixir_val = json_to_elixir(val);
624                let _ = writeln!(out, "      assert decoded_body[{key_lit}] == {elixir_val}");
625            }
626        }
627    }
628
629    /// Emit validation-error assertions, checking each expected `msg` appears in
630    /// the encoded response body.
631    fn render_assert_validation_errors(
632        &self,
633        out: &mut String,
634        response_var: &str,
635        errors: &[ValidationErrorExpectation],
636    ) {
637        for err in errors {
638            let msg_lit = format!("\"{}\"", escape_elixir(&err.msg));
639            let _ = writeln!(
640                out,
641                "      assert String.contains?(Jason.encode!({response_var}.body), {msg_lit})"
642            );
643        }
644    }
645}
646
647/// Render an ExUnit `describe` + `test` block for an HTTP server test fixture.
648///
649/// Delegates to [`client::http_call::render_http_test`] after the one
650/// Elixir-specific pre-condition: HTTP methods unsupported by Finch (the
651/// underlying Req adapter) are emitted with `@tag :skip` directly.
652fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
653    let method = http.request.method.to_uppercase();
654
655    // Finch does not support TRACE/CONNECT — emit a skipped test stub directly
656    // rather than routing through the shared driver, which would assert on the
657    // response and fail.
658    if FINCH_UNSUPPORTED_METHODS.contains(&method.as_str()) {
659        let test_name = sanitize_ident(&fixture.id);
660        let test_label = fixture.id.replace('"', "\\\"");
661        let path = &http.request.path;
662        let _ = writeln!(out, "  describe \"{test_name}\" do");
663        let _ = writeln!(out, "    @tag :skip");
664        let _ = writeln!(out, "    test \"{method} {path} - {test_label}\" do");
665        let _ = writeln!(out, "    end");
666        let _ = writeln!(out, "  end");
667        return;
668    }
669
670    let renderer = ElixirTestClientRenderer {
671        fixture_id: &fixture.id,
672        expected_status: http.expected_response.status_code,
673    };
674    client::http_call::render_http_test(out, &renderer, fixture);
675}
676
677// ---------------------------------------------------------------------------
678// Function-call test rendering
679// ---------------------------------------------------------------------------
680
681#[allow(clippy::too_many_arguments)]
682fn render_test_case(
683    out: &mut String,
684    fixture: &Fixture,
685    e2e_config: &E2eConfig,
686    default_module_path: &str,
687    default_function_name: &str,
688    default_result_var: &str,
689    args: &[crate::config::ArgMapping],
690    options_type: Option<&str>,
691    options_default_fn: Option<&str>,
692    enum_fields: &HashMap<String, String>,
693    handle_struct_type: Option<&str>,
694    handle_atom_list_fields: &std::collections::HashSet<String>,
695    adapters: &[alef_core::config::extras::AdapterConfig],
696) {
697    let test_name = sanitize_ident(&fixture.id);
698    let test_label = fixture.id.replace('"', "\\\"");
699
700    // Non-HTTP non-mock_response fixtures (e.g. AsyncAPI, WebSocket, OpenRPC
701    // protocol-only fixtures) cannot be tested via the configured `[e2e.call]`
702    // function when the binding does not expose it. Emit a documented `@tag :skip`
703    // test so the suite stays compilable. HTTP fixtures dispatch via render_http_test_case
704    // and never reach here.
705    if fixture.mock_response.is_none() && !fixture_has_elixir_callable(fixture, e2e_config) {
706        let _ = writeln!(out, "  describe \"{test_name}\" do");
707        let _ = writeln!(out, "    @tag :skip");
708        let _ = writeln!(out, "    test \"{test_label}\" do");
709        let _ = writeln!(
710            out,
711            "      # non-HTTP fixture: Elixir binding does not expose a callable for the configured `[e2e.call]` function"
712        );
713        let _ = writeln!(out, "      :ok");
714        let _ = writeln!(out, "    end");
715        let _ = writeln!(out, "  end");
716        return;
717    }
718
719    // Resolve per-fixture call config (falls back to default if fixture.call is None).
720    let call_config = e2e_config.resolve_call_for_fixture(
721        fixture.call.as_deref(),
722        &fixture.id,
723        &fixture.resolved_category(),
724        &fixture.tags,
725        &fixture.input,
726    );
727    // Build per-call field resolver using the effective field sets for this call.
728    let call_field_resolver = FieldResolver::new(
729        e2e_config.effective_fields(call_config),
730        e2e_config.effective_fields_optional(call_config),
731        e2e_config.effective_result_fields(call_config),
732        e2e_config.effective_fields_array(call_config),
733        &std::collections::HashSet::new(),
734    );
735    let field_resolver = &call_field_resolver;
736    let lang = "elixir";
737    let call_overrides = call_config.overrides.get(lang);
738
739    // Check if the function is excluded from the Elixir binding (e.g., batch functions
740    // that require unsafe NIF tuple marshalling). Emit a skipped test with rationale.
741    let base_fn = call_overrides
742        .and_then(|o| o.function.as_ref())
743        .cloned()
744        .unwrap_or_else(|| call_config.function.clone());
745    if base_fn.starts_with("batch_extract_") {
746        let _ = writeln!(
747            out,
748            "  describe \"{test_name}\" do",
749            test_name = sanitize_ident(&fixture.id)
750        );
751        let _ = writeln!(out, "    @tag :skip");
752        let _ = writeln!(
753            out,
754            "    test \"{test_label}\" do",
755            test_label = fixture.id.replace('"', "\\\"")
756        );
757        let _ = writeln!(
758            out,
759            "      # batch functions excluded from Elixir binding: unsafe NIF tuple marshalling"
760        );
761        let _ = writeln!(out, "      :ok");
762        let _ = writeln!(out, "    end");
763        let _ = writeln!(out, "  end");
764        return;
765    }
766
767    // Compute module_path and function_name from the resolved call config,
768    // applying Elixir-specific PascalCase conversion.
769    let (module_path, function_name, result_var) = if fixture.call.is_some() {
770        let raw_module = call_overrides
771            .and_then(|o| o.module.as_ref())
772            .cloned()
773            .unwrap_or_else(|| call_config.module.clone());
774        let resolved_module = if raw_module.contains('.') || raw_module.chars().next().is_some_and(|c| c.is_uppercase())
775        {
776            raw_module.clone()
777        } else {
778            elixir_module_name(&raw_module)
779        };
780        let resolved_fn = if call_config.r#async && !base_fn.ends_with("_async") && !base_fn.ends_with("_stream") {
781            format!("{base_fn}_async")
782        } else {
783            base_fn
784        };
785        (resolved_module, resolved_fn, call_config.result_var.clone())
786    } else {
787        (
788            default_module_path.to_string(),
789            default_function_name.to_string(),
790            default_result_var.to_string(),
791        )
792    };
793
794    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
795    // Validation-category fixtures expect engine creation itself to fail (bad config).
796    // Other expects_error fixtures (e.g. error_*) construct a valid engine and expect the
797    // *operation under test* to fail. We need different shapes for these two cases.
798    let validation_creation_failure = expects_error && fixture.resolved_category() == "validation";
799
800    // When the fixture uses a named call, use the args and options from that call's config.
801    let (
802        effective_args,
803        effective_options_type,
804        effective_options_default_fn,
805        effective_enum_fields,
806        effective_handle_struct_type,
807        effective_handle_atom_list_fields,
808    );
809    let empty_enum_fields_local: HashMap<String, String>;
810    let empty_atom_fields_local: std::collections::HashSet<String>;
811    let (
812        resolved_args,
813        resolved_options_type,
814        resolved_options_default_fn,
815        resolved_enum_fields_ref,
816        resolved_handle_struct_type,
817        resolved_handle_atom_list_fields_ref,
818    ) = if fixture.call.is_some() {
819        let co = call_config.overrides.get(lang);
820        effective_args = call_config.args.as_slice();
821        effective_options_type = co.and_then(|o| o.options_type.as_deref());
822        effective_options_default_fn = co.and_then(|o| o.options_via.as_deref());
823        empty_enum_fields_local = HashMap::new();
824        effective_enum_fields = co.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields_local);
825        effective_handle_struct_type = co.and_then(|o| o.handle_struct_type.as_deref());
826        empty_atom_fields_local = std::collections::HashSet::new();
827        effective_handle_atom_list_fields = co
828            .map(|o| &o.handle_atom_list_fields)
829            .unwrap_or(&empty_atom_fields_local);
830        (
831            effective_args,
832            effective_options_type,
833            effective_options_default_fn,
834            effective_enum_fields,
835            effective_handle_struct_type,
836            effective_handle_atom_list_fields,
837        )
838    } else {
839        (
840            args as &[_],
841            options_type,
842            options_default_fn,
843            enum_fields,
844            handle_struct_type,
845            handle_atom_list_fields,
846        )
847    };
848
849    let test_documents_path = e2e_config.test_documents_relative_from(0);
850    let adapter_request_type: Option<String> = adapters
851        .iter()
852        .find(|a| a.name == call_config.function.as_str())
853        .and_then(|a| a.request_type.as_deref())
854        .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
855    let (mut setup_lines, args_str) = build_args_and_setup(
856        &fixture.input,
857        resolved_args,
858        &module_path,
859        resolved_options_type,
860        resolved_options_default_fn,
861        resolved_enum_fields_ref,
862        fixture,
863        resolved_handle_struct_type,
864        resolved_handle_atom_list_fields_ref,
865        &test_documents_path,
866        adapter_request_type.as_deref(),
867    );
868
869    // Build visitor if present — it will be injected into the options map.
870    let visitor_var = fixture
871        .visitor
872        .as_ref()
873        .map(|visitor_spec| build_elixir_visitor(&mut setup_lines, visitor_spec));
874
875    // If we have a visitor and the args contain a nil for options, replace it with a map
876    // containing the visitor. The fixture.visitor is already set above.
877    let final_args = if let Some(ref visitor_var) = visitor_var {
878        // Parse args_str to handle injection properly.
879        // Since we're dealing with a 2-arg function (html, options), and options might be nil,
880        // we need to inject visitor into the options.
881        let parts: Vec<&str> = args_str.split(", ").collect();
882        if parts.len() == 2 && parts[1] == "nil" {
883            // Replace nil with %{visitor: visitor}
884            format!("{}, %{{visitor: {}}}", parts[0], visitor_var)
885        } else if parts.len() == 2 {
886            // Options is a variable (e.g., "options") — add visitor to it
887            setup_lines.push(format!(
888                "{} = Map.put({}, :visitor, {})",
889                parts[1], parts[1], visitor_var
890            ));
891            args_str
892        } else if parts.len() == 1 {
893            // Only HTML provided — create options map with just visitor
894            format!("{}, %{{visitor: {}}}", parts[0], visitor_var)
895        } else {
896            args_str
897        }
898    } else {
899        args_str
900    };
901
902    // Client factory: when configured, create a client and pass it as the first argument.
903    let client_factory = call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
904        e2e_config
905            .call
906            .overrides
907            .get("elixir")
908            .and_then(|o| o.client_factory.as_deref())
909    });
910
911    // Append per-call extra_args (e.g. trailing `nil` for `list_files(client, query)`)
912    // so Elixir matches the binding's positional arity. Mirrors the same override the
913    // Ruby/Go/Node codegens already honor.
914    let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
915    let final_args_with_extras = if extra_args.is_empty() {
916        final_args
917    } else if final_args.is_empty() {
918        extra_args.join(", ")
919    } else {
920        format!("{final_args}, {}", extra_args.join(", "))
921    };
922
923    // Prefix the client variable to the args when client_factory is set.
924    let effective_args = if client_factory.is_some() {
925        if final_args_with_extras.is_empty() {
926            "client".to_string()
927        } else {
928            format!("client, {final_args_with_extras}")
929        }
930    } else {
931        final_args_with_extras
932    };
933
934    // Real-API smoke fixtures (no mock_response, no http) must be env-gated on the
935    // configured `env.api_key_var` so absent keys yield a deterministic skip rather
936    // than a spurious "no mock route" failure. Mirrors the Python conftest skip.
937    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
938    let api_key_var_opt = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
939    let needs_api_key_skip = !has_mock && api_key_var_opt.is_some();
940    // When the fixture has both a mock and an api_key_var, generate env-fallback code:
941    // use the real API when the key is set, otherwise fall back to the mock server.
942    let needs_env_fallback = has_mock && api_key_var_opt.is_some();
943
944    let _ = writeln!(out, "  describe \"{test_name}\" do");
945    let _ = writeln!(out, "    test \"{test_label}\" do");
946
947    if needs_api_key_skip {
948        let api_key_var = api_key_var_opt.unwrap_or("");
949        let _ = writeln!(out, "      if System.get_env(\"{api_key_var}\") in [nil, \"\"] do");
950        let _ = writeln!(out, "        # {api_key_var} not set — skipping live smoke test");
951        let _ = writeln!(out, "        :ok");
952        let _ = writeln!(out, "      else");
953    }
954
955    // Validation-category fixtures: engine/handle creation itself is expected to fail.
956    // Transform the first `{:ok, _} = ...` setup line into `assert {:error, _} = ...`
957    // and stop emission there, since the rest of the test body would be unreachable.
958    if validation_creation_failure {
959        let mut emitted_error_assertion = false;
960        for line in &setup_lines {
961            if !emitted_error_assertion && line.starts_with("{:ok,") {
962                if let Some(rhs) = line.split_once('=').map(|x| x.1) {
963                    let rhs = rhs.trim();
964                    let _ = writeln!(out, "      assert {{:error, _}} = {rhs}");
965                    emitted_error_assertion = true;
966                } else {
967                    let _ = writeln!(out, "      {line}");
968                }
969            } else {
970                let _ = writeln!(out, "      {line}");
971            }
972        }
973        if !emitted_error_assertion {
974            let _ = writeln!(
975                out,
976                "      assert {{:error, _}} = {module_path}.{function_name}({effective_args})"
977            );
978        }
979        if needs_api_key_skip {
980            let _ = writeln!(out, "      end");
981        }
982        let _ = writeln!(out, "    end");
983        let _ = writeln!(out, "  end");
984        return;
985    }
986
987    // Non-validation expects_error fixtures (error_*, etc.): engine creation succeeds.
988    // Emit setup as-is and assert that the *operation under test* fails. The
989    // call body still references `client` (e.g. `defaultclient_chat_async(client, …)`),
990    // so we must emit the same `{:ok, client} = create_client(...)` line that the
991    // non-error path below uses — without it the generated test fails to compile
992    // with `undefined variable "client"`.
993    if expects_error {
994        for line in &setup_lines {
995            let _ = writeln!(out, "      {line}");
996        }
997        if let Some(factory) = client_factory {
998            let fixture_id = &fixture.id;
999            let base_url_expr = if fixture.has_host_root_route() {
1000                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1001                format!(
1002                    "(System.get_env(\"{env_key}\") || (System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\")"
1003                )
1004            } else {
1005                format!("(System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\"")
1006            };
1007            let _ = writeln!(
1008                out,
1009                "      {{:ok, client}} = {module_path}.{factory}(\"test-key\", base_url: {base_url_expr})"
1010            );
1011        }
1012        let _ = writeln!(
1013            out,
1014            "      assert {{:error, _}} = {module_path}.{function_name}({effective_args})"
1015        );
1016        if needs_api_key_skip {
1017            let _ = writeln!(out, "      end");
1018        }
1019        let _ = writeln!(out, "    end");
1020        let _ = writeln!(out, "  end");
1021        return;
1022    }
1023
1024    for line in &setup_lines {
1025        let _ = writeln!(out, "      {line}");
1026    }
1027
1028    // Emit client creation when client_factory is configured.
1029    if let Some(factory) = client_factory {
1030        let fixture_id = &fixture.id;
1031        if needs_env_fallback {
1032            // Fixture has both a mock and an api_key_var: use the real API when the key is
1033            // set, otherwise fall back to the mock server.
1034            let api_key_var = api_key_var_opt.unwrap_or("");
1035            let mock_url_expr = if fixture.has_host_root_route() {
1036                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1037                format!(
1038                    "System.get_env(\"{env_key}\") || (System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\""
1039                )
1040            } else {
1041                format!("(System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\"")
1042            };
1043            let _ = writeln!(out, "      api_key_val = System.get_env(\"{api_key_var}\")");
1044            let _ = writeln!(
1045                out,
1046                "      {{api_key_val, client_opts}} = if api_key_val && api_key_val != \"\" do"
1047            );
1048            let _ = writeln!(
1049                out,
1050                "        IO.puts(\"{fixture_id}: using real API ({api_key_var} is set)\")"
1051            );
1052            let _ = writeln!(out, "        {{api_key_val, []}}");
1053            let _ = writeln!(out, "      else");
1054            let _ = writeln!(
1055                out,
1056                "        IO.puts(\"{fixture_id}: using mock server ({api_key_var} not set)\")"
1057            );
1058            let _ = writeln!(out, "        {{\"test-key\", [base_url: {mock_url_expr}]}}");
1059            let _ = writeln!(out, "      end");
1060            let _ = writeln!(
1061                out,
1062                "      {{:ok, client}} = {module_path}.{factory}(api_key_val, client_opts)"
1063            );
1064        } else {
1065            let base_url_expr = if fixture.has_host_root_route() {
1066                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1067                format!(
1068                    "(System.get_env(\"{env_key}\") || (System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\")"
1069                )
1070            } else {
1071                format!("(System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\"")
1072            };
1073            let _ = writeln!(
1074                out,
1075                "      {{:ok, client}} = {module_path}.{factory}(\"test-key\", base_url: {base_url_expr})"
1076            );
1077        }
1078    }
1079
1080    // Use returns_result from the Elixir override if present, otherwise from base config
1081    let returns_result = call_overrides
1082        .and_then(|o| o.returns_result)
1083        .unwrap_or(call_config.returns_result || client_factory.is_some());
1084
1085    // Some calls (e.g. speech, file_content) return raw bytes rather than a struct.
1086    // When the call is marked `result_is_simple`, treat the bound `result` variable as
1087    // the value itself so assertions on a logical "audio"/"content" field map to the
1088    // bare binary instead of a struct accessor that doesn't exist.
1089    let result_is_simple = call_config.result_is_simple || call_overrides.is_some_and(|o| o.result_is_simple);
1090
1091    // Streaming detection (call-level `streaming` opt-out is honored).
1092    let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
1093    // For streaming fixtures the stream is bound to `result_var` first, then drained into `chunks`.
1094    let chunks_var = "chunks";
1095
1096    // If the result variable is never referenced in assertions or streaming operations,
1097    // prefix it with _ to avoid "unused variable" warnings in mix compile --warnings-as-errors.
1098    let actual_result_var = if fixture.assertions.is_empty() && !is_streaming {
1099        format!("_{result_var}")
1100    } else {
1101        result_var.to_string()
1102    };
1103
1104    if returns_result {
1105        let _ = writeln!(
1106            out,
1107            "      {{:ok, {actual_result_var}}} = {module_path}.{function_name}({effective_args})"
1108        );
1109    } else {
1110        // Non-Result function returns value directly (e.g., bool, String).
1111        let _ = writeln!(
1112            out,
1113            "      {actual_result_var} = {module_path}.{function_name}({effective_args})"
1114        );
1115    }
1116
1117    // For streaming fixtures, drain the stream into a list before asserting.
1118    if is_streaming {
1119        if let Some(collect) = crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(
1120            "elixir",
1121            &result_var,
1122            chunks_var,
1123        ) {
1124            let _ = writeln!(out, "      {collect}");
1125        }
1126    }
1127
1128    for assertion in &fixture.assertions {
1129        render_assertion(
1130            out,
1131            assertion,
1132            if is_streaming { chunks_var } else { &result_var },
1133            field_resolver,
1134            &module_path,
1135            e2e_config.effective_fields_enum(call_config),
1136            resolved_enum_fields_ref,
1137            result_is_simple,
1138            is_streaming,
1139        );
1140    }
1141
1142    if needs_api_key_skip {
1143        let _ = writeln!(out, "      end");
1144    }
1145    let _ = writeln!(out, "    end");
1146    let _ = writeln!(out, "  end");
1147}
1148
1149/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1150///
1151/// Returns `(setup_lines, args_string)`.
1152#[allow(clippy::too_many_arguments)]
1153/// Emit Elixir batch item map constructors for BatchBytesItem or BatchFileItem arrays.
1154fn emit_elixir_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1155    if let Some(items) = arr.as_array() {
1156        let item_strs: Vec<String> = items
1157            .iter()
1158            .filter_map(|item| {
1159                if let Some(obj) = item.as_object() {
1160                    match elem_type {
1161                        "BatchBytesItem" => {
1162                            let content = obj.get("content").and_then(|v| v.as_array());
1163                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1164                            let content_code = if let Some(arr) = content {
1165                                let bytes: Vec<String> =
1166                                    arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1167                                format!("<<{}>>", bytes.join(", "))
1168                            } else {
1169                                "<<>>".to_string()
1170                            };
1171                            Some(format!(
1172                                "%BatchBytesItem{{content: {}, mime_type: \"{}\"}}",
1173                                content_code, mime_type
1174                            ))
1175                        }
1176                        "BatchFileItem" => {
1177                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1178                            Some(format!("%BatchFileItem{{path: \"{}\"}}", path))
1179                        }
1180                        _ => None,
1181                    }
1182                } else {
1183                    None
1184                }
1185            })
1186            .collect();
1187        format!("[{}]", item_strs.join(", "))
1188    } else {
1189        "[]".to_string()
1190    }
1191}
1192
1193#[allow(clippy::too_many_arguments)]
1194fn build_args_and_setup(
1195    input: &serde_json::Value,
1196    args: &[crate::config::ArgMapping],
1197    module_path: &str,
1198    options_type: Option<&str>,
1199    options_default_fn: Option<&str>,
1200    enum_fields: &HashMap<String, String>,
1201    fixture: &crate::fixture::Fixture,
1202    _handle_struct_type: Option<&str>,
1203    _handle_atom_list_fields: &std::collections::HashSet<String>,
1204    test_documents_path: &str,
1205    adapter_request_type: Option<&str>,
1206) -> (Vec<String>, String) {
1207    let fixture_id = &fixture.id;
1208    if args.is_empty() {
1209        // No args config: pass the whole input only when it's non-empty.
1210        // Functions with no parameters (e.g. language_count) have empty input
1211        // and must be called with no arguments — not with `%{}`.
1212        let is_empty_input = match input {
1213            serde_json::Value::Null => true,
1214            serde_json::Value::Object(m) => m.is_empty(),
1215            _ => false,
1216        };
1217        if is_empty_input {
1218            return (Vec::new(), String::new());
1219        }
1220        return (Vec::new(), json_to_elixir(input));
1221    }
1222
1223    let mut setup_lines: Vec<String> = Vec::new();
1224    let mut parts: Vec<String> = Vec::new();
1225
1226    for arg in args {
1227        if arg.arg_type == "mock_url" {
1228            if fixture.has_host_root_route() {
1229                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1230                setup_lines.push(format!(
1231                    "{} = System.get_env(\"{env_key}\") || (System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\"",
1232                    arg.name,
1233                ));
1234            } else {
1235                setup_lines.push(format!(
1236                    "{} = (System.get_env(\"MOCK_SERVER_URL\") || \"\") <> \"/fixtures/{fixture_id}\"",
1237                    arg.name,
1238                ));
1239            }
1240            if let Some(req_type) = adapter_request_type {
1241                let req_var = format!("{}_req", arg.name);
1242                setup_lines.push(format!("{req_var} = %Kreuzcrawl.{req_type}{{url: {}}}", arg.name,));
1243                parts.push(req_var);
1244            } else {
1245                parts.push(arg.name.clone());
1246            }
1247            continue;
1248        }
1249
1250        if arg.arg_type == "handle" {
1251            // Generate a create_{name} call using {:ok, name} = ... pattern.
1252            // The NIF now accepts config as an optional JSON string (not a NifStruct/NifMap)
1253            // so that partial maps work: serde_json::from_str respects #[serde(default)].
1254            let constructor_name = format!("create_{}", arg.name.to_snake_case());
1255            let config_value = if arg.field == "input" {
1256                input
1257            } else {
1258                let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1259                input.get(field).unwrap_or(&serde_json::Value::Null)
1260            };
1261            let name = &arg.name;
1262            if config_value.is_null()
1263                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1264            {
1265                setup_lines.push(format!("{{:ok, {name}}} = {module_path}.{constructor_name}(nil)"));
1266            } else {
1267                // Serialize the config map to a JSON string with Jason so that Rust can
1268                // deserialize it with serde_json and apply field defaults for missing keys.
1269                let json_str = serde_json::to_string(config_value).unwrap_or_else(|_| "{}".to_string());
1270                let escaped = escape_elixir(&json_str);
1271                setup_lines.push(format!("{name}_config = \"{escaped}\""));
1272                setup_lines.push(format!(
1273                    "{{:ok, {name}}} = {module_path}.{constructor_name}({name}_config)",
1274                ));
1275            }
1276            parts.push(arg.name.clone());
1277            continue;
1278        }
1279
1280        let val = if arg.field == "input" {
1281            Some(input)
1282        } else {
1283            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1284            input.get(field)
1285        };
1286        match val {
1287            None | Some(serde_json::Value::Null) if arg.optional => {
1288                // Optional params map to the keyword-opts `opts \\ []` argument.
1289                // When the value is absent, omit the keyword entirely — the default `[]` applies.
1290                continue;
1291            }
1292            None | Some(serde_json::Value::Null) => {
1293                // Required arg with no fixture value: pass a language-appropriate default.
1294                let default_val = match arg.arg_type.as_str() {
1295                    "string" => "\"\"".to_string(),
1296                    "int" | "integer" => "0".to_string(),
1297                    "float" | "number" => "0.0".to_string(),
1298                    "bool" | "boolean" => "false".to_string(),
1299                    _ => "nil".to_string(),
1300                };
1301                parts.push(default_val);
1302            }
1303            Some(v) => {
1304                // For file_path args, prepend the path to the test_documents directory
1305                // relative to the e2e/elixir/ directory where `mix test` runs.
1306                if arg.arg_type == "file_path" {
1307                    if let Some(path_str) = v.as_str() {
1308                        let full_path = format!("{test_documents_path}/{path_str}");
1309                        let formatted = format!("\"{}\"", escape_elixir(&full_path));
1310                        if arg.optional {
1311                            parts.push(format!("{}: {formatted}", arg.name));
1312                        } else {
1313                            parts.push(formatted);
1314                        }
1315                        continue;
1316                    }
1317                }
1318                // For bytes args, use File.read! for file paths and Base.decode64! for base64.
1319                // Inline text (starts with '<', '{', '[' or contains spaces) is used as-is (UTF-8 binary).
1320                if arg.arg_type == "bytes" {
1321                    if let Some(raw) = v.as_str() {
1322                        let var_name = &arg.name;
1323                        if raw.starts_with('<') || raw.starts_with('{') || raw.starts_with('[') || raw.contains(' ') {
1324                            // Inline text — use as a binary string.
1325                            let formatted = format!("\"{}\"", escape_elixir(raw));
1326                            if arg.optional {
1327                                parts.push(format!("{}: {formatted}", arg.name));
1328                            } else {
1329                                parts.push(formatted);
1330                            }
1331                        } else {
1332                            let first = raw.chars().next().unwrap_or('\0');
1333                            let is_file_path = (first.is_ascii_alphanumeric() || first == '_')
1334                                && raw
1335                                    .find('/')
1336                                    .is_some_and(|slash_pos| slash_pos > 0 && raw[slash_pos + 1..].contains('.'));
1337                            if is_file_path {
1338                                // Looks like "dir/file.ext" — read from the
1339                                // configured test-documents directory.
1340                                let full_path = format!("{test_documents_path}/{raw}");
1341                                let escaped = escape_elixir(&full_path);
1342                                setup_lines.push(format!("{var_name} = File.read!(\"{escaped}\")"));
1343                                if arg.optional {
1344                                    parts.push(format!("{}: {var_name}", arg.name));
1345                                } else {
1346                                    parts.push(var_name.to_string());
1347                                }
1348                            } else {
1349                                // Treat as base64-encoded binary.
1350                                setup_lines.push(format!(
1351                                    "{var_name} = Base.decode64!(\"{}\", padding: false)",
1352                                    escape_elixir(raw)
1353                                ));
1354                                if arg.optional {
1355                                    parts.push(format!("{}: {var_name}", arg.name));
1356                                } else {
1357                                    parts.push(var_name.to_string());
1358                                }
1359                            }
1360                        }
1361                        continue;
1362                    }
1363                }
1364                // For json_object args with options_type+options_via, build a proper struct.
1365                if arg.arg_type == "json_object" && !v.is_null() {
1366                    if let (Some(_opts_type), Some(options_fn), Some(obj)) =
1367                        (options_type, options_default_fn, v.as_object())
1368                    {
1369                        // Add setup line to initialize options from default function.
1370                        let options_var = "options";
1371                        setup_lines.push(format!("{options_var} = {module_path}.{options_fn}()"));
1372
1373                        // For each field in the options object, add a struct update line.
1374                        for (k, vv) in obj.iter() {
1375                            let snake_key = k.to_snake_case();
1376                            let elixir_val = if let Some(_enum_type) = enum_fields.get(k) {
1377                                if let Some(s) = vv.as_str() {
1378                                    let snake_val = s.to_snake_case();
1379                                    // Use atom for enum values, not string
1380                                    format!(":{snake_val}")
1381                                } else {
1382                                    json_to_elixir(vv)
1383                                }
1384                            } else {
1385                                json_to_elixir(vv)
1386                            };
1387                            setup_lines.push(format!(
1388                                "{options_var} = %{{{options_var} | {snake_key}: {elixir_val}}}"
1389                            ));
1390                        }
1391
1392                        // Push the variable name as the argument.
1393                        // For optional json_object args with options_type, pass as positional (not keyword form)
1394                        // so they work with `convert(html, options_map)` style function signatures.
1395                        parts.push(options_var.to_string());
1396                        continue;
1397                    }
1398                    // When options_type is set but options_via is NOT, emit struct-literal form.
1399                    if let (Some(opts_type), None, Some(obj)) = (options_type, options_default_fn, v.as_object()) {
1400                        let options_var = "options";
1401                        let mut field_strs = Vec::new();
1402                        for (k, vv) in obj.iter() {
1403                            let snake_key = k.to_snake_case();
1404                            let elixir_val = if let Some(_enum_type) = enum_fields.get(k) {
1405                                if let Some(s) = vv.as_str() {
1406                                    let snake_val = s.to_snake_case();
1407                                    format!(":{snake_val}")
1408                                } else {
1409                                    json_to_elixir(vv)
1410                                }
1411                            } else {
1412                                json_to_elixir(vv)
1413                            };
1414                            field_strs.push(format!("{snake_key}: {elixir_val}"));
1415                        }
1416                        let fields = field_strs.join(", ");
1417                        setup_lines.push(format!("{options_var} = %{module_path}.{opts_type}{{{fields}}}"));
1418                        // For optional json_object args with options_type, pass as positional (not keyword form)
1419                        // so they work with `convert(html, options_map)` style function signatures.
1420                        parts.push(options_var.to_string());
1421                        continue;
1422                    }
1423                    // When element_type is set to a batch item type, wrap items with constructors.
1424                    if let Some(elem_type) = &arg.element_type {
1425                        if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1426                            let formatted = emit_elixir_batch_item_array(v, elem_type);
1427                            if arg.optional {
1428                                parts.push(format!("{}: {formatted}", arg.name));
1429                            } else {
1430                                parts.push(formatted);
1431                            }
1432                            continue;
1433                        }
1434                        // When element_type is set to a simple type (e.g. Vec<String>).
1435                        // The NIF accepts an Elixir list directly — emit one.
1436                        if v.is_array() {
1437                            let formatted = json_to_elixir(v);
1438                            if arg.optional {
1439                                parts.push(format!("{}: {formatted}", arg.name));
1440                            } else {
1441                                parts.push(formatted);
1442                            }
1443                            continue;
1444                        }
1445                    }
1446                    // When there's no options_type+options_via, the Elixir NIF expects a JSON
1447                    // string (Option<String> decoded by serde_json) rather than an Elixir map.
1448                    // Serialize the JSON value to a string literal here.
1449                    if !v.is_null() {
1450                        let json_str = serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string());
1451                        let escaped = escape_elixir(&json_str);
1452                        let formatted = format!("\"{escaped}\"");
1453                        if arg.optional {
1454                            parts.push(format!("{}: {formatted}", arg.name));
1455                        } else {
1456                            parts.push(formatted);
1457                        }
1458                        continue;
1459                    }
1460                }
1461                // Optional args use keyword-opts form: `name: value`.
1462                let elixir_val = json_to_elixir(v);
1463                if arg.optional {
1464                    parts.push(format!("{}: {elixir_val}", arg.name));
1465                } else {
1466                    parts.push(elixir_val);
1467                }
1468            }
1469        }
1470    }
1471
1472    // Separate positional and keyword args; Elixir requires all positionals before keywords
1473    let mut positional_args = Vec::new();
1474    let mut keyword_args = Vec::new();
1475    for part in parts {
1476        if part.contains(": ") && !part.starts_with('"') {
1477            keyword_args.push(part);
1478        } else {
1479            positional_args.push(part);
1480        }
1481    }
1482
1483    let mut final_args = positional_args;
1484    final_args.extend(keyword_args);
1485
1486    (setup_lines, final_args.join(", "))
1487}
1488
1489/// Returns true if the field expression is a numeric/integer expression
1490/// (e.g., a `length(...)` call) rather than a string.
1491fn is_numeric_expr(field_expr: &str) -> bool {
1492    field_expr.starts_with("length(")
1493}
1494
1495#[allow(clippy::too_many_arguments)]
1496fn render_assertion(
1497    out: &mut String,
1498    assertion: &Assertion,
1499    result_var: &str,
1500    field_resolver: &FieldResolver,
1501    module_path: &str,
1502    fields_enum: &std::collections::HashSet<String>,
1503    per_call_enum_fields: &HashMap<String, String>,
1504    result_is_simple: bool,
1505    is_streaming: bool,
1506) {
1507    // Handle synthetic / derived fields before the is_valid_for_result check
1508    // so they are never treated as struct field accesses on the result.
1509    if let Some(f) = &assertion.field {
1510        match f.as_str() {
1511            "chunks_have_content" => {
1512                let pred =
1513                    format!("Enum.all?({result_var}.chunks || [], fn c -> c.content != nil and c.content != \"\" end)");
1514                match assertion.assertion_type.as_str() {
1515                    "is_true" => {
1516                        let _ = writeln!(out, "      assert {pred}");
1517                    }
1518                    "is_false" => {
1519                        let _ = writeln!(out, "      refute {pred}");
1520                    }
1521                    _ => {
1522                        let _ = writeln!(
1523                            out,
1524                            "      # skipped: unsupported assertion type on synthetic field '{f}'"
1525                        );
1526                    }
1527                }
1528                return;
1529            }
1530            "chunks_have_embeddings" => {
1531                let pred = format!(
1532                    "Enum.all?({result_var}.chunks || [], fn c -> c.embedding != nil and c.embedding != [] end)"
1533                );
1534                match assertion.assertion_type.as_str() {
1535                    "is_true" => {
1536                        let _ = writeln!(out, "      assert {pred}");
1537                    }
1538                    "is_false" => {
1539                        let _ = writeln!(out, "      refute {pred}");
1540                    }
1541                    _ => {
1542                        let _ = writeln!(
1543                            out,
1544                            "      # skipped: unsupported assertion type on synthetic field '{f}'"
1545                        );
1546                    }
1547                }
1548                return;
1549            }
1550            // ---- EmbedResponse virtual fields ----
1551            // embed_texts returns [[float]] in Elixir — no wrapper struct.
1552            // result_var is the embedding matrix; use it directly.
1553            "embeddings" => {
1554                match assertion.assertion_type.as_str() {
1555                    "count_equals" => {
1556                        if let Some(val) = &assertion.value {
1557                            let ex_val = json_to_elixir(val);
1558                            let _ = writeln!(out, "      assert length({result_var}) == {ex_val}");
1559                        }
1560                    }
1561                    "count_min" => {
1562                        if let Some(val) = &assertion.value {
1563                            let ex_val = json_to_elixir(val);
1564                            let _ = writeln!(out, "      assert length({result_var}) >= {ex_val}");
1565                        }
1566                    }
1567                    "not_empty" => {
1568                        let _ = writeln!(out, "      assert {result_var} != []");
1569                    }
1570                    "is_empty" => {
1571                        let _ = writeln!(out, "      assert {result_var} == []");
1572                    }
1573                    _ => {
1574                        let _ = writeln!(
1575                            out,
1576                            "      # skipped: unsupported assertion type on synthetic field 'embeddings'"
1577                        );
1578                    }
1579                }
1580                return;
1581            }
1582            "embedding_dimensions" => {
1583                let expr = format!("(if {result_var} == [], do: 0, else: length(hd({result_var})))");
1584                match assertion.assertion_type.as_str() {
1585                    "equals" => {
1586                        if let Some(val) = &assertion.value {
1587                            let ex_val = json_to_elixir(val);
1588                            let _ = writeln!(out, "      assert {expr} == {ex_val}");
1589                        }
1590                    }
1591                    "greater_than" => {
1592                        if let Some(val) = &assertion.value {
1593                            let ex_val = json_to_elixir(val);
1594                            let _ = writeln!(out, "      assert {expr} > {ex_val}");
1595                        }
1596                    }
1597                    _ => {
1598                        let _ = writeln!(
1599                            out,
1600                            "      # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'"
1601                        );
1602                    }
1603                }
1604                return;
1605            }
1606            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1607                let pred = match f.as_str() {
1608                    "embeddings_valid" => {
1609                        format!("Enum.all?({result_var}, fn e -> e != [] end)")
1610                    }
1611                    "embeddings_finite" => {
1612                        format!("Enum.all?({result_var}, fn e -> Enum.all?(e, fn v -> is_float(v) and v == v end) end)")
1613                    }
1614                    "embeddings_non_zero" => {
1615                        format!("Enum.all?({result_var}, fn e -> Enum.any?(e, fn v -> v != 0.0 end) end)")
1616                    }
1617                    "embeddings_normalized" => {
1618                        format!(
1619                            "Enum.all?({result_var}, fn e -> n = Enum.reduce(e, 0.0, fn v, acc -> acc + v * v end); abs(n - 1.0) < 1.0e-3 end)"
1620                        )
1621                    }
1622                    _ => unreachable!(),
1623                };
1624                match assertion.assertion_type.as_str() {
1625                    "is_true" => {
1626                        let _ = writeln!(out, "      assert {pred}");
1627                    }
1628                    "is_false" => {
1629                        let _ = writeln!(out, "      refute {pred}");
1630                    }
1631                    _ => {
1632                        let _ = writeln!(
1633                            out,
1634                            "      # skipped: unsupported assertion type on synthetic field '{f}'"
1635                        );
1636                    }
1637                }
1638                return;
1639            }
1640            // ---- keywords / keywords_count ----
1641            // Elixir ExtractionResult does not expose extracted_keywords; skip.
1642            "keywords" | "keywords_count" => {
1643                let _ = writeln!(
1644                    out,
1645                    "      # skipped: field '{f}' not available on Elixir ExtractionResult"
1646                );
1647                return;
1648            }
1649            _ => {}
1650        }
1651    }
1652
1653    // Streaming virtual fields: intercept before is_valid_for_result so they are
1654    // never skipped.  These fields resolve against the `chunks` collected-list variable.
1655    if is_streaming {
1656        if let Some(f) = &assertion.field {
1657            if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1658                if let Some(expr) =
1659                    crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "elixir", result_var)
1660                {
1661                    match assertion.assertion_type.as_str() {
1662                        "count_min" => {
1663                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1664                                let _ = writeln!(out, "      assert length({expr}) >= {n}");
1665                            }
1666                        }
1667                        "count_equals" => {
1668                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1669                                let _ = writeln!(out, "      assert length({expr}) == {n}");
1670                            }
1671                        }
1672                        "equals" => {
1673                            if let Some(serde_json::Value::String(s)) = &assertion.value {
1674                                let escaped = escape_elixir(s);
1675                                let _ = writeln!(out, "      assert {expr} == \"{escaped}\"");
1676                            } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1677                                let _ = writeln!(out, "      assert {expr} == {n}");
1678                            }
1679                        }
1680                        "not_empty" => {
1681                            let _ = writeln!(out, "      assert {expr} != []");
1682                        }
1683                        "is_empty" => {
1684                            let _ = writeln!(out, "      assert {expr} == []");
1685                        }
1686                        "is_true" => {
1687                            let _ = writeln!(out, "      assert {expr}");
1688                        }
1689                        "is_false" => {
1690                            let _ = writeln!(out, "      refute {expr}");
1691                        }
1692                        "greater_than" => {
1693                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1694                                let _ = writeln!(out, "      assert {expr} > {n}");
1695                            }
1696                        }
1697                        "greater_than_or_equal" => {
1698                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1699                                let _ = writeln!(out, "      assert {expr} >= {n}");
1700                            }
1701                        }
1702                        "contains" => {
1703                            if let Some(serde_json::Value::String(s)) = &assertion.value {
1704                                let escaped = escape_elixir(s);
1705                                let _ = writeln!(out, "      assert String.contains?({expr}, \"{escaped}\")");
1706                            }
1707                        }
1708                        _ => {
1709                            let _ = writeln!(
1710                                out,
1711                                "      # streaming field '{f}': assertion type '{}' not rendered",
1712                                assertion.assertion_type
1713                            );
1714                        }
1715                    }
1716                }
1717                return;
1718            }
1719        }
1720    }
1721
1722    // Skip assertions on fields that don't exist on the result type.
1723    // When `result_is_simple`, the bound result is the value itself (e.g. a binary)
1724    // so `is_valid_for_result` is meaningless — fall through and emit the assertion
1725    // against the bare result_var below.
1726    if !result_is_simple {
1727        if let Some(f) = &assertion.field {
1728            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1729                let _ = writeln!(out, "      # skipped: field '{f}' not available on result type");
1730                return;
1731            }
1732        }
1733    }
1734
1735    // result_is_simple: when the call returns the value itself (e.g. a binary for
1736    // `speech` / `file_content`), bypass the field accessor and assert against the
1737    // bound `result` variable directly.
1738    let field_expr = if result_is_simple {
1739        result_var.to_string()
1740    } else {
1741        match &assertion.field {
1742            Some(f) if !f.is_empty() => field_resolver.accessor(f, "elixir", result_var),
1743            _ => result_var.to_string(),
1744        }
1745    };
1746
1747    // Only wrap in String.trim/0 when the expression is actually a string.
1748    // Numeric expressions (e.g., length(...)) must not be wrapped.
1749    let is_numeric = is_numeric_expr(&field_expr);
1750    // Detect whether the field resolves to an enum type. Rustler binds Rust
1751    // enums as atoms (e.g. `:stop`), so calling `String.trim/1` on them raises
1752    // FunctionClauseError. Coerce via `to_string/1` before string ops. Look up
1753    // both the global `[crates.e2e] fields_enum` set AND the per-call override
1754    // `[crates.e2e.calls.<x>.overrides.elixir] enum_fields = { ... }` so a single
1755    // config entry already populated for the C#/Java/Python sides applies here.
1756    let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1757        let resolved = field_resolver.resolve(f);
1758        fields_enum.contains(f)
1759            || fields_enum.contains(resolved)
1760            || per_call_enum_fields.contains_key(f)
1761            || per_call_enum_fields.contains_key(resolved)
1762    });
1763    let coerced_field_expr = if field_is_enum {
1764        format!("to_string({field_expr})")
1765    } else {
1766        field_expr.clone()
1767    };
1768    let trimmed_field_expr = if is_numeric {
1769        field_expr.clone()
1770    } else {
1771        format!("String.trim({coerced_field_expr})")
1772    };
1773
1774    // Detect whether the assertion field resolves to an array type so that
1775    // contains assertions can iterate items instead of calling to_string on the list.
1776    let field_is_array = assertion
1777        .field
1778        .as_deref()
1779        .filter(|f| !f.is_empty())
1780        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1781
1782    match assertion.assertion_type.as_str() {
1783        "equals" => {
1784            if let Some(expected) = &assertion.value {
1785                let elixir_val = json_to_elixir(expected);
1786                // Apply String.trim only for string comparisons, not numeric ones.
1787                let is_string_expected = expected.is_string();
1788                if is_string_expected && !is_numeric {
1789                    let _ = writeln!(out, "      assert {trimmed_field_expr} == {elixir_val}");
1790                } else if field_is_enum {
1791                    let _ = writeln!(out, "      assert {coerced_field_expr} == {elixir_val}");
1792                } else {
1793                    let _ = writeln!(out, "      assert {field_expr} == {elixir_val}");
1794                }
1795            }
1796        }
1797        "contains" => {
1798            if let Some(expected) = &assertion.value {
1799                let elixir_val = json_to_elixir(expected);
1800                if field_is_array && expected.is_string() {
1801                    // List of structs: check if any item's text representation contains the value.
1802                    let _ = writeln!(
1803                        out,
1804                        "      assert Enum.any?({field_expr}, fn item -> Enum.any?(alef_e2e_item_texts(item), &String.contains?(&1, {elixir_val})) end)"
1805                    );
1806                } else {
1807                    // Use to_string() to handle atoms (enums) as well as strings
1808                    let _ = writeln!(
1809                        out,
1810                        "      assert String.contains?(to_string({field_expr}), {elixir_val})"
1811                    );
1812                }
1813            }
1814        }
1815        "contains_all" => {
1816            if let Some(values) = &assertion.values {
1817                for val in values {
1818                    let elixir_val = json_to_elixir(val);
1819                    if field_is_array && val.is_string() {
1820                        let _ = writeln!(
1821                            out,
1822                            "      assert Enum.any?({field_expr}, fn item -> Enum.any?(alef_e2e_item_texts(item), &String.contains?(&1, {elixir_val})) end)"
1823                        );
1824                    } else {
1825                        let _ = writeln!(
1826                            out,
1827                            "      assert String.contains?(to_string({field_expr}), {elixir_val})"
1828                        );
1829                    }
1830                }
1831            }
1832        }
1833        "not_contains" => {
1834            if let Some(expected) = &assertion.value {
1835                let elixir_val = json_to_elixir(expected);
1836                if field_is_array && expected.is_string() {
1837                    let _ = writeln!(
1838                        out,
1839                        "      refute Enum.any?({field_expr}, fn item -> Enum.any?(alef_e2e_item_texts(item), &String.contains?(&1, {elixir_val})) end)"
1840                    );
1841                } else {
1842                    let _ = writeln!(
1843                        out,
1844                        "      refute String.contains?(to_string({field_expr}), {elixir_val})"
1845                    );
1846                }
1847            }
1848        }
1849        "not_empty" => {
1850            let _ = writeln!(out, "      assert {field_expr} != \"\"");
1851        }
1852        "is_empty" => {
1853            if is_numeric {
1854                // length(...) == 0
1855                let _ = writeln!(out, "      assert {field_expr} == 0");
1856            } else {
1857                // Handle nil (None) as empty
1858                let _ = writeln!(out, "      assert is_nil({field_expr}) or {trimmed_field_expr} == \"\"");
1859            }
1860        }
1861        "contains_any" => {
1862            if let Some(values) = &assertion.values {
1863                let items: Vec<String> = values.iter().map(json_to_elixir).collect();
1864                let list_str = items.join(", ");
1865                let _ = writeln!(
1866                    out,
1867                    "      assert Enum.any?([{list_str}], fn v -> String.contains?(to_string({field_expr}), v) end)"
1868                );
1869            }
1870        }
1871        "greater_than" => {
1872            if let Some(val) = &assertion.value {
1873                let elixir_val = json_to_elixir(val);
1874                let _ = writeln!(out, "      assert {field_expr} > {elixir_val}");
1875            }
1876        }
1877        "less_than" => {
1878            if let Some(val) = &assertion.value {
1879                let elixir_val = json_to_elixir(val);
1880                let _ = writeln!(out, "      assert {field_expr} < {elixir_val}");
1881            }
1882        }
1883        "greater_than_or_equal" => {
1884            if let Some(val) = &assertion.value {
1885                let elixir_val = json_to_elixir(val);
1886                let _ = writeln!(out, "      assert {field_expr} >= {elixir_val}");
1887            }
1888        }
1889        "less_than_or_equal" => {
1890            if let Some(val) = &assertion.value {
1891                let elixir_val = json_to_elixir(val);
1892                let _ = writeln!(out, "      assert {field_expr} <= {elixir_val}");
1893            }
1894        }
1895        "starts_with" => {
1896            if let Some(expected) = &assertion.value {
1897                let elixir_val = json_to_elixir(expected);
1898                let _ = writeln!(out, "      assert String.starts_with?({field_expr}, {elixir_val})");
1899            }
1900        }
1901        "ends_with" => {
1902            if let Some(expected) = &assertion.value {
1903                let elixir_val = json_to_elixir(expected);
1904                let _ = writeln!(out, "      assert String.ends_with?({field_expr}, {elixir_val})");
1905            }
1906        }
1907        "min_length" => {
1908            if let Some(val) = &assertion.value {
1909                if let Some(n) = val.as_u64() {
1910                    let _ = writeln!(out, "      assert String.length({field_expr}) >= {n}");
1911                }
1912            }
1913        }
1914        "max_length" => {
1915            if let Some(val) = &assertion.value {
1916                if let Some(n) = val.as_u64() {
1917                    let _ = writeln!(out, "      assert String.length({field_expr}) <= {n}");
1918                }
1919            }
1920        }
1921        "count_min" => {
1922            if let Some(val) = &assertion.value {
1923                if let Some(n) = val.as_u64() {
1924                    let _ = writeln!(out, "      assert length({field_expr}) >= {n}");
1925                }
1926            }
1927        }
1928        "count_equals" => {
1929            if let Some(val) = &assertion.value {
1930                if let Some(n) = val.as_u64() {
1931                    let _ = writeln!(out, "      assert length({field_expr}) == {n}");
1932                }
1933            }
1934        }
1935        "is_true" => {
1936            let _ = writeln!(out, "      assert {field_expr} == true");
1937        }
1938        "is_false" => {
1939            let _ = writeln!(out, "      assert {field_expr} == false");
1940        }
1941        "method_result" => {
1942            if let Some(method_name) = &assertion.method {
1943                let call_expr = build_elixir_method_call(result_var, method_name, assertion.args.as_ref(), module_path);
1944                let check = assertion.check.as_deref().unwrap_or("is_true");
1945                match check {
1946                    "equals" => {
1947                        if let Some(val) = &assertion.value {
1948                            let elixir_val = json_to_elixir(val);
1949                            let _ = writeln!(out, "      assert {call_expr} == {elixir_val}");
1950                        }
1951                    }
1952                    "is_true" => {
1953                        let _ = writeln!(out, "      assert {call_expr} == true");
1954                    }
1955                    "is_false" => {
1956                        let _ = writeln!(out, "      assert {call_expr} == false");
1957                    }
1958                    "greater_than_or_equal" => {
1959                        if let Some(val) = &assertion.value {
1960                            let n = val.as_u64().unwrap_or(0);
1961                            let _ = writeln!(out, "      assert {call_expr} >= {n}");
1962                        }
1963                    }
1964                    "count_min" => {
1965                        if let Some(val) = &assertion.value {
1966                            let n = val.as_u64().unwrap_or(0);
1967                            let _ = writeln!(out, "      assert length({call_expr}) >= {n}");
1968                        }
1969                    }
1970                    "contains" => {
1971                        if let Some(val) = &assertion.value {
1972                            let elixir_val = json_to_elixir(val);
1973                            let _ = writeln!(out, "      assert String.contains?({call_expr}, {elixir_val})");
1974                        }
1975                    }
1976                    "is_error" => {
1977                        let _ = writeln!(out, "      assert_raise RuntimeError, fn -> {call_expr} end");
1978                    }
1979                    other_check => {
1980                        panic!("Elixir e2e generator: unsupported method_result check type: {other_check}");
1981                    }
1982                }
1983            } else {
1984                panic!("Elixir e2e generator: method_result assertion missing 'method' field");
1985            }
1986        }
1987        "matches_regex" => {
1988            if let Some(expected) = &assertion.value {
1989                let elixir_val = json_to_elixir(expected);
1990                let _ = writeln!(out, "      assert Regex.match?(~r/{elixir_val}/, {field_expr})");
1991            }
1992        }
1993        "not_error" => {
1994            // Already handled — the call would fail if it returned {:error, _}.
1995        }
1996        "error" => {
1997            // Handled at the test level.
1998        }
1999        other => {
2000            panic!("Elixir e2e generator: unsupported assertion type: {other}");
2001        }
2002    }
2003}
2004
2005/// Build an Elixir call expression for a `method_result` assertion on a tree-sitter result.
2006/// Maps method names to the appropriate `module_path` function calls.
2007fn build_elixir_method_call(
2008    result_var: &str,
2009    method_name: &str,
2010    args: Option<&serde_json::Value>,
2011    module_path: &str,
2012) -> String {
2013    match method_name {
2014        "root_child_count" => format!("{module_path}.root_child_count({result_var})"),
2015        "has_error_nodes" => format!("{module_path}.tree_has_error_nodes({result_var})"),
2016        "error_count" | "tree_error_count" => format!("{module_path}.tree_error_count({result_var})"),
2017        "tree_to_sexp" => format!("{module_path}.tree_to_sexp({result_var})"),
2018        "contains_node_type" => {
2019            let node_type = args
2020                .and_then(|a| a.get("node_type"))
2021                .and_then(|v| v.as_str())
2022                .unwrap_or("");
2023            format!("{module_path}.tree_contains_node_type({result_var}, \"{node_type}\")")
2024        }
2025        "find_nodes_by_type" => {
2026            let node_type = args
2027                .and_then(|a| a.get("node_type"))
2028                .and_then(|v| v.as_str())
2029                .unwrap_or("");
2030            format!("{module_path}.find_nodes_by_type({result_var}, \"{node_type}\")")
2031        }
2032        "run_query" => {
2033            let query_source = args
2034                .and_then(|a| a.get("query_source"))
2035                .and_then(|v| v.as_str())
2036                .unwrap_or("");
2037            let language = args
2038                .and_then(|a| a.get("language"))
2039                .and_then(|v| v.as_str())
2040                .unwrap_or("");
2041            format!("{module_path}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
2042        }
2043        _ => format!("{module_path}.{method_name}({result_var})"),
2044    }
2045}
2046
2047/// Convert a category name to an Elixir module-safe PascalCase name.
2048fn elixir_module_name(category: &str) -> String {
2049    use heck::ToUpperCamelCase;
2050    category.to_upper_camel_case()
2051}
2052
2053/// Convert a `serde_json::Value` to an Elixir literal string.
2054fn json_to_elixir(value: &serde_json::Value) -> String {
2055    match value {
2056        serde_json::Value::String(s) => format!("\"{}\"", escape_elixir(s)),
2057        serde_json::Value::Bool(true) => "true".to_string(),
2058        serde_json::Value::Bool(false) => "false".to_string(),
2059        serde_json::Value::Number(n) => {
2060            // Elixir requires floats to have a decimal point and does not accept
2061            // `e+N` exponent notation. Strip the `+` and ensure there is a decimal
2062            // point before any `e` exponent marker (e.g. `1e-10` → `1.0e-10`).
2063            let s = n.to_string().replace("e+", "e");
2064            if s.contains('e') && !s.contains('.') {
2065                // Insert `.0` before the `e` so Elixir treats this as a float.
2066                s.replacen('e', ".0e", 1)
2067            } else {
2068                s
2069            }
2070        }
2071        serde_json::Value::Null => "nil".to_string(),
2072        serde_json::Value::Array(arr) => {
2073            let items: Vec<String> = arr.iter().map(json_to_elixir).collect();
2074            format!("[{}]", items.join(", "))
2075        }
2076        serde_json::Value::Object(map) => {
2077            let entries: Vec<String> = map
2078                .iter()
2079                .map(|(k, v)| format!("\"{}\" => {}", escape_elixir(k), json_to_elixir(v)))
2080                .collect();
2081            format!("%{{{}}}", entries.join(", "))
2082        }
2083    }
2084}
2085
2086/// Build an Elixir visitor map and add setup line. Returns the visitor variable name.
2087fn build_elixir_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
2088    use std::fmt::Write as FmtWrite;
2089    let mut visitor_obj = String::new();
2090    let _ = writeln!(visitor_obj, "%{{");
2091    for (method_name, action) in &visitor_spec.callbacks {
2092        emit_elixir_visitor_method(&mut visitor_obj, method_name, action);
2093    }
2094    let _ = writeln!(visitor_obj, "    }}");
2095
2096    setup_lines.push(format!("visitor = {visitor_obj}"));
2097    "visitor".to_string()
2098}
2099
2100/// Emit an Elixir visitor method for a callback action.
2101fn emit_elixir_visitor_method(out: &mut String, method_name: &str, action: &CallbackAction) {
2102    use std::fmt::Write as FmtWrite;
2103
2104    // Elixir uses atom keys and handle_ prefix
2105    let handle_method = format!("handle_{}", &method_name[6..]); // strip "visit_" prefix
2106    // The Rust NIF bridge packages every visitor argument (`_ctx`, `_text`, …) into a
2107    // single map and invokes the user's anonymous function with that map. Generating
2108    // multi-arity functions like `fn(_ctx, _text) ->` therefore raised BadArityError
2109    // ("arity 2 called with 1 argument") at runtime. Generate arity-1 functions that
2110    // accept the args map (and ignore it) to match the bridge's calling convention.
2111
2112    // CustomTemplate needs to read from args; other actions can ignore it.
2113    let arg_binding = match action {
2114        CallbackAction::CustomTemplate { .. } => "args",
2115        _ => "_args",
2116    };
2117    let _ = writeln!(out, "      :{handle_method} => fn({arg_binding}) ->");
2118    match action {
2119        CallbackAction::Skip => {
2120            let _ = writeln!(out, "        :skip");
2121        }
2122        CallbackAction::Continue => {
2123            let _ = writeln!(out, "        :continue");
2124        }
2125        CallbackAction::PreserveHtml => {
2126            let _ = writeln!(out, "        :preserve_html");
2127        }
2128        CallbackAction::Custom { output } => {
2129            let escaped = escape_elixir(output);
2130            let _ = writeln!(out, "        {{:custom, \"{escaped}\"}}");
2131        }
2132        CallbackAction::CustomTemplate { template, .. } => {
2133            // Build a <> concatenation expression so {key} placeholders are substituted
2134            // from the args map at runtime without embedding double-quoted strings inside
2135            // a double-quoted string literal.
2136            let expr = template_to_elixir_concat(template);
2137            let _ = writeln!(out, "        {{:custom, {expr}}}");
2138        }
2139    }
2140    let _ = writeln!(out, "      end,");
2141}
2142
2143/// Convert a template like `"_{text}_"` into an Elixir `<>` concat expression:
2144/// `"_" <> Map.get(args, "text", "") <> "_"`.
2145/// Static parts are escaped via `escape_elixir`; `{key}` placeholders become
2146/// `Map.get(args, "key", "")` lookups into the JSON-decoded args map.
2147fn template_to_elixir_concat(template: &str) -> String {
2148    let mut parts: Vec<String> = Vec::new();
2149    let mut static_buf = String::new();
2150    let mut chars = template.chars().peekable();
2151
2152    while let Some(ch) = chars.next() {
2153        if ch == '{' {
2154            let mut key = String::new();
2155            let mut closed = false;
2156            for kc in chars.by_ref() {
2157                if kc == '}' {
2158                    closed = true;
2159                    break;
2160                }
2161                key.push(kc);
2162            }
2163            if closed && !key.is_empty() {
2164                if !static_buf.is_empty() {
2165                    let escaped = escape_elixir(&static_buf);
2166                    parts.push(format!("\"{escaped}\""));
2167                    static_buf.clear();
2168                }
2169                let escaped_key = escape_elixir(&key);
2170                parts.push(format!("Map.get(args, \"{escaped_key}\", \"\")"));
2171            } else {
2172                static_buf.push('{');
2173                static_buf.push_str(&key);
2174                if !closed {
2175                    // unclosed brace — treat remaining as literal
2176                }
2177            }
2178        } else {
2179            static_buf.push(ch);
2180        }
2181    }
2182
2183    if !static_buf.is_empty() {
2184        let escaped = escape_elixir(&static_buf);
2185        parts.push(format!("\"{escaped}\""));
2186    }
2187
2188    if parts.is_empty() {
2189        return "\"\"".to_string();
2190    }
2191    parts.join(" <> ")
2192}
2193
2194fn fixture_has_elixir_callable(fixture: &Fixture, e2e_config: &E2eConfig) -> bool {
2195    // HTTP fixtures are handled separately — not our concern here.
2196    if fixture.is_http_test() {
2197        return false;
2198    }
2199    let call_config = e2e_config.resolve_call_for_fixture(
2200        fixture.call.as_deref(),
2201        &fixture.id,
2202        &fixture.resolved_category(),
2203        &fixture.tags,
2204        &fixture.input,
2205    );
2206    let elixir_override = call_config
2207        .overrides
2208        .get("elixir")
2209        .or_else(|| e2e_config.call.overrides.get("elixir"));
2210    // When a client_factory is configured the fixture is callable via the client pattern.
2211    if elixir_override.and_then(|o| o.client_factory.as_deref()).is_some() {
2212        return true;
2213    }
2214    // Elixir bindings expose functions via module-level callables.
2215    // Like Python and Node, Elixir can call the base function directly without requiring
2216    // a language-specific override. The function can come from either the override or
2217    // the default [e2e.call] configuration.
2218    let function_from_override = elixir_override.and_then(|o| o.function.as_deref());
2219
2220    // If there's an override function, use it. Otherwise, Elixir can use the base function.
2221    function_from_override.is_some() || !call_config.function.is_empty()
2222}