Skip to main content

alef_e2e/codegen/
go.rs

1//! Go e2e test generator using testing.T.
2
3use crate::config::E2eConfig;
4use crate::escape::{go_string_literal, sanitize_filename};
5use crate::field_access::FieldResolver;
6use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, ValidationErrorExpectation};
7use alef_codegen::naming::{go_param_name, to_go_name};
8use alef_core::backend::GeneratedFile;
9use alef_core::config::Language;
10use alef_core::config::ResolvedCrateConfig;
11use alef_core::hash::{self, CommentStyle};
12use anyhow::Result;
13use heck::ToUpperCamelCase;
14use std::fmt::Write as FmtWrite;
15use std::path::PathBuf;
16
17use super::E2eCodegen;
18use super::client;
19
20/// Go e2e code generator.
21pub struct GoCodegen;
22
23impl E2eCodegen for GoCodegen {
24    fn generate(
25        &self,
26        groups: &[FixtureGroup],
27        e2e_config: &E2eConfig,
28        config: &ResolvedCrateConfig,
29        _type_defs: &[alef_core::ir::TypeDef],
30    ) -> Result<Vec<GeneratedFile>> {
31        let lang = self.language_name();
32        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
33
34        let mut files = Vec::new();
35
36        // Resolve call config with overrides (for module path and import alias).
37        let call = &e2e_config.call;
38        let overrides = call.overrides.get(lang);
39        let configured_go_module_path = config.go.as_ref().and_then(|go| go.module.as_ref()).cloned();
40        let module_path = overrides
41            .and_then(|o| o.module.as_ref())
42            .cloned()
43            .or_else(|| configured_go_module_path.clone())
44            .unwrap_or_else(|| call.module.clone());
45        let import_alias = overrides
46            .and_then(|o| o.alias.as_ref())
47            .cloned()
48            .unwrap_or_else(|| "pkg".to_string());
49
50        // Resolve package config.
51        let go_pkg = e2e_config.resolve_package("go");
52        let go_module_path = go_pkg
53            .as_ref()
54            .and_then(|p| p.module.as_ref())
55            .cloned()
56            .or_else(|| configured_go_module_path.clone())
57            .unwrap_or_else(|| module_path.clone());
58        let replace_path = go_pkg
59            .as_ref()
60            .and_then(|p| p.path.as_ref())
61            .cloned()
62            .or_else(|| Some(format!("../../{}", config.package_dir(Language::Go))));
63        let go_version = go_pkg
64            .as_ref()
65            .and_then(|p| p.version.as_ref())
66            .cloned()
67            .unwrap_or_else(|| {
68                config
69                    .resolved_version()
70                    .map(|v| format!("v{v}"))
71                    .unwrap_or_else(|| "v0.0.0".to_string())
72            });
73        let field_resolver = FieldResolver::new(
74            &e2e_config.fields,
75            &e2e_config.fields_optional,
76            &e2e_config.result_fields,
77            &e2e_config.fields_array,
78            &std::collections::HashSet::new(),
79        );
80
81        // Generate go.mod. In registry mode, omit the `replace` directive so the
82        // module is fetched from the Go module proxy.
83        let effective_replace = match e2e_config.dep_mode {
84            crate::config::DependencyMode::Registry => None,
85            crate::config::DependencyMode::Local => replace_path.as_deref().map(String::from),
86        };
87        // In local mode with a `replace` directive the version in `require` is a
88        // placeholder.  Go requires that for a major-version module path (`/vN`, N ≥ 2)
89        // the placeholder version must start with `vN.`, e.g. `v3.0.0`.  A version like
90        // `v0.0.0` is rejected with "should be v3, not v0".  Fix the placeholder when the
91        // module path ends with `/vN` and the configured version doesn't match.
92        let effective_go_version = if effective_replace.is_some() {
93            fix_go_major_version(&go_module_path, &go_version)
94        } else {
95            go_version.clone()
96        };
97        files.push(GeneratedFile {
98            path: output_base.join("go.mod"),
99            content: render_go_mod(&go_module_path, effective_replace.as_deref(), &effective_go_version),
100            generated_header: false,
101        });
102
103        // Determine if any fixture needs jsonString helper across all groups.
104        let emits_executable_test =
105            |fixture: &Fixture| fixture.is_http_test() || fixture_has_go_callable(fixture, e2e_config);
106        let needs_json_stringify = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
107            emits_executable_test(f)
108                && f.assertions.iter().any(|a| {
109                    matches!(
110                        a.assertion_type.as_str(),
111                        "contains" | "contains_all" | "contains_any" | "not_contains"
112                    ) && {
113                        if a.field.as_ref().is_none_or(|f| f.is_empty()) {
114                            e2e_config
115                                .resolve_call_for_fixture(f.call.as_deref(), &f.input)
116                                .result_is_array
117                        } else {
118                            let resolved_name = field_resolver.resolve(a.field.as_deref().unwrap_or(""));
119                            field_resolver.is_array(resolved_name)
120                        }
121                    }
122                })
123        });
124
125        // Generate helpers_test.go with jsonString if needed, emitted exactly once.
126        if needs_json_stringify {
127            files.push(GeneratedFile {
128                path: output_base.join("helpers_test.go"),
129                content: render_helpers_test_go(),
130                generated_header: true,
131            });
132        }
133
134        // Generate main_test.go with TestMain when:
135        // 1. Any fixture needs the mock server (has mock_response), or
136        // 2. Any fixture is client_factory-based (reads MOCK_SERVER_URL), or
137        // 3. Any fixture is file-based (requires test_documents directory setup).
138        //
139        // TestMain runs before all tests and changes to the test_documents directory,
140        // ensuring that relative file paths like "pdf/fake_memo.pdf" resolve correctly.
141        let has_file_fixtures = groups
142            .iter()
143            .flat_map(|g| g.fixtures.iter())
144            .any(|f| f.http.is_none() && !f.needs_mock_server());
145
146        let needs_main_test = has_file_fixtures
147            || groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
148                if f.needs_mock_server() {
149                    return true;
150                }
151                let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
152                let go_override = cc.overrides.get("go").or_else(|| e2e_config.call.overrides.get("go"));
153                go_override.and_then(|o| o.client_factory.as_deref()).is_some()
154            });
155
156        if needs_main_test {
157            files.push(GeneratedFile {
158                path: output_base.join("main_test.go"),
159                content: render_main_test_go(&e2e_config.test_documents_dir),
160                generated_header: true,
161            });
162        }
163
164        // Generate test files per category.
165        for group in groups {
166            let active: Vec<&Fixture> = group
167                .fixtures
168                .iter()
169                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
170                .collect();
171
172            if active.is_empty() {
173                continue;
174            }
175
176            let filename = format!("{}_test.go", sanitize_filename(&group.category));
177            let content = render_test_file(
178                &group.category,
179                &active,
180                &module_path,
181                &import_alias,
182                &field_resolver,
183                e2e_config,
184            );
185            files.push(GeneratedFile {
186                path: output_base.join(filename),
187                content,
188                generated_header: true,
189            });
190        }
191
192        Ok(files)
193    }
194
195    fn language_name(&self) -> &'static str {
196        "go"
197    }
198}
199
200/// Fix a Go module version so it is valid for a major-version module path.
201///
202/// Go requires that a module path ending in `/vN` (N ≥ 2) uses a version
203/// whose major component matches N.  In local-replace mode we use a synthetic
204/// placeholder version; if that placeholder (e.g. `v0.0.0`) doesn't match the
205/// major suffix, fix it to `vN.0.0` so `go mod` accepts the go.mod.
206fn fix_go_major_version(module_path: &str, version: &str) -> String {
207    // Extract `/vN` suffix from the module path (N must be ≥ 2).
208    let major = module_path
209        .rsplit('/')
210        .next()
211        .and_then(|seg| seg.strip_prefix('v'))
212        .and_then(|n| n.parse::<u64>().ok())
213        .filter(|&n| n >= 2);
214
215    let Some(n) = major else {
216        return version.to_string();
217    };
218
219    // If the version already starts with `vN.`, it is valid — leave it alone.
220    let expected_prefix = format!("v{n}.");
221    if version.starts_with(&expected_prefix) {
222        return version.to_string();
223    }
224
225    format!("v{n}.0.0")
226}
227
228fn render_go_mod(go_module_path: &str, replace_path: Option<&str>, version: &str) -> String {
229    let mut out = String::new();
230    let _ = writeln!(out, "module e2e_go");
231    let _ = writeln!(out);
232    let _ = writeln!(out, "go 1.26");
233    let _ = writeln!(out);
234    let _ = writeln!(out, "require (");
235    let _ = writeln!(out, "\t{go_module_path} {version}");
236    let _ = writeln!(out, "\tgithub.com/stretchr/testify v1.11.1");
237    let _ = writeln!(out, ")");
238
239    if let Some(path) = replace_path {
240        let _ = writeln!(out);
241        let _ = writeln!(out, "replace {go_module_path} => {path}");
242    }
243
244    out
245}
246
247/// Generate `main_test.go` that starts the mock HTTP server before all tests run.
248///
249/// The binary is expected at `../rust/target/release/mock-server` relative to the Go e2e
250/// directory.  The server prints `MOCK_SERVER_URL=http://...` on stdout; we read that line
251/// and export the variable so all test files can call `os.Getenv("MOCK_SERVER_URL")`.
252fn render_main_test_go(test_documents_dir: &str) -> String {
253    // NOTE: the generated-file header is injected by the caller (generated_header: true).
254    let mut out = String::new();
255    let _ = writeln!(out, "package e2e_test");
256    let _ = writeln!(out);
257    let _ = writeln!(out, "import (");
258    let _ = writeln!(out, "\t\"bufio\"");
259    let _ = writeln!(out, "\t\"encoding/json\"");
260    let _ = writeln!(out, "\t\"io\"");
261    let _ = writeln!(out, "\t\"os\"");
262    let _ = writeln!(out, "\t\"os/exec\"");
263    let _ = writeln!(out, "\t\"path/filepath\"");
264    let _ = writeln!(out, "\t\"runtime\"");
265    let _ = writeln!(out, "\t\"strings\"");
266    let _ = writeln!(out, "\t\"testing\"");
267    let _ = writeln!(out, ")");
268    let _ = writeln!(out);
269    let _ = writeln!(out, "func TestMain(m *testing.M) {{");
270    let _ = writeln!(out, "\t_, filename, _, _ := runtime.Caller(0)");
271    let _ = writeln!(out, "\tdir := filepath.Dir(filename)");
272    let _ = writeln!(out);
273    let _ = writeln!(
274        out,
275        "\t// Change to the configured test-documents directory so that fixture file paths like"
276    );
277    let _ = writeln!(
278        out,
279        "\t// \"pdf/fake_memo.pdf\" resolve correctly when running go test from e2e/go/."
280    );
281    let _ = writeln!(
282        out,
283        "\ttestDocumentsDir := filepath.Join(dir, \"..\", \"..\", \"{test_documents_dir}\")"
284    );
285    let _ = writeln!(out, "\tif err := os.Chdir(testDocumentsDir); err != nil {{");
286    let _ = writeln!(out, "\t\tpanic(err)");
287    let _ = writeln!(out, "\t}}");
288    let _ = writeln!(out);
289    let _ = writeln!(out, "\t// Start the mock HTTP server if it exists.");
290    let _ = writeln!(
291        out,
292        "\tmockServerBin := filepath.Join(dir, \"..\", \"rust\", \"target\", \"release\", \"mock-server\")"
293    );
294    let _ = writeln!(out, "\tif _, err := os.Stat(mockServerBin); err == nil {{");
295    let _ = writeln!(
296        out,
297        "\t\tfixturesDir := filepath.Join(dir, \"..\", \"..\", \"fixtures\")"
298    );
299    let _ = writeln!(out, "\t\tcmd := exec.Command(mockServerBin, fixturesDir)");
300    let _ = writeln!(out, "\t\tcmd.Stderr = os.Stderr");
301    let _ = writeln!(out, "\t\tstdout, err := cmd.StdoutPipe()");
302    let _ = writeln!(out, "\t\tif err != nil {{");
303    let _ = writeln!(out, "\t\t\tpanic(err)");
304    let _ = writeln!(out, "\t\t}}");
305    let _ = writeln!(out, "\t\t// Keep a writable pipe to the mock-server's stdin so the");
306    let _ = writeln!(
307        out,
308        "\t\t// server does not see EOF and exit immediately. The mock-server"
309    );
310    let _ = writeln!(out, "\t\t// blocks reading stdin until the parent closes the pipe.");
311    let _ = writeln!(out, "\t\tstdin, err := cmd.StdinPipe()");
312    let _ = writeln!(out, "\t\tif err != nil {{");
313    let _ = writeln!(out, "\t\t\tpanic(err)");
314    let _ = writeln!(out, "\t\t}}");
315    let _ = writeln!(out, "\t\tif err := cmd.Start(); err != nil {{");
316    let _ = writeln!(out, "\t\t\tpanic(err)");
317    let _ = writeln!(out, "\t\t}}");
318    let _ = writeln!(out, "\t\tscanner := bufio.NewScanner(stdout)");
319    let _ = writeln!(out, "\t\tfor scanner.Scan() {{");
320    let _ = writeln!(out, "\t\t\tline := scanner.Text()");
321    let _ = writeln!(out, "\t\t\tif strings.HasPrefix(line, \"MOCK_SERVER_URL=\") {{");
322    let _ = writeln!(
323        out,
324        "\t\t\t\t_ = os.Setenv(\"MOCK_SERVER_URL\", strings.TrimPrefix(line, \"MOCK_SERVER_URL=\"))"
325    );
326    let _ = writeln!(out, "\t\t\t}} else if strings.HasPrefix(line, \"MOCK_SERVERS=\") {{");
327    let _ = writeln!(out, "\t\t\t\t_jsonVal := strings.TrimPrefix(line, \"MOCK_SERVERS=\")");
328    let _ = writeln!(out, "\t\t\t\t_ = os.Setenv(\"MOCK_SERVERS\", _jsonVal)");
329    let _ = writeln!(
330        out,
331        "\t\t\t\t// Parse the JSON map and set per-fixture env vars (MOCK_SERVER_<FIXTURE_ID>)."
332    );
333    let _ = writeln!(out, "\t\t\t\tvar _perFixture map[string]string");
334    let _ = writeln!(
335        out,
336        "\t\t\t\tif err := json.Unmarshal([]byte(_jsonVal), &_perFixture); err == nil {{"
337    );
338    let _ = writeln!(out, "\t\t\t\t\tfor _fid, _furl := range _perFixture {{");
339    let _ = writeln!(
340        out,
341        "\t\t\t\t\t\t_ = os.Setenv(\"MOCK_SERVER_\"+strings.ToUpper(_fid), _furl)"
342    );
343    let _ = writeln!(out, "\t\t\t\t\t}}");
344    let _ = writeln!(out, "\t\t\t\t}}");
345    let _ = writeln!(out, "\t\t\t\tbreak");
346    let _ = writeln!(out, "\t\t\t}} else if os.Getenv(\"MOCK_SERVER_URL\") != \"\" {{");
347    let _ = writeln!(out, "\t\t\t\tbreak");
348    let _ = writeln!(out, "\t\t\t}}");
349    let _ = writeln!(out, "\t\t}}");
350    let _ = writeln!(out, "\t\tgo func() {{ _, _ = io.Copy(io.Discard, stdout) }}()");
351    let _ = writeln!(out, "\t\tcode := m.Run()");
352    let _ = writeln!(out, "\t\t_ = stdin.Close()");
353    let _ = writeln!(out, "\t\t_ = cmd.Process.Signal(os.Interrupt)");
354    let _ = writeln!(out, "\t\t_ = cmd.Wait()");
355    let _ = writeln!(out, "\t\tos.Exit(code)");
356    let _ = writeln!(out, "\t}} else {{");
357    let _ = writeln!(out, "\t\tcode := m.Run()");
358    let _ = writeln!(out, "\t\tos.Exit(code)");
359    let _ = writeln!(out, "\t}}");
360    let _ = writeln!(out, "}}");
361    out
362}
363
364/// Generate `helpers_test.go` with the jsonString helper function.
365/// This is emitted once per package to avoid duplicate function definitions.
366fn render_helpers_test_go() -> String {
367    let mut out = String::new();
368    let _ = writeln!(out, "package e2e_test");
369    let _ = writeln!(out);
370    let _ = writeln!(out, "import \"encoding/json\"");
371    let _ = writeln!(out);
372    let _ = writeln!(out, "// jsonString converts a value to its JSON string representation.");
373    let _ = writeln!(
374        out,
375        "// Array fields use jsonString instead of fmt.Sprint to preserve structure."
376    );
377    let _ = writeln!(out, "func jsonString(value any) string {{");
378    let _ = writeln!(out, "\tencoded, err := json.Marshal(value)");
379    let _ = writeln!(out, "\tif err != nil {{");
380    let _ = writeln!(out, "\t\treturn \"\"");
381    let _ = writeln!(out, "\t}}");
382    let _ = writeln!(out, "\treturn string(encoded)");
383    let _ = writeln!(out, "}}");
384    out
385}
386
387fn render_test_file(
388    category: &str,
389    fixtures: &[&Fixture],
390    go_module_path: &str,
391    import_alias: &str,
392    field_resolver: &FieldResolver,
393    e2e_config: &crate::config::E2eConfig,
394) -> String {
395    let mut out = String::new();
396    let emits_executable_test =
397        |fixture: &Fixture| fixture.is_http_test() || fixture_has_go_callable(fixture, e2e_config);
398
399    // Go convention: generated file marker must appear before the package declaration.
400    out.push_str(&hash::header(CommentStyle::DoubleSlash));
401    let _ = writeln!(out);
402
403    // Determine if any fixture actually uses the pkg import.
404    // Fixtures without mock_response are emitted as t.Skip() stubs and don't reference the
405    // package — omit the import when no fixture needs it to avoid the Go "imported and not
406    // used" compile error. Visitor fixtures reference the package types (NodeContext,
407    // VisitResult, VisitResult* helpers) in struct method signatures emitted at file scope,
408    // so they also require the import even when the test body itself is a Skip stub.
409    // Direct-callable fixtures (non-HTTP, non-mock, with a resolved Go function) also
410    // reference the package when a Go override function is configured.
411    let needs_pkg = fixtures
412        .iter()
413        .any(|f| fixture_has_go_callable(f, e2e_config) || f.is_http_test() || f.visitor.is_some());
414
415    // Determine if we need the "os" import (mock_url args, HTTP fixtures, or
416    // client_factory fixtures that read MOCK_SERVER_URL via os.Getenv).
417    let needs_os = fixtures.iter().any(|f| {
418        if f.is_http_test() {
419            return true;
420        }
421        if !emits_executable_test(f) {
422            return false;
423        }
424        let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
425        let go_override = call_config
426            .overrides
427            .get("go")
428            .or_else(|| e2e_config.call.overrides.get("go"));
429        if go_override.and_then(|o| o.client_factory.as_deref()).is_some() {
430            return true;
431        }
432        let call_args = &call_config.args;
433        // Need "os" for mock_url args, or for bytes args with a string fixture value
434        // (fixture-relative path loaded via os.ReadFile at test-run time).
435        if call_args.iter().any(|a| a.arg_type == "mock_url") {
436            return true;
437        }
438        call_args.iter().any(|a| {
439            if a.arg_type != "bytes" {
440                return false;
441            }
442            // alef.toml field paths are dotted (e.g. "input.data"). The fixture's `input`
443            // field already strips the "input." prefix, so we walk the remaining segments.
444            let mut current = &f.input;
445            let path = a.field.strip_prefix("input.").unwrap_or(&a.field);
446            for segment in path.split('.') {
447                match current.get(segment) {
448                    Some(next) => current = next,
449                    None => return false,
450                }
451            }
452            current.is_string()
453        })
454    });
455
456    // Note: file_path args are passed directly as relative strings — the e2e/go
457    // TestMain in main_test.go already chdir's into the repo-root test_documents/.
458    let needs_filepath = false;
459
460    let _needs_json_stringify = fixtures.iter().any(|f| {
461        emits_executable_test(f)
462            && f.assertions.iter().any(|a| {
463                matches!(
464                    a.assertion_type.as_str(),
465                    "contains" | "contains_all" | "contains_any" | "not_contains"
466                ) && {
467                    // Check if this assertion operates on an array field.
468                    // If no field is specified, check if the result itself is an array.
469                    if a.field.as_ref().is_none_or(|f| f.is_empty()) {
470                        // No field specified: check if result is an array
471                        e2e_config
472                            .resolve_call_for_fixture(f.call.as_deref(), &f.input)
473                            .result_is_array
474                    } else {
475                        // Field specified: check if that field is an array
476                        let resolved_name = field_resolver.resolve(a.field.as_deref().unwrap_or(""));
477                        field_resolver.is_array(resolved_name)
478                    }
479                }
480            })
481    });
482
483    // Determine if we need "encoding/json" (handle args with non-null config,
484    // json_object args that will be unmarshalled into a typed struct, or HTTP
485    // body/partial/validation-error assertions that use json.Unmarshal).
486    let needs_json = fixtures.iter().any(|f| {
487        // HTTP body assertions use json.Unmarshal for Object/Array bodies;
488        // partial body and validation-error assertions always use json.Unmarshal.
489        if let Some(http) = &f.http {
490            let body_needs_json = http
491                .expected_response
492                .body
493                .as_ref()
494                .is_some_and(|b| matches!(b, serde_json::Value::Object(_) | serde_json::Value::Array(_)));
495            let partial_needs_json = http.expected_response.body_partial.is_some();
496            let ve_needs_json = http
497                .expected_response
498                .validation_errors
499                .as_ref()
500                .is_some_and(|v| !v.is_empty());
501            if body_needs_json || partial_needs_json || ve_needs_json {
502                return true;
503            }
504        }
505        if !emits_executable_test(f) {
506            return false;
507        }
508
509        let call = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
510        let call_args = &call.args;
511        // handle args with non-null config value
512        let has_handle = call_args.iter().any(|a| a.arg_type == "handle") && {
513            call_args.iter().filter(|a| a.arg_type == "handle").any(|a| {
514                let field = a.field.strip_prefix("input.").unwrap_or(&a.field);
515                let v = f.input.get(field).unwrap_or(&serde_json::Value::Null);
516                !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
517            })
518        };
519        // json_object args with options_type or array values (will use JSON unmarshal)
520        let go_override = call.overrides.get("go");
521        let opts_type = go_override.and_then(|o| o.options_type.as_deref()).or_else(|| {
522            e2e_config
523                .call
524                .overrides
525                .get("go")
526                .and_then(|o| o.options_type.as_deref())
527        });
528        let has_json_obj = call_args.iter().any(|a| {
529            if a.arg_type != "json_object" {
530                return false;
531            }
532            let v = if a.field == "input" {
533                &f.input
534            } else {
535                let field = a.field.strip_prefix("input.").unwrap_or(&a.field);
536                f.input.get(field).unwrap_or(&serde_json::Value::Null)
537            };
538            if v.is_array() {
539                return true;
540            } // array → []string unmarshal
541            opts_type.is_some() && v.is_object() && !v.as_object().is_some_and(|o| o.is_empty())
542        });
543        has_handle || has_json_obj
544    });
545
546    // No runtime base64 calls remain in generated Go code. Bytes args with string values
547    // are now loaded via os.ReadFile (see needs_os) and HTTP body byte arrays are
548    // base64-encoded at codegen time and embedded as literal strings in the json.Unmarshal
549    // call, which doesn't require the `encoding/base64` import in the test file.
550    let needs_base64 = false;
551
552    // Determine if we need the "fmt" import (CustomTemplate visitor actions
553    // with placeholders or string assertions rendered through fmt.Sprint).
554    // Note: jsonString is now in helpers_test.go (uses encoding/json, not fmt),
555    // so individual test files do NOT need fmt just for calling jsonString.
556    let needs_fmt = fixtures.iter().any(|f| {
557        f.visitor.as_ref().is_some_and(|v| {
558            v.callbacks.values().any(|action| {
559                if let CallbackAction::CustomTemplate { template } = action {
560                    template.contains('{')
561                } else {
562                    false
563                }
564            })
565        }) || (emits_executable_test(f)
566            && f.assertions.iter().any(|a| {
567                matches!(
568                    a.assertion_type.as_str(),
569                    "contains" | "contains_all" | "contains_any" | "not_contains"
570                ) && {
571                    // Check if this assertion uses fmt.Sprint (non-array fields).
572                    // Array fields use jsonString instead, which also needs fmt.
573                    // Also verify the field is valid for the result type — assertions
574                    // on invalid fields are skipped without emitting any fmt.Sprint call.
575                    if a.field.as_ref().is_none_or(|f| f.is_empty()) {
576                        // No field: fmt.Sprint only if result is not an array
577                        !e2e_config
578                            .resolve_call_for_fixture(f.call.as_deref(), &f.input)
579                            .result_is_array
580                    } else {
581                        // Field specified: fmt.Sprint only if that field is not an array
582                        // and the field is actually valid for the result type (otherwise
583                        // the assertion is skipped and fmt.Sprint is never emitted).
584                        let field = a.field.as_deref().unwrap_or("");
585                        let resolved_name = field_resolver.resolve(field);
586                        !field_resolver.is_array(resolved_name) && field_resolver.is_valid_for_result(field)
587                    }
588                }
589            }))
590    });
591
592    // Determine if we need the "strings" import.
593    // Only count assertions whose fields are actually valid for the result type.
594    let needs_strings = fixtures.iter().any(|f| {
595        if !emits_executable_test(f) {
596            return false;
597        }
598        f.assertions.iter().any(|a| {
599            let type_needs_strings = if a.assertion_type == "equals" {
600                // equals with string values needs strings.TrimSpace
601                a.value.as_ref().is_some_and(|v| v.is_string())
602            } else {
603                matches!(
604                    a.assertion_type.as_str(),
605                    "contains" | "contains_all" | "contains_any" | "not_contains" | "starts_with" | "ends_with"
606                )
607            };
608            let field_valid = a
609                .field
610                .as_ref()
611                .map(|f| f.is_empty() || field_resolver.is_valid_for_result(f))
612                .unwrap_or(true);
613            type_needs_strings && field_valid
614        })
615    });
616
617    // Determine if we need the testify assert import.
618    let needs_assert = fixtures.iter().any(|f| {
619        if !emits_executable_test(f) {
620            return false;
621        }
622        // Validation-category fixtures with an `error` assertion emit
623        // `assert.Error(t, createErr)` in their setup block, requiring testify.
624        // Other categories (e.g. `error`) use t.Errorf/t.Fatalf and do NOT need testify.
625        if f.resolved_category() == "validation" && f.assertions.iter().any(|a| a.assertion_type == "error") {
626            return true;
627        }
628        f.assertions.iter().any(|a| {
629            let field_valid = a
630                .field
631                .as_ref()
632                .map(|f| f.is_empty() || field_resolver.is_valid_for_result(f))
633                .unwrap_or(true);
634            let synthetic_field_needs_assert = match a.field.as_deref() {
635                Some("chunks_have_content" | "chunks_have_embeddings") => {
636                    matches!(a.assertion_type.as_str(), "is_true" | "is_false")
637                }
638                Some("embeddings") => {
639                    matches!(
640                        a.assertion_type.as_str(),
641                        "count_equals" | "count_min" | "not_empty" | "is_empty"
642                    )
643                }
644                _ => false,
645            };
646            let type_needs_assert = matches!(
647                a.assertion_type.as_str(),
648                "count_equals"
649                    | "count_min"
650                    | "count_max"
651                    | "is_true"
652                    | "is_false"
653                    | "method_result"
654                    | "min_length"
655                    | "max_length"
656                    | "matches_regex"
657            );
658            synthetic_field_needs_assert || type_needs_assert && field_valid
659        })
660    });
661
662    // Determine if we need "net/http" and "io" (HTTP server tests via HTTP client).
663    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
664    let needs_http = has_http_fixtures;
665    // io.ReadAll is emitted for every HTTP fixture (render_call always reads the body).
666    let needs_io = has_http_fixtures;
667
668    // Determine if we need "reflect" (for HTTP response body JSON comparison
669    // and partial-body assertions, both of which use reflect.DeepEqual).
670    let needs_reflect = fixtures.iter().any(|f| {
671        if let Some(http) = &f.http {
672            let body_needs_reflect = http
673                .expected_response
674                .body
675                .as_ref()
676                .is_some_and(|b| matches!(b, serde_json::Value::Object(_) | serde_json::Value::Array(_)));
677            let partial_needs_reflect = http.expected_response.body_partial.is_some();
678            body_needs_reflect || partial_needs_reflect
679        } else {
680            false
681        }
682    });
683
684    let _ = writeln!(out, "// E2e tests for category: {category}");
685    let _ = writeln!(out, "package e2e_test");
686    let _ = writeln!(out);
687    let _ = writeln!(out, "import (");
688    if needs_base64 {
689        let _ = writeln!(out, "\t\"encoding/base64\"");
690    }
691    if needs_json || needs_reflect {
692        let _ = writeln!(out, "\t\"encoding/json\"");
693    }
694    if needs_fmt {
695        let _ = writeln!(out, "\t\"fmt\"");
696    }
697    if needs_io {
698        let _ = writeln!(out, "\t\"io\"");
699    }
700    if needs_http {
701        let _ = writeln!(out, "\t\"net/http\"");
702    }
703    if needs_os {
704        let _ = writeln!(out, "\t\"os\"");
705    }
706    let _ = needs_filepath; // reserved for future use; currently always false
707    if needs_reflect {
708        let _ = writeln!(out, "\t\"reflect\"");
709    }
710    if needs_strings {
711        let _ = writeln!(out, "\t\"strings\"");
712    }
713    let _ = writeln!(out, "\t\"testing\"");
714    if needs_assert {
715        let _ = writeln!(out);
716        let _ = writeln!(out, "\t\"github.com/stretchr/testify/assert\"");
717    }
718    if needs_pkg {
719        let _ = writeln!(out);
720        let _ = writeln!(out, "\t{import_alias} \"{go_module_path}\"");
721    }
722    let _ = writeln!(out, ")");
723    let _ = writeln!(out);
724
725    // Emit package-level visitor structs (must be outside any function in Go).
726    for fixture in fixtures.iter() {
727        if let Some(visitor_spec) = &fixture.visitor {
728            let struct_name = visitor_struct_name(&fixture.id);
729            emit_go_visitor_struct(&mut out, &struct_name, visitor_spec, import_alias);
730            let _ = writeln!(out);
731        }
732    }
733
734    for (i, fixture) in fixtures.iter().enumerate() {
735        render_test_function(&mut out, fixture, import_alias, field_resolver, e2e_config);
736        if i + 1 < fixtures.len() {
737            let _ = writeln!(out);
738        }
739    }
740
741    // Clean up trailing newlines.
742    while out.ends_with("\n\n") {
743        out.pop();
744    }
745    if !out.ends_with('\n') {
746        out.push('\n');
747    }
748    out
749}
750
751/// Return `true` when a non-HTTP fixture can be exercised by calling the Go
752/// binding directly.
753///
754/// A fixture is Go-callable when the resolved call config provides a non-empty
755/// function name — either via a Go-specific override (`[e2e.call.overrides.go]
756/// function`) or via the base call `function` field.  The Go binding exposes all
757/// public functions from the Rust core as PascalCase exports, so any non-empty
758/// function name can be resolved to a valid Go symbol via `to_go_name`.
759fn fixture_has_go_callable(fixture: &Fixture, e2e_config: &crate::config::E2eConfig) -> bool {
760    // HTTP fixtures are handled by render_http_test_function — not our concern here.
761    if fixture.is_http_test() {
762        return false;
763    }
764    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
765    // Honor per-call `skip_languages`: when the resolved call's `skip_languages`
766    // contains `"go"`, the Go binding doesn't expose this function.
767    if call_config.skip_languages.iter().any(|l| l == "go") {
768        return false;
769    }
770    let go_override = call_config
771        .overrides
772        .get("go")
773        .or_else(|| e2e_config.call.overrides.get("go"));
774    // When a client_factory is configured, the fixture is callable via the
775    // client-method pattern even when the base function name is empty.
776    if go_override.and_then(|o| o.client_factory.as_deref()).is_some() {
777        return true;
778    }
779    // Prefer a Go-specific override function name; fall back to the base function name.
780    // Any non-empty function name is callable: the Go binding exports all public
781    // Rust functions as PascalCase symbols (snake_case → PascalCase via to_go_name).
782    let fn_name = go_override
783        .and_then(|o| o.function.as_deref())
784        .filter(|s| !s.is_empty())
785        .unwrap_or(call_config.function.as_str());
786    !fn_name.is_empty()
787}
788
789fn render_test_function(
790    out: &mut String,
791    fixture: &Fixture,
792    import_alias: &str,
793    field_resolver: &FieldResolver,
794    e2e_config: &crate::config::E2eConfig,
795) {
796    let fn_name = fixture.id.to_upper_camel_case();
797    let description = &fixture.description;
798
799    // Delegate HTTP fixtures to the shared driver via GoTestClientRenderer.
800    if fixture.http.is_some() {
801        render_http_test_function(out, fixture);
802        return;
803    }
804
805    // Non-HTTP fixtures are tested directly when the call config provides a
806    // callable Go function.  Emit a t.Skip() stub when:
807    //   - No mock response and no callable (non-HTTP, non-mock, unreachable), or
808    //   - The call's skip_languages includes "go" (e.g. streaming not supported).
809    if !fixture_has_go_callable(fixture, e2e_config) {
810        let _ = writeln!(out, "func Test_{fn_name}(t *testing.T) {{");
811        let _ = writeln!(out, "\t// {description}");
812        let _ = writeln!(
813            out,
814            "\tt.Skip(\"non-HTTP fixture: Go binding does not expose a callable for the configured `[e2e.call]` function\")"
815        );
816        let _ = writeln!(out, "}}");
817        return;
818    }
819
820    // Resolve call config per-fixture (supports named calls via fixture.call).
821    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
822    let lang = "go";
823    let overrides = call_config.overrides.get(lang);
824
825    // Select the function name: Go bindings now integrate visitor support into
826    // the main Convert() function via ConversionOptions.Visitor field.
827    // (In other languages, there may be separate visitor_function overrides, but Go uses a single function.)
828    let base_function_name = overrides
829        .and_then(|o| o.function.as_deref())
830        .unwrap_or(&call_config.function);
831    let function_name = to_go_name(base_function_name);
832    let result_var = &call_config.result_var;
833    let args = &call_config.args;
834
835    // Whether the function returns (value, error) or just (error) or just (value).
836    // Check Go override first, fall back to call-level returns_result.
837    let returns_result = overrides
838        .and_then(|o| o.returns_result)
839        .unwrap_or(call_config.returns_result);
840
841    // Whether the function returns only error (no value component), i.e. Result<(), E>.
842    // When returns_result=true and returns_void=true, Go emits `err :=` not `_, err :=`.
843    let returns_void = call_config.returns_void;
844
845    // result_is_simple: result is a scalar (*string, *bool, etc.) not a struct.
846    // Priority: Go override > call-level (canonical source) > Rust override (legacy compat).
847    let result_is_simple = overrides.map(|o| o.result_is_simple).unwrap_or_else(|| {
848        if call_config.result_is_simple {
849            return true;
850        }
851        call_config
852            .overrides
853            .get("rust")
854            .map(|o| o.result_is_simple)
855            .unwrap_or(false)
856    });
857
858    // result_is_array: the simple result is a slice/array type (e.g., []string).
859    // Priority: Go override > call-level (canonical source).
860    let result_is_array = overrides
861        .map(|o| o.result_is_array)
862        .unwrap_or(call_config.result_is_array);
863
864    // Per-call Go options_type, falling back to the default call's Go override.
865    let call_options_type = overrides.and_then(|o| o.options_type.as_deref()).or_else(|| {
866        e2e_config
867            .call
868            .overrides
869            .get("go")
870            .and_then(|o| o.options_type.as_deref())
871    });
872
873    // Whether json_object options are passed as a pointer (*OptionsType).
874    let call_options_ptr = overrides.map(|o| o.options_ptr).unwrap_or_else(|| {
875        e2e_config
876            .call
877            .overrides
878            .get("go")
879            .map(|o| o.options_ptr)
880            .unwrap_or(false)
881    });
882
883    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
884    // Validation-category fixtures expect engine *creation* to fail. Other expects_error
885    // fixtures (error_*) construct a valid engine and expect the *operation* to fail —
886    // engine creation should not be wrapped in assert.Error there.
887    let validation_creation_failure = expects_error && fixture.resolved_category() == "validation";
888
889    // Client factory: when set, the test creates a client via `pkg.Factory("test-key", baseURL)`
890    // and calls methods on the instance rather than top-level package functions.
891    let client_factory = overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
892        e2e_config
893            .call
894            .overrides
895            .get(lang)
896            .and_then(|o| o.client_factory.as_deref())
897    });
898
899    let (mut setup_lines, args_str) = build_args_and_setup(
900        &fixture.input,
901        args,
902        import_alias,
903        call_options_type,
904        fixture,
905        call_options_ptr,
906        validation_creation_failure,
907    );
908
909    // Build visitor if present — integrate into options instead of separate parameter.
910    // Go binding's Convert() checks options.Visitor and delegates to convertWithVisitorHelper when set.
911    let mut visitor_opts_var: Option<String> = None;
912    if fixture.visitor.is_some() {
913        let struct_name = visitor_struct_name(&fixture.id);
914        setup_lines.push(format!("visitor := &{struct_name}{{}}"));
915        // Create a fresh opts variable with the visitor attached.
916        let opts_type = call_options_type.unwrap_or("ConversionOptions");
917        let opts_var = "opts".to_string();
918        setup_lines.push(format!("opts := &{import_alias}.{opts_type}{{}}"));
919        setup_lines.push("opts.Visitor = visitor".to_string());
920        visitor_opts_var = Some(opts_var);
921    }
922
923    let go_extra_args = overrides.map(|o| o.extra_args.as_slice()).unwrap_or(&[]).to_vec();
924    let final_args = {
925        let mut parts: Vec<String> = Vec::new();
926        if !args_str.is_empty() {
927            // When visitor is present, replace trailing ", nil" with ", opts"
928            let processed_args = if let Some(ref opts_var) = visitor_opts_var {
929                args_str.trim_end_matches(", nil").to_string() + ", " + opts_var
930            } else {
931                args_str
932            };
933            parts.push(processed_args);
934        }
935        parts.extend(go_extra_args);
936        parts.join(", ")
937    };
938
939    let _ = writeln!(out, "func Test_{fn_name}(t *testing.T) {{");
940    let _ = writeln!(out, "\t// {description}");
941
942    // Live-API fixtures use `env.api_key_var` to mark the env var that
943    // supplies the real API key. Skip the test when the env var is unset
944    // (mirrors Python's pytest.skip and Node's early-return pattern).
945    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
946    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
947    if let Some(var) = api_key_var {
948        if has_mock {
949            // Env-fallback branch: when the real API key is set use the live
950            // provider; otherwise fall back to the mock server so the test
951            // always runs in CI without credentials.
952            let fixture_id = &fixture.id;
953            let _ = writeln!(out, "\tapiKey := os.Getenv(\"{var}\")");
954            let _ = writeln!(out, "\tvar baseURL *string");
955            let _ = writeln!(out, "\tif apiKey != \"\" {{");
956            let _ = writeln!(out, "\t\tt.Logf(\"{fixture_id}: using real API ({var} is set)\")");
957            let _ = writeln!(out, "\t}} else {{");
958            let _ = writeln!(out, "\t\tt.Logf(\"{fixture_id}: using mock server ({var} not set)\")");
959            let _ = writeln!(
960                out,
961                "\t\tu := os.Getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\""
962            );
963            let _ = writeln!(out, "\t\tbaseURL = &u");
964            let _ = writeln!(out, "\t\tapiKey = \"test-key\"");
965            let _ = writeln!(out, "\t}}");
966        } else {
967            let _ = writeln!(out, "\tapiKey := os.Getenv(\"{var}\")");
968            let _ = writeln!(out, "\tif apiKey == \"\" {{");
969            let _ = writeln!(out, "\t\tt.Skipf(\"{var} not set\")");
970            let _ = writeln!(out, "\t}}");
971        }
972    }
973
974    for line in &setup_lines {
975        let _ = writeln!(out, "\t{line}");
976    }
977
978    // Client factory: emit client creation before the call.
979    // Each test creates a fresh client pointed at MOCK_SERVER_URL/fixtures/<id>
980    // so the mock server can serve the fixture response via prefix routing.
981    let call_prefix = if let Some(factory) = client_factory {
982        let factory_name = to_go_name(factory);
983        let fixture_id = &fixture.id;
984        // Determine how to express the API key and base URL for the client
985        // constructor call, depending on which code path was emitted above.
986        let (api_key_expr, base_url_expr) = if has_mock && api_key_var.is_some() {
987            // Env-fallback: local vars emitted above carry the right values.
988            ("apiKey".to_string(), "baseURL".to_string())
989        } else if api_key_var.is_some() {
990            // Skip-unless-set: live API only, no mock fallback.
991            ("apiKey".to_string(), "nil".to_string())
992        } else if fixture.has_host_root_route() {
993            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
994            let _ = writeln!(out, "\tmockURL := os.Getenv(\"{env_key}\")");
995            let _ = writeln!(out, "\tif mockURL == \"\" {{");
996            let _ = writeln!(
997                out,
998                "\t\tmockURL = os.Getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\""
999            );
1000            let _ = writeln!(out, "\t}}");
1001            ("\"test-key\"".to_string(), "&mockURL".to_string())
1002        } else {
1003            let _ = writeln!(
1004                out,
1005                "\tmockURL := os.Getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\""
1006            );
1007            ("\"test-key\"".to_string(), "&mockURL".to_string())
1008        };
1009        let _ = writeln!(
1010            out,
1011            "\tclient, clientErr := {import_alias}.{factory_name}({api_key_expr}, {base_url_expr}, nil, nil, nil)"
1012        );
1013        let _ = writeln!(out, "\tif clientErr != nil {{");
1014        let _ = writeln!(out, "\t\tt.Fatalf(\"create client failed: %v\", clientErr)");
1015        let _ = writeln!(out, "\t}}");
1016        "client".to_string()
1017    } else {
1018        import_alias.to_string()
1019    };
1020
1021    // The Go binding generator wraps the FFI call in `(T, error)` whenever any
1022    // param requires JSON marshalling, even when the underlying Rust function
1023    // does not return Result. Detect that so error-expecting tests emit `_, err :=`
1024    // instead of `err :=` when the binding has a value component.
1025    let binding_returns_error_pre = args
1026        .iter()
1027        .any(|a| matches!(a.arg_type.as_str(), "json_object" | "bytes"));
1028    let effective_returns_result_pre = returns_result || binding_returns_error_pre || client_factory.is_some();
1029
1030    if expects_error {
1031        if effective_returns_result_pre && !returns_void {
1032            let _ = writeln!(out, "\t_, err := {call_prefix}.{function_name}({final_args})");
1033        } else {
1034            let _ = writeln!(out, "\terr := {call_prefix}.{function_name}({final_args})");
1035        }
1036        let _ = writeln!(out, "\tif err == nil {{");
1037        let _ = writeln!(out, "\t\tt.Errorf(\"expected an error, but call succeeded\")");
1038        let _ = writeln!(out, "\t}}");
1039        let _ = writeln!(out, "}}");
1040        return;
1041    }
1042
1043    // Check if any assertion actually uses the result variable.
1044    // If all assertions are skipped (field not on result type), use `_` to avoid
1045    // Go's "declared and not used" compile error.
1046    let has_usable_assertion = fixture.assertions.iter().any(|a| {
1047        if a.assertion_type == "not_error" || a.assertion_type == "error" {
1048            return false;
1049        }
1050        // method_result assertions always use the result variable.
1051        if a.assertion_type == "method_result" {
1052            return true;
1053        }
1054        match &a.field {
1055            Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
1056            _ => true,
1057        }
1058    });
1059
1060    // The Go binding generator (alef-backend-go) wraps the FFI call in `(T, error)`
1061    // whenever any param requires JSON marshalling (Vec, Map, Named struct), even when
1062    // the underlying Rust function does not return Result. So a result_is_simple call
1063    // like `generate_cache_key(parts: &[(String, String)]) -> String` still surfaces in
1064    // Go as `func GenerateCacheKey(parts [][]string) (*string, error)`. Detect that
1065    // here so the test emits `_, err :=` / `result, err :=` instead of `result :=`.
1066    let binding_returns_error = args
1067        .iter()
1068        .any(|a| matches!(a.arg_type.as_str(), "json_object" | "bytes"));
1069    // Client-factory methods always return (value, error) in the Go binding.
1070    let effective_returns_result = returns_result || binding_returns_error || client_factory.is_some();
1071
1072    // For result_is_simple functions, the result variable IS the value (e.g. *string, *bool).
1073    // We create a local `value` that dereferences it so assertions can use a plain type.
1074    // For functions that return (value, error): emit `result, err :=`
1075    // For functions that return only error: emit `err :=`
1076    // For functions that return only a value (result_is_simple, no error): emit `result :=`
1077    if !effective_returns_result && result_is_simple {
1078        // Function returns a single value, no error (e.g. *string, *bool).
1079        let result_binding = if has_usable_assertion {
1080            result_var.to_string()
1081        } else {
1082            "_".to_string()
1083        };
1084        // In Go, `_ :=` is invalid — must use `_ =` for the blank identifier.
1085        let assign_op = if result_binding == "_" { "=" } else { ":=" };
1086        let _ = writeln!(
1087            out,
1088            "\t{result_binding} {assign_op} {call_prefix}.{function_name}({final_args})"
1089        );
1090        if has_usable_assertion && result_binding != "_" {
1091            if result_is_array {
1092                // Array results are slices (not pointers); assign directly without dereference.
1093                let _ = writeln!(out, "\tvalue := {result_var}");
1094            } else {
1095                // Check if ALL simple-result assertions are is_empty/is_null with no field.
1096                // If so, skip dereference — we'll use the pointer directly.
1097                let only_nil_assertions = fixture
1098                    .assertions
1099                    .iter()
1100                    .filter(|a| a.field.as_ref().is_none_or(|f| f.is_empty()))
1101                    .filter(|a| !matches!(a.assertion_type.as_str(), "not_error" | "error"))
1102                    .all(|a| matches!(a.assertion_type.as_str(), "is_empty" | "is_null"));
1103
1104                if !only_nil_assertions {
1105                    // Emit nil check and dereference for simple pointer results.
1106                    let _ = writeln!(out, "\tif {result_var} == nil {{");
1107                    let _ = writeln!(out, "\t\tt.Fatalf(\"expected non-nil result\")");
1108                    let _ = writeln!(out, "\t}}");
1109                    let _ = writeln!(out, "\tvalue := *{result_var}");
1110                }
1111            }
1112        }
1113    } else if !effective_returns_result || returns_void {
1114        // Function returns only error (either returns_result=false, or returns_result=true
1115        // with returns_void=true meaning the Go function signature is `func(...) error`).
1116        let _ = writeln!(out, "\terr := {call_prefix}.{function_name}({final_args})");
1117        let _ = writeln!(out, "\tif err != nil {{");
1118        let _ = writeln!(out, "\t\tt.Fatalf(\"call failed: %v\", err)");
1119        let _ = writeln!(out, "\t}}");
1120        // No result variable to use in assertions.
1121        let _ = writeln!(out, "}}");
1122        return;
1123    } else {
1124        // returns_result = true, returns_void = false: function returns (value, error).
1125        let result_binding = if has_usable_assertion {
1126            result_var.to_string()
1127        } else {
1128            "_".to_string()
1129        };
1130        let _ = writeln!(
1131            out,
1132            "\t{result_binding}, err := {call_prefix}.{function_name}({final_args})"
1133        );
1134        let _ = writeln!(out, "\tif err != nil {{");
1135        let _ = writeln!(out, "\t\tt.Fatalf(\"call failed: %v\", err)");
1136        let _ = writeln!(out, "\t}}");
1137        if result_is_simple && has_usable_assertion && result_binding != "_" {
1138            if result_is_array {
1139                // Array results are slices (not pointers); assign directly without dereference.
1140                let _ = writeln!(out, "\tvalue := {}", result_var);
1141            } else {
1142                // Check if ALL simple-result assertions are is_empty/is_null with no field.
1143                // If so, skip dereference — we'll use the pointer directly.
1144                let only_nil_assertions = fixture
1145                    .assertions
1146                    .iter()
1147                    .filter(|a| a.field.as_ref().is_none_or(|f| f.is_empty()))
1148                    .filter(|a| !matches!(a.assertion_type.as_str(), "not_error" | "error"))
1149                    .all(|a| matches!(a.assertion_type.as_str(), "is_empty" | "is_null"));
1150
1151                if !only_nil_assertions {
1152                    // Emit nil check and dereference for simple pointer results.
1153                    let _ = writeln!(out, "\tif {} == nil {{", result_var);
1154                    let _ = writeln!(out, "\t\tt.Fatalf(\"expected non-nil result\")");
1155                    let _ = writeln!(out, "\t}}");
1156                    let _ = writeln!(out, "\tvalue := *{}", result_var);
1157                }
1158            }
1159        }
1160    }
1161
1162    // For result_is_simple functions, determine if we created a dereferenced `value` variable.
1163    // We skip dereferencing if all simple-result assertions are is_empty/is_null with no field.
1164    let has_deref_value = if result_is_simple && has_usable_assertion && !result_is_array {
1165        let only_nil_assertions = fixture
1166            .assertions
1167            .iter()
1168            .filter(|a| a.field.as_ref().is_none_or(|f| f.is_empty()))
1169            .filter(|a| !matches!(a.assertion_type.as_str(), "not_error" | "error"))
1170            .all(|a| matches!(a.assertion_type.as_str(), "is_empty" | "is_null"));
1171        !only_nil_assertions
1172    } else {
1173        result_is_simple && has_usable_assertion
1174    };
1175
1176    let effective_result_var = if has_deref_value {
1177        "value".to_string()
1178    } else {
1179        result_var.to_string()
1180    };
1181
1182    // Collect optional fields referenced by assertions and emit nil-safe
1183    // dereference blocks so that assertions can use plain string locals.
1184    // Only dereference fields whose assertion values are strings (or that are
1185    // used in string-oriented assertions like equals/contains with string values).
1186    let mut optional_locals: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1187    for assertion in &fixture.assertions {
1188        if let Some(f) = &assertion.field {
1189            if !f.is_empty() {
1190                let resolved = field_resolver.resolve(f);
1191                if field_resolver.is_optional(resolved) && !optional_locals.contains_key(f.as_str()) {
1192                    // Only create deref locals for string-valued fields that are NOT arrays.
1193                    // Array fields (e.g., *[]string) must keep their pointer form so
1194                    // render_assertion can emit strings.Join(*field, " ") rather than
1195                    // treating them as plain strings.
1196                    let is_string_field = assertion.value.as_ref().is_some_and(|v| v.is_string());
1197                    let is_array_field = field_resolver.is_array(resolved);
1198                    if !is_string_field || is_array_field {
1199                        // Non-string optional fields (e.g., *uint64) and array optional
1200                        // fields (e.g., *[]string) are handled by nil guards in render_assertion.
1201                        continue;
1202                    }
1203                    let field_expr = field_resolver.accessor(f, "go", &effective_result_var);
1204                    let local_var = go_param_name(&resolved.replace(['.', '[', ']'], "_"));
1205                    if field_resolver.has_map_access(f) {
1206                        // Go map access returns a value type (string), not a pointer.
1207                        // Use the value directly — empty string means not present.
1208                        let _ = writeln!(out, "\t{local_var} := {field_expr}");
1209                    } else {
1210                        let _ = writeln!(out, "\tvar {local_var} string");
1211                        let _ = writeln!(out, "\tif {field_expr} != nil {{");
1212                        // Use string() cast to handle named string types (e.g. *FinishReason) in
1213                        // addition to plain *string fields — string(*ptr) is a no-op for *string
1214                        // and a safe coercion for any named type whose underlying type is string.
1215                        let _ = writeln!(out, "\t\t{local_var} = string(*{field_expr})");
1216                        let _ = writeln!(out, "\t}}");
1217                    }
1218                    optional_locals.insert(f.clone(), local_var);
1219                }
1220            }
1221        }
1222    }
1223
1224    // Emit assertions, wrapping in nil guards when an intermediate path segment is optional.
1225    for assertion in &fixture.assertions {
1226        if let Some(f) = &assertion.field {
1227            if !f.is_empty() && !optional_locals.contains_key(f.as_str()) {
1228                // Check if any prefix of the dotted path is optional (pointer in Go).
1229                // e.g., "document.nodes" — if "document" is optional, guard the whole block.
1230                let parts: Vec<&str> = f.split('.').collect();
1231                let mut guard_expr: Option<String> = None;
1232                for i in 1..parts.len() {
1233                    let prefix = parts[..i].join(".");
1234                    let resolved_prefix = field_resolver.resolve(&prefix);
1235                    if field_resolver.is_optional(resolved_prefix) {
1236                        let accessor = field_resolver.accessor(&prefix, "go", &effective_result_var);
1237                        guard_expr = Some(accessor);
1238                        break;
1239                    }
1240                }
1241                if let Some(guard) = guard_expr {
1242                    // Only emit nil guard if the assertion will actually produce code
1243                    // (not just a skip comment), to avoid empty branches (SA9003).
1244                    if field_resolver.is_valid_for_result(f) {
1245                        let _ = writeln!(out, "\tif {guard} != nil {{");
1246                        // Render into a temporary buffer so we can re-indent by one
1247                        // tab level to sit inside the nil-guard block.
1248                        let mut nil_buf = String::new();
1249                        render_assertion(
1250                            &mut nil_buf,
1251                            assertion,
1252                            &effective_result_var,
1253                            import_alias,
1254                            field_resolver,
1255                            &optional_locals,
1256                            result_is_simple,
1257                            result_is_array,
1258                        );
1259                        for line in nil_buf.lines() {
1260                            let _ = writeln!(out, "\t{line}");
1261                        }
1262                        let _ = writeln!(out, "\t}}");
1263                    } else {
1264                        render_assertion(
1265                            out,
1266                            assertion,
1267                            &effective_result_var,
1268                            import_alias,
1269                            field_resolver,
1270                            &optional_locals,
1271                            result_is_simple,
1272                            result_is_array,
1273                        );
1274                    }
1275                    continue;
1276                }
1277            }
1278        }
1279        render_assertion(
1280            out,
1281            assertion,
1282            &effective_result_var,
1283            import_alias,
1284            field_resolver,
1285            &optional_locals,
1286            result_is_simple,
1287            result_is_array,
1288        );
1289    }
1290
1291    let _ = writeln!(out, "}}");
1292}
1293
1294/// Render an HTTP server test function using net/http against MOCK_SERVER_URL.
1295///
1296/// Delegates to the shared driver [`client::http_call::render_http_test`] via
1297/// [`GoTestClientRenderer`]. The emitted test shape is unchanged: `func Test_<Name>(t *testing.T)`
1298/// with a `net/http` client that hits `$MOCK_SERVER_URL/fixtures/<id>`.
1299fn render_http_test_function(out: &mut String, fixture: &Fixture) {
1300    client::http_call::render_http_test(out, &GoTestClientRenderer, fixture);
1301}
1302
1303// ---------------------------------------------------------------------------
1304// HTTP test rendering — GoTestClientRenderer
1305// ---------------------------------------------------------------------------
1306
1307/// Go `net/http` test renderer.
1308///
1309/// Go HTTP e2e tests send a request to `$MOCK_SERVER_URL/fixtures/<id>` using
1310/// the standard library `net/http` client. The trait primitives emit the
1311/// request-build, response-capture, and assertion code that the previous
1312/// monolithic renderer produced, so generated output is unchanged after the
1313/// migration.
1314struct GoTestClientRenderer;
1315
1316impl client::TestClientRenderer for GoTestClientRenderer {
1317    fn language_name(&self) -> &'static str {
1318        "go"
1319    }
1320
1321    /// Go test names use `UpperCamelCase` so they form valid exported identifiers
1322    /// (e.g. `Test_MyFixtureId`). Override the default `sanitize_ident` which
1323    /// produces `lower_snake_case`.
1324    fn sanitize_test_name(&self, id: &str) -> String {
1325        id.to_upper_camel_case()
1326    }
1327
1328    /// Emit `func Test_<fn_name>(t *testing.T) {`, a description comment, and the
1329    /// `baseURL` / request scaffolding. Skipped fixtures get `t.Skip(...)` inline.
1330    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
1331        let _ = writeln!(out, "func Test_{fn_name}(t *testing.T) {{");
1332        let _ = writeln!(out, "\t// {description}");
1333        if let Some(reason) = skip_reason {
1334            let escaped = go_string_literal(reason);
1335            let _ = writeln!(out, "\tt.Skip({escaped})");
1336        }
1337    }
1338
1339    fn render_test_close(&self, out: &mut String) {
1340        let _ = writeln!(out, "}}");
1341    }
1342
1343    /// Emit the full `net/http` request scaffolding: URL construction, body,
1344    /// headers, cookies, a no-redirect client, and `io.ReadAll` for the body.
1345    ///
1346    /// `bodyBytes` is always declared (with `_ = bodyBytes` to avoid the Go
1347    /// "declared and not used" compile error on tests with no body assertion).
1348    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
1349        let method = ctx.method.to_uppercase();
1350        let path = ctx.path;
1351
1352        let _ = writeln!(out, "\tbaseURL := os.Getenv(\"MOCK_SERVER_URL\")");
1353        let _ = writeln!(out, "\tif baseURL == \"\" {{");
1354        let _ = writeln!(out, "\t\tbaseURL = \"http://localhost:8080\"");
1355        let _ = writeln!(out, "\t}}");
1356
1357        // Build request body expression.
1358        let body_expr = if let Some(body) = ctx.body {
1359            let json = serde_json::to_string(body).unwrap_or_default();
1360            let escaped = go_string_literal(&json);
1361            format!("strings.NewReader({})", escaped)
1362        } else {
1363            "strings.NewReader(\"\")".to_string()
1364        };
1365
1366        let _ = writeln!(out, "\tbody := {body_expr}");
1367        let _ = writeln!(
1368            out,
1369            "\treq, err := http.NewRequest(\"{method}\", baseURL+\"{path}\", body)"
1370        );
1371        let _ = writeln!(out, "\tif err != nil {{");
1372        let _ = writeln!(out, "\t\tt.Fatalf(\"new request failed: %v\", err)");
1373        let _ = writeln!(out, "\t}}");
1374
1375        // Content-Type header (only when a body is present).
1376        if ctx.body.is_some() {
1377            let content_type = ctx.content_type.unwrap_or("application/json");
1378            let _ = writeln!(out, "\treq.Header.Set(\"Content-Type\", \"{content_type}\")");
1379        }
1380
1381        // Explicit request headers (sorted for deterministic output).
1382        let mut header_names: Vec<&String> = ctx.headers.keys().collect();
1383        header_names.sort();
1384        for name in header_names {
1385            let value = &ctx.headers[name];
1386            let escaped_name = go_string_literal(name);
1387            let escaped_value = go_string_literal(value);
1388            let _ = writeln!(out, "\treq.Header.Set({escaped_name}, {escaped_value})");
1389        }
1390
1391        // Cookies.
1392        if !ctx.cookies.is_empty() {
1393            let mut cookie_names: Vec<&String> = ctx.cookies.keys().collect();
1394            cookie_names.sort();
1395            for name in cookie_names {
1396                let value = &ctx.cookies[name];
1397                let escaped_name = go_string_literal(name);
1398                let escaped_value = go_string_literal(value);
1399                let _ = writeln!(
1400                    out,
1401                    "\treq.AddCookie(&http.Cookie{{Name: {escaped_name}, Value: {escaped_value}}})"
1402                );
1403            }
1404        }
1405
1406        // No-redirect client so 3xx fixtures assert the redirect response itself.
1407        let _ = writeln!(out, "\tnoRedirectClient := &http.Client{{");
1408        let _ = writeln!(
1409            out,
1410            "\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {{"
1411        );
1412        let _ = writeln!(out, "\t\t\treturn http.ErrUseLastResponse");
1413        let _ = writeln!(out, "\t\t}},");
1414        let _ = writeln!(out, "\t}}");
1415        let _ = writeln!(out, "\tresp, err := noRedirectClient.Do(req)");
1416        let _ = writeln!(out, "\tif err != nil {{");
1417        let _ = writeln!(out, "\t\tt.Fatalf(\"request failed: %v\", err)");
1418        let _ = writeln!(out, "\t}}");
1419        let _ = writeln!(out, "\tdefer resp.Body.Close()");
1420
1421        // Always read the response body so body-assertion methods can reference
1422        // `bodyBytes`. Suppress the "declared and not used" compile error with
1423        // `_ = bodyBytes` for tests that have no body assertion.
1424        let _ = writeln!(out, "\tbodyBytes, err := io.ReadAll(resp.Body)");
1425        let _ = writeln!(out, "\tif err != nil {{");
1426        let _ = writeln!(out, "\t\tt.Fatalf(\"read body failed: %v\", err)");
1427        let _ = writeln!(out, "\t}}");
1428        let _ = writeln!(out, "\t_ = bodyBytes");
1429    }
1430
1431    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
1432        let _ = writeln!(out, "\tif resp.StatusCode != {status} {{");
1433        let _ = writeln!(out, "\t\tt.Fatalf(\"status: got %d want {status}\", resp.StatusCode)");
1434        let _ = writeln!(out, "\t}}");
1435    }
1436
1437    /// Emit a header assertion, skipping special tokens (`<<present>>`, `<<absent>>`,
1438    /// `<<uuid>>`) and hop-by-hop headers (`Connection`) that `net/http` strips.
1439    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
1440        // Skip special-token assertions.
1441        if matches!(expected, "<<absent>>" | "<<present>>" | "<<uuid>>") {
1442            return;
1443        }
1444        // Connection is a hop-by-hop header that Go's net/http strips.
1445        if name.eq_ignore_ascii_case("connection") {
1446            return;
1447        }
1448        let escaped_name = go_string_literal(name);
1449        let escaped_value = go_string_literal(expected);
1450        let _ = writeln!(
1451            out,
1452            "\tif !strings.Contains(resp.Header.Get({escaped_name}), {escaped_value}) {{"
1453        );
1454        let _ = writeln!(
1455            out,
1456            "\t\tt.Fatalf(\"header %s mismatch: got %q want to contain %q\", {escaped_name}, resp.Header.Get({escaped_name}), {escaped_value})"
1457        );
1458        let _ = writeln!(out, "\t}}");
1459    }
1460
1461    /// Emit an exact-equality body assertion.
1462    ///
1463    /// JSON objects and arrays are round-tripped via `json.Unmarshal` + `reflect.DeepEqual`.
1464    /// Scalar values are compared as trimmed strings.
1465    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1466        match expected {
1467            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
1468                let json_str = serde_json::to_string(expected).unwrap_or_default();
1469                let escaped = go_string_literal(&json_str);
1470                let _ = writeln!(out, "\tvar got any");
1471                let _ = writeln!(out, "\tvar want any");
1472                let _ = writeln!(out, "\tif err := json.Unmarshal(bodyBytes, &got); err != nil {{");
1473                let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal got: %v\", err)");
1474                let _ = writeln!(out, "\t}}");
1475                let _ = writeln!(
1476                    out,
1477                    "\tif err := json.Unmarshal([]byte({escaped}), &want); err != nil {{"
1478                );
1479                let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal want: %v\", err)");
1480                let _ = writeln!(out, "\t}}");
1481                let _ = writeln!(out, "\tif !reflect.DeepEqual(got, want) {{");
1482                let _ = writeln!(out, "\t\tt.Fatalf(\"body mismatch: got %v want %v\", got, want)");
1483                let _ = writeln!(out, "\t}}");
1484            }
1485            serde_json::Value::String(s) => {
1486                let escaped = go_string_literal(s);
1487                let _ = writeln!(out, "\twant := {escaped}");
1488                let _ = writeln!(out, "\tif strings.TrimSpace(string(bodyBytes)) != want {{");
1489                let _ = writeln!(out, "\t\tt.Fatalf(\"body: got %q want %q\", string(bodyBytes), want)");
1490                let _ = writeln!(out, "\t}}");
1491            }
1492            other => {
1493                let escaped = go_string_literal(&other.to_string());
1494                let _ = writeln!(out, "\twant := {escaped}");
1495                let _ = writeln!(out, "\tif strings.TrimSpace(string(bodyBytes)) != want {{");
1496                let _ = writeln!(out, "\t\tt.Fatalf(\"body: got %q want %q\", string(bodyBytes), want)");
1497                let _ = writeln!(out, "\t}}");
1498            }
1499        }
1500    }
1501
1502    /// Emit partial-body assertions: every key in `expected` must appear in the
1503    /// parsed JSON response with the matching value.
1504    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1505        if let Some(obj) = expected.as_object() {
1506            let _ = writeln!(out, "\tvar _partialGot map[string]any");
1507            let _ = writeln!(
1508                out,
1509                "\tif err := json.Unmarshal(bodyBytes, &_partialGot); err != nil {{"
1510            );
1511            let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal partial: %v\", err)");
1512            let _ = writeln!(out, "\t}}");
1513            for (key, val) in obj {
1514                let escaped_key = go_string_literal(key);
1515                let json_val = serde_json::to_string(val).unwrap_or_default();
1516                let escaped_val = go_string_literal(&json_val);
1517                let _ = writeln!(out, "\t{{");
1518                let _ = writeln!(out, "\t\tvar _wantVal any");
1519                let _ = writeln!(
1520                    out,
1521                    "\t\tif err := json.Unmarshal([]byte({escaped_val}), &_wantVal); err != nil {{"
1522                );
1523                let _ = writeln!(out, "\t\t\tt.Fatalf(\"json unmarshal partial want: %v\", err)");
1524                let _ = writeln!(out, "\t\t}}");
1525                let _ = writeln!(
1526                    out,
1527                    "\t\tif !reflect.DeepEqual(_partialGot[{escaped_key}], _wantVal) {{"
1528                );
1529                let _ = writeln!(
1530                    out,
1531                    "\t\t\tt.Fatalf(\"partial body field {key}: got %v want %v\", _partialGot[{escaped_key}], _wantVal)"
1532                );
1533                let _ = writeln!(out, "\t\t}}");
1534                let _ = writeln!(out, "\t}}");
1535            }
1536        }
1537    }
1538
1539    /// Emit validation-error assertions for 422 responses.
1540    ///
1541    /// Checks that each expected `msg` appears in at least one element of the
1542    /// parsed body's `"errors"` array.
1543    fn render_assert_validation_errors(
1544        &self,
1545        out: &mut String,
1546        _response_var: &str,
1547        errors: &[ValidationErrorExpectation],
1548    ) {
1549        let _ = writeln!(out, "\tvar _veBody map[string]any");
1550        let _ = writeln!(out, "\tif err := json.Unmarshal(bodyBytes, &_veBody); err != nil {{");
1551        let _ = writeln!(out, "\t\tt.Fatalf(\"json unmarshal validation errors: %v\", err)");
1552        let _ = writeln!(out, "\t}}");
1553        let _ = writeln!(out, "\t_veErrors, _ := _veBody[\"errors\"].([]any)");
1554        for ve in errors {
1555            let escaped_msg = go_string_literal(&ve.msg);
1556            let _ = writeln!(out, "\t{{");
1557            let _ = writeln!(out, "\t\t_found := false");
1558            let _ = writeln!(out, "\t\tfor _, _e := range _veErrors {{");
1559            let _ = writeln!(out, "\t\t\tif _em, ok := _e.(map[string]any); ok {{");
1560            let _ = writeln!(
1561                out,
1562                "\t\t\t\tif _msg, ok := _em[\"msg\"].(string); ok && strings.Contains(_msg, {escaped_msg}) {{"
1563            );
1564            let _ = writeln!(out, "\t\t\t\t\t_found = true");
1565            let _ = writeln!(out, "\t\t\t\t\tbreak");
1566            let _ = writeln!(out, "\t\t\t\t}}");
1567            let _ = writeln!(out, "\t\t\t}}");
1568            let _ = writeln!(out, "\t\t}}");
1569            let _ = writeln!(out, "\t\tif !_found {{");
1570            let _ = writeln!(
1571                out,
1572                "\t\t\tt.Fatalf(\"validation error with msg containing %q not found in errors\", {escaped_msg})"
1573            );
1574            let _ = writeln!(out, "\t\t}}");
1575            let _ = writeln!(out, "\t}}");
1576        }
1577    }
1578}
1579
1580/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1581///
1582/// Returns `(setup_lines, args_string)`.
1583///
1584/// `options_ptr` — when `true`, `json_object` args with an `options_type` are
1585/// passed as a Go pointer (`*OptionsType`): absent/empty → `nil`, present →
1586/// `&varName` after JSON unmarshal.
1587fn build_args_and_setup(
1588    input: &serde_json::Value,
1589    args: &[crate::config::ArgMapping],
1590    import_alias: &str,
1591    options_type: Option<&str>,
1592    fixture: &crate::fixture::Fixture,
1593    options_ptr: bool,
1594    expects_error: bool,
1595) -> (Vec<String>, String) {
1596    let fixture_id = &fixture.id;
1597    use heck::ToUpperCamelCase;
1598
1599    if args.is_empty() {
1600        return (Vec::new(), String::new());
1601    }
1602
1603    let mut setup_lines: Vec<String> = Vec::new();
1604    let mut parts: Vec<String> = Vec::new();
1605
1606    for arg in args {
1607        if arg.arg_type == "mock_url" {
1608            if fixture.has_host_root_route() {
1609                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1610                setup_lines.push(format!("{} := os.Getenv(\"{env_key}\")", arg.name));
1611                setup_lines.push(format!(
1612                    "if {} == \"\" {{ {} = os.Getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\" }}",
1613                    arg.name, arg.name
1614                ));
1615            } else {
1616                setup_lines.push(format!(
1617                    "{} := os.Getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\"",
1618                    arg.name,
1619                ));
1620            }
1621            parts.push(arg.name.clone());
1622            continue;
1623        }
1624
1625        if arg.arg_type == "handle" {
1626            // Generate a CreateEngine (or equivalent) call and pass the variable.
1627            let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
1628            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1629            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1630            // When the fixture expects an error (validation test), engine creation
1631            // is the error source. Assert the error and return so the test passes
1632            // without proceeding to the (unreachable) function call.
1633            let create_err_handler = if expects_error {
1634                "assert.Error(t, createErr)\n\t\treturn".to_string()
1635            } else {
1636                "t.Fatalf(\"create handle failed: %v\", createErr)".to_string()
1637            };
1638            if config_value.is_null()
1639                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1640            {
1641                setup_lines.push(format!(
1642                    "{name}, createErr := {import_alias}.{constructor_name}(nil)\n\tif createErr != nil {{\n\t\t{create_err_handler}\n\t}}",
1643                    name = arg.name,
1644                ));
1645            } else {
1646                let json_str = serde_json::to_string(config_value).unwrap_or_default();
1647                let go_literal = go_string_literal(&json_str);
1648                let name = &arg.name;
1649                setup_lines.push(format!(
1650                    "var {name}Config {import_alias}.CrawlConfig\n\tif err := json.Unmarshal([]byte({go_literal}), &{name}Config); err != nil {{\n\t\tt.Fatalf(\"config parse failed: %v\", err)\n\t}}"
1651                ));
1652                setup_lines.push(format!(
1653                    "{name}, createErr := {import_alias}.{constructor_name}(&{name}Config)\n\tif createErr != nil {{\n\t\t{create_err_handler}\n\t}}"
1654                ));
1655            }
1656            parts.push(arg.name.clone());
1657            continue;
1658        }
1659
1660        let val: Option<&serde_json::Value> = if arg.field == "input" {
1661            Some(input)
1662        } else {
1663            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1664            input.get(field)
1665        };
1666
1667        // file_path args are fixture-relative paths under `test_documents/`. The Go test
1668        // runner's TestMain (in main_test.go) already does `os.Chdir(test_documents)` so
1669        // tests can pass these relative strings directly; no additional resolution needed.
1670
1671        // Handle bytes type: fixture stores base64-encoded bytes.
1672        // Emit a Go base64.StdEncoding.DecodeString call to decode at runtime.
1673        if arg.arg_type == "bytes" {
1674            let var_name = format!("{}Bytes", arg.name);
1675            match val {
1676                None | Some(serde_json::Value::Null) => {
1677                    if arg.optional {
1678                        parts.push("nil".to_string());
1679                    } else {
1680                        parts.push("[]byte{}".to_string());
1681                    }
1682                }
1683                Some(serde_json::Value::String(s)) => {
1684                    // Bytes args whose fixture value is a string are fixture-relative paths into
1685                    // the repo-root `test_documents/` directory (matching the rust e2e codegen
1686                    // convention). The Go test runner's TestMain chdirs into test_documents/, so
1687                    // a bare relative path resolves correctly via os.ReadFile.
1688                    let go_path = go_string_literal(s);
1689                    setup_lines.push(format!(
1690                        "{var_name}, {var_name}Err := os.ReadFile({go_path})\n\tif {var_name}Err != nil {{\n\t\tt.Fatalf(\"read fixture {s}: %v\", {var_name}Err)\n\t}}"
1691                    ));
1692                    parts.push(var_name);
1693                }
1694                Some(other) => {
1695                    parts.push(format!("[]byte({})", json_to_go(other)));
1696                }
1697            }
1698            continue;
1699        }
1700
1701        match val {
1702            None | Some(serde_json::Value::Null) if arg.optional => {
1703                // Optional arg absent: emit Go zero/nil for the type.
1704                match arg.arg_type.as_str() {
1705                    "string" => {
1706                        // Optional string in Go bindings is *string → nil.
1707                        parts.push("nil".to_string());
1708                    }
1709                    "json_object" => {
1710                        if options_ptr {
1711                            // Pointer options type (*OptionsType): absent → nil.
1712                            parts.push("nil".to_string());
1713                        } else if let Some(opts_type) = options_type {
1714                            // Value options type: zero-value struct.
1715                            parts.push(format!("{import_alias}.{opts_type}{{}}"));
1716                        } else {
1717                            parts.push("nil".to_string());
1718                        }
1719                    }
1720                    _ => {
1721                        parts.push("nil".to_string());
1722                    }
1723                }
1724            }
1725            None | Some(serde_json::Value::Null) => {
1726                // Required arg with no fixture value: pass a language-appropriate default.
1727                let default_val = match arg.arg_type.as_str() {
1728                    "string" => "\"\"".to_string(),
1729                    "int" | "integer" | "i64" => "0".to_string(),
1730                    "float" | "number" => "0.0".to_string(),
1731                    "bool" | "boolean" => "false".to_string(),
1732                    "json_object" => {
1733                        if options_ptr {
1734                            // Pointer options type (*OptionsType): absent → nil.
1735                            "nil".to_string()
1736                        } else if let Some(opts_type) = options_type {
1737                            format!("{import_alias}.{opts_type}{{}}")
1738                        } else {
1739                            "nil".to_string()
1740                        }
1741                    }
1742                    _ => "nil".to_string(),
1743                };
1744                parts.push(default_val);
1745            }
1746            Some(v) => {
1747                match arg.arg_type.as_str() {
1748                    "json_object" => {
1749                        // JSON arrays unmarshal into []string (Go slices).
1750                        // JSON objects with a known options_type unmarshal into that type.
1751                        let is_array = v.is_array();
1752                        let is_empty_obj = !is_array && v.is_object() && v.as_object().is_some_and(|o| o.is_empty());
1753                        if is_empty_obj {
1754                            if options_ptr {
1755                                // Pointer options type: empty object → nil.
1756                                parts.push("nil".to_string());
1757                            } else if let Some(opts_type) = options_type {
1758                                parts.push(format!("{import_alias}.{opts_type}{{}}"));
1759                            } else {
1760                                parts.push("nil".to_string());
1761                            }
1762                        } else if is_array {
1763                            // Array type — unmarshal into a Go slice. Honor `go_type` for a
1764                            // fully explicit Go type (e.g. `"kreuzberg.BatchBytesItem"`), fall
1765                            // back to deriving the slice type from `element_type`, defaulting
1766                            // to `[]string` for unknown types.
1767                            let go_slice_type = if let Some(go_t) = arg.go_type.as_deref() {
1768                                // go_type is the slice element type — wrap it in [].
1769                                // If it already starts with '[' the user specified the full
1770                                // slice type; use it verbatim.
1771                                if go_t.starts_with('[') {
1772                                    go_t.to_string()
1773                                } else {
1774                                    // Qualify unqualified types (e.g., "BatchBytesItem" → "kreuzberg.BatchBytesItem")
1775                                    let qualified = if go_t.contains('.') {
1776                                        go_t.to_string()
1777                                    } else {
1778                                        format!("{import_alias}.{go_t}")
1779                                    };
1780                                    format!("[]{qualified}")
1781                                }
1782                            } else {
1783                                element_type_to_go_slice(arg.element_type.as_deref(), import_alias)
1784                            };
1785                            // Convert JSON for Go compatibility (e.g., byte arrays → base64 strings)
1786                            let converted_v = convert_json_for_go(v.clone());
1787                            let json_str = serde_json::to_string(&converted_v).unwrap_or_default();
1788                            let go_literal = go_string_literal(&json_str);
1789                            let var_name = &arg.name;
1790                            setup_lines.push(format!(
1791                                "var {var_name} {go_slice_type}\n\tif err := json.Unmarshal([]byte({go_literal}), &{var_name}); err != nil {{\n\t\tt.Fatalf(\"config parse failed: %v\", err)\n\t}}"
1792                            ));
1793                            parts.push(var_name.to_string());
1794                        } else if let Some(opts_type) = options_type {
1795                            // Object with known type — unmarshal into typed struct.
1796                            // When options_ptr is set, the Go struct uses snake_case JSON
1797                            // field tags and lowercase/snake_case enum values.  Remap the
1798                            // fixture's camelCase keys and PascalCase enum string values.
1799                            let remapped_v = if options_ptr {
1800                                convert_json_for_go(v.clone())
1801                            } else {
1802                                v.clone()
1803                            };
1804                            let json_str = serde_json::to_string(&remapped_v).unwrap_or_default();
1805                            let go_literal = go_string_literal(&json_str);
1806                            let var_name = &arg.name;
1807                            setup_lines.push(format!(
1808                                "var {var_name} {import_alias}.{opts_type}\n\tif err := json.Unmarshal([]byte({go_literal}), &{var_name}); err != nil {{\n\t\tt.Fatalf(\"config parse failed: %v\", err)\n\t}}"
1809                            ));
1810                            // Pass as pointer when options_ptr is set.
1811                            let arg_expr = if options_ptr {
1812                                format!("&{var_name}")
1813                            } else {
1814                                var_name.to_string()
1815                            };
1816                            parts.push(arg_expr);
1817                        } else {
1818                            parts.push(json_to_go(v));
1819                        }
1820                    }
1821                    "string" if arg.optional => {
1822                        // Optional string in Go is *string — take address of a local.
1823                        let var_name = format!("{}Val", arg.name);
1824                        let go_val = json_to_go(v);
1825                        setup_lines.push(format!("{var_name} := {go_val}"));
1826                        parts.push(format!("&{var_name}"));
1827                    }
1828                    _ => {
1829                        parts.push(json_to_go(v));
1830                    }
1831                }
1832            }
1833        }
1834    }
1835
1836    (setup_lines, parts.join(", "))
1837}
1838
1839#[allow(clippy::too_many_arguments)]
1840fn render_assertion(
1841    out: &mut String,
1842    assertion: &Assertion,
1843    result_var: &str,
1844    import_alias: &str,
1845    field_resolver: &FieldResolver,
1846    optional_locals: &std::collections::HashMap<String, String>,
1847    result_is_simple: bool,
1848    result_is_array: bool,
1849) {
1850    // Handle synthetic / derived fields before the is_valid_for_result check
1851    // so they are never treated as struct field accesses on the result.
1852    if !result_is_simple {
1853        if let Some(f) = &assertion.field {
1854            // embed_texts returns *[][]float32; the embedding matrix is *result_var.
1855            // We emit inline func() expressions so we don't need additional variables.
1856            let embed_deref = format!("(*{result_var})");
1857            match f.as_str() {
1858                "chunks_have_content" => {
1859                    let pred = format!(
1860                        "func() bool {{ chunks := {result_var}.Chunks; if chunks == nil {{ return false }}; for _, c := range *chunks {{ if c.Content == \"\" {{ return false }} }}; return true }}()"
1861                    );
1862                    match assertion.assertion_type.as_str() {
1863                        "is_true" => {
1864                            let _ = writeln!(out, "\tassert.True(t, {pred}, \"expected true\")");
1865                        }
1866                        "is_false" => {
1867                            let _ = writeln!(out, "\tassert.False(t, {pred}, \"expected false\")");
1868                        }
1869                        _ => {
1870                            let _ = writeln!(out, "\t// skipped: unsupported assertion type on synthetic field '{f}'");
1871                        }
1872                    }
1873                    return;
1874                }
1875                "chunks_have_embeddings" => {
1876                    let pred = format!(
1877                        "func() bool {{ chunks := {result_var}.Chunks; if chunks == nil {{ return false }}; for _, c := range *chunks {{ if c.Embedding == nil || len(*c.Embedding) == 0 {{ return false }} }}; return true }}()"
1878                    );
1879                    match assertion.assertion_type.as_str() {
1880                        "is_true" => {
1881                            let _ = writeln!(out, "\tassert.True(t, {pred}, \"expected true\")");
1882                        }
1883                        "is_false" => {
1884                            let _ = writeln!(out, "\tassert.False(t, {pred}, \"expected false\")");
1885                        }
1886                        _ => {
1887                            let _ = writeln!(out, "\t// skipped: unsupported assertion type on synthetic field '{f}'");
1888                        }
1889                    }
1890                    return;
1891                }
1892                "embeddings" => {
1893                    match assertion.assertion_type.as_str() {
1894                        "count_equals" => {
1895                            if let Some(val) = &assertion.value {
1896                                if let Some(n) = val.as_u64() {
1897                                    let _ = writeln!(
1898                                        out,
1899                                        "\tassert.Equal(t, {n}, len({embed_deref}), \"expected exactly {n} elements\")"
1900                                    );
1901                                }
1902                            }
1903                        }
1904                        "count_min" => {
1905                            if let Some(val) = &assertion.value {
1906                                if let Some(n) = val.as_u64() {
1907                                    let _ = writeln!(
1908                                        out,
1909                                        "\tassert.GreaterOrEqual(t, len({embed_deref}), {n}, \"expected at least {n} elements\")"
1910                                    );
1911                                }
1912                            }
1913                        }
1914                        "not_empty" => {
1915                            let _ = writeln!(
1916                                out,
1917                                "\tassert.NotEmpty(t, {embed_deref}, \"expected non-empty embeddings\")"
1918                            );
1919                        }
1920                        "is_empty" => {
1921                            let _ = writeln!(out, "\tassert.Empty(t, {embed_deref}, \"expected empty embeddings\")");
1922                        }
1923                        _ => {
1924                            let _ = writeln!(
1925                                out,
1926                                "\t// skipped: unsupported assertion type on synthetic field 'embeddings'"
1927                            );
1928                        }
1929                    }
1930                    return;
1931                }
1932                "embedding_dimensions" => {
1933                    let expr = format!(
1934                        "func() int {{ if len({embed_deref}) == 0 {{ return 0 }}; return len({embed_deref}[0]) }}()"
1935                    );
1936                    match assertion.assertion_type.as_str() {
1937                        "equals" => {
1938                            if let Some(val) = &assertion.value {
1939                                if let Some(n) = val.as_u64() {
1940                                    let _ = writeln!(
1941                                        out,
1942                                        "\tif {expr} != {n} {{\n\t\tt.Errorf(\"equals mismatch: got %v\", {expr})\n\t}}"
1943                                    );
1944                                }
1945                            }
1946                        }
1947                        "greater_than" => {
1948                            if let Some(val) = &assertion.value {
1949                                if let Some(n) = val.as_u64() {
1950                                    let _ = writeln!(out, "\tassert.Greater(t, {expr}, {n}, \"expected > {n}\")");
1951                                }
1952                            }
1953                        }
1954                        _ => {
1955                            let _ = writeln!(
1956                                out,
1957                                "\t// skipped: unsupported assertion type on synthetic field 'embedding_dimensions'"
1958                            );
1959                        }
1960                    }
1961                    return;
1962                }
1963                "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1964                    let pred = match f.as_str() {
1965                        "embeddings_valid" => {
1966                            format!(
1967                                "func() bool {{ for _, e := range {embed_deref} {{ if len(e) == 0 {{ return false }} }}; return true }}()"
1968                            )
1969                        }
1970                        "embeddings_finite" => {
1971                            format!(
1972                                "func() bool {{ for _, e := range {embed_deref} {{ for _, v := range e {{ if v != v || v == float32(1.0/0.0) || v == float32(-1.0/0.0) {{ return false }} }} }}; return true }}()"
1973                            )
1974                        }
1975                        "embeddings_non_zero" => {
1976                            format!(
1977                                "func() bool {{ for _, e := range {embed_deref} {{ hasNonZero := false; for _, v := range e {{ if v != 0 {{ hasNonZero = true; break }} }}; if !hasNonZero {{ return false }} }}; return true }}()"
1978                            )
1979                        }
1980                        "embeddings_normalized" => {
1981                            format!(
1982                                "func() bool {{ for _, e := range {embed_deref} {{ var n float64; for _, v := range e {{ n += float64(v) * float64(v) }}; if n < 0.999 || n > 1.001 {{ return false }} }}; return true }}()"
1983                            )
1984                        }
1985                        _ => unreachable!(),
1986                    };
1987                    match assertion.assertion_type.as_str() {
1988                        "is_true" => {
1989                            let _ = writeln!(out, "\tassert.True(t, {pred}, \"expected true\")");
1990                        }
1991                        "is_false" => {
1992                            let _ = writeln!(out, "\tassert.False(t, {pred}, \"expected false\")");
1993                        }
1994                        _ => {
1995                            let _ = writeln!(out, "\t// skipped: unsupported assertion type on synthetic field '{f}'");
1996                        }
1997                    }
1998                    return;
1999                }
2000                // ---- keywords / keywords_count ----
2001                // Go ExtractionResult does not expose extracted_keywords; skip.
2002                "keywords" | "keywords_count" => {
2003                    let _ = writeln!(out, "\t// skipped: field '{f}' not available on Go ExtractionResult");
2004                    return;
2005                }
2006                _ => {}
2007            }
2008        }
2009    }
2010
2011    // Skip assertions on fields that don't exist on the result type.
2012    // When result_is_simple, all field assertions operate on the scalar result directly.
2013    if !result_is_simple {
2014        if let Some(f) = &assertion.field {
2015            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
2016                let _ = writeln!(out, "\t// skipped: field '{f}' not available on result type");
2017                return;
2018            }
2019        }
2020    }
2021
2022    let field_expr = if result_is_simple {
2023        // The result IS the value — field access is irrelevant.
2024        result_var.to_string()
2025    } else {
2026        match &assertion.field {
2027            Some(f) if !f.is_empty() => {
2028                // Use the local variable if the field was dereferenced above.
2029                if let Some(local_var) = optional_locals.get(f.as_str()) {
2030                    local_var.clone()
2031                } else {
2032                    field_resolver.accessor(f, "go", result_var)
2033                }
2034            }
2035            _ => result_var.to_string(),
2036        }
2037    };
2038
2039    // Check if the field (after resolution) is optional, which means it's a pointer in Go.
2040    // Also check if a `.length` suffix's parent is optional (e.g., metadata.headings.length
2041    // where metadata.headings is optional → len() needs dereference).
2042    let is_optional = assertion
2043        .field
2044        .as_ref()
2045        .map(|f| {
2046            let resolved = field_resolver.resolve(f);
2047            let check_path = resolved
2048                .strip_suffix(".length")
2049                .or_else(|| resolved.strip_suffix(".count"))
2050                .or_else(|| resolved.strip_suffix(".size"))
2051                .unwrap_or(resolved);
2052            field_resolver.is_optional(check_path) && !optional_locals.contains_key(f.as_str())
2053        })
2054        .unwrap_or(false);
2055
2056    // When field_expr is `len(X)` and X is an optional (pointer) field, rewrite to `len(*X)`
2057    // and we'll wrap with a nil guard in the assertion handlers.
2058    // However, slices are already nil-able and should not be dereferenced.
2059    let field_is_array_for_len = assertion
2060        .field
2061        .as_ref()
2062        .map(|f| {
2063            let resolved = field_resolver.resolve(f);
2064            let check_path = resolved
2065                .strip_suffix(".length")
2066                .or_else(|| resolved.strip_suffix(".count"))
2067                .or_else(|| resolved.strip_suffix(".size"))
2068                .unwrap_or(resolved);
2069            field_resolver.is_array(check_path)
2070        })
2071        .unwrap_or(false);
2072    let field_expr =
2073        if is_optional && field_expr.starts_with("len(") && field_expr.ends_with(')') && !field_is_array_for_len {
2074            let inner = &field_expr[4..field_expr.len() - 1];
2075            format!("len(*{inner})")
2076        } else {
2077            field_expr
2078        };
2079    // Build the nil-guard expression for the inner pointer (without len wrapper).
2080    let nil_guard_expr = if is_optional && field_expr.starts_with("len(*") {
2081        Some(field_expr[5..field_expr.len() - 1].to_string())
2082    } else {
2083        None
2084    };
2085
2086    // For optional non-string fields that weren't dereferenced into locals,
2087    // we need to dereference the pointer in comparisons.
2088    // However, slices are already nil-able and should not be dereferenced.
2089    let field_is_slice = assertion
2090        .field
2091        .as_ref()
2092        .map(|f| field_resolver.is_array(field_resolver.resolve(f)))
2093        .unwrap_or(false);
2094    let deref_field_expr = if is_optional && !field_expr.starts_with("len(") && !field_is_slice {
2095        format!("*{field_expr}")
2096    } else {
2097        field_expr.clone()
2098    };
2099
2100    // Detect array element access (e.g., `result.Assets[0].ContentHash`).
2101    // When the field_expr contains `[0]`, we must guard against an out-of-bounds
2102    // panic by checking that the array is non-empty first.
2103    // Extract the array slice expression (everything before `[0]`).
2104    let array_guard: Option<String> = if let Some(idx) = field_expr.find("[0]") {
2105        let mut array_expr = field_expr[..idx].to_string();
2106        if let Some(stripped) = array_expr.strip_prefix("len(") {
2107            array_expr = stripped.to_string();
2108        }
2109        Some(array_expr)
2110    } else {
2111        None
2112    };
2113
2114    // Render the assertion into a temporary buffer first, then wrap with the array
2115    // bounds guard (if needed) by adding one extra level of indentation.
2116    let mut assertion_buf = String::new();
2117    let out_ref = &mut assertion_buf;
2118
2119    match assertion.assertion_type.as_str() {
2120        "equals" => {
2121            if let Some(expected) = &assertion.value {
2122                let go_val = json_to_go(expected);
2123                // For string equality, trim whitespace to handle trailing newlines from the converter.
2124                if expected.is_string() {
2125                    // Wrap field expression with strings.TrimSpace() for string comparisons.
2126                    // Use string() cast to handle named string types (e.g. BatchStatus, FinishReason).
2127                    let trimmed_field = if is_optional && !field_expr.starts_with("len(") {
2128                        format!("strings.TrimSpace(string(*{field_expr}))")
2129                    } else {
2130                        format!("strings.TrimSpace(string({field_expr}))")
2131                    };
2132                    if is_optional && !field_expr.starts_with("len(") {
2133                        let _ = writeln!(out_ref, "\tif {field_expr} != nil && {trimmed_field} != {go_val} {{");
2134                    } else {
2135                        let _ = writeln!(out_ref, "\tif {trimmed_field} != {go_val} {{");
2136                    }
2137                } else if is_optional && !field_expr.starts_with("len(") {
2138                    let _ = writeln!(out_ref, "\tif {field_expr} != nil && {deref_field_expr} != {go_val} {{");
2139                } else {
2140                    let _ = writeln!(out_ref, "\tif {field_expr} != {go_val} {{");
2141                }
2142                let _ = writeln!(out_ref, "\t\tt.Errorf(\"equals mismatch: got %v\", {field_expr})");
2143                let _ = writeln!(out_ref, "\t}}");
2144            }
2145        }
2146        "contains" => {
2147            if let Some(expected) = &assertion.value {
2148                let go_val = json_to_go(expected);
2149                // Determine the "string view" of the field expression.
2150                // - []string (optional) → jsonString(field_expr) — Go slices are nil-able, no `*` needed
2151                // - *string → string(*field_expr)
2152                // - string → string(field_expr) (or just field_expr for plain strings)
2153                // - result_is_array (result_is_simple + array result) → jsonString(field_expr)
2154                let resolved_field = assertion.field.as_deref().unwrap_or("");
2155                let resolved_name = field_resolver.resolve(resolved_field);
2156                let field_is_array = result_is_array || field_resolver.is_array(resolved_name);
2157                let is_opt =
2158                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
2159                let field_for_contains = if is_opt && field_is_array {
2160                    // Go slices are nil-able directly — no pointer dereference needed.
2161                    format!("jsonString({field_expr})")
2162                } else if is_opt {
2163                    format!("fmt.Sprint(*{field_expr})")
2164                } else if field_is_array {
2165                    format!("jsonString({field_expr})")
2166                } else {
2167                    format!("fmt.Sprint({field_expr})")
2168                };
2169                if is_opt {
2170                    let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2171                    let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
2172                    let _ = writeln!(
2173                        out_ref,
2174                        "\t\tt.Errorf(\"expected to contain %s, got %v\", {go_val}, {field_expr})"
2175                    );
2176                    let _ = writeln!(out_ref, "\t}}");
2177                    let _ = writeln!(out_ref, "\t}}");
2178                } else {
2179                    let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
2180                    let _ = writeln!(
2181                        out_ref,
2182                        "\t\tt.Errorf(\"expected to contain %s, got %v\", {go_val}, {field_expr})"
2183                    );
2184                    let _ = writeln!(out_ref, "\t}}");
2185                }
2186            }
2187        }
2188        "contains_all" => {
2189            if let Some(values) = &assertion.values {
2190                let resolved_field = assertion.field.as_deref().unwrap_or("");
2191                let resolved_name = field_resolver.resolve(resolved_field);
2192                let field_is_array = result_is_array || field_resolver.is_array(resolved_name);
2193                let is_opt =
2194                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
2195                for val in values {
2196                    let go_val = json_to_go(val);
2197                    let field_for_contains = if is_opt && field_is_array {
2198                        // Go slices are nil-able directly — no pointer dereference needed.
2199                        format!("jsonString({field_expr})")
2200                    } else if is_opt {
2201                        format!("fmt.Sprint(*{field_expr})")
2202                    } else if field_is_array {
2203                        format!("jsonString({field_expr})")
2204                    } else {
2205                        format!("fmt.Sprint({field_expr})")
2206                    };
2207                    if is_opt {
2208                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2209                        let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
2210                        let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected to contain %s\", {go_val})");
2211                        let _ = writeln!(out_ref, "\t}}");
2212                        let _ = writeln!(out_ref, "\t}}");
2213                    } else {
2214                        let _ = writeln!(out_ref, "\tif !strings.Contains({field_for_contains}, {go_val}) {{");
2215                        let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected to contain %s\", {go_val})");
2216                        let _ = writeln!(out_ref, "\t}}");
2217                    }
2218                }
2219            }
2220        }
2221        "not_contains" => {
2222            if let Some(expected) = &assertion.value {
2223                let go_val = json_to_go(expected);
2224                let resolved_field = assertion.field.as_deref().unwrap_or("");
2225                let resolved_name = field_resolver.resolve(resolved_field);
2226                let field_is_array = result_is_array || field_resolver.is_array(resolved_name);
2227                let is_opt =
2228                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
2229                let field_for_contains = if is_opt && field_is_array {
2230                    // Go slices are nil-able directly — no pointer dereference needed.
2231                    format!("jsonString({field_expr})")
2232                } else if is_opt {
2233                    format!("fmt.Sprint(*{field_expr})")
2234                } else if field_is_array {
2235                    format!("jsonString({field_expr})")
2236                } else {
2237                    format!("fmt.Sprint({field_expr})")
2238                };
2239                let _ = writeln!(out_ref, "\tif strings.Contains({field_for_contains}, {go_val}) {{");
2240                let _ = writeln!(
2241                    out_ref,
2242                    "\t\tt.Errorf(\"expected NOT to contain %s, got %v\", {go_val}, {field_expr})"
2243                );
2244                let _ = writeln!(out_ref, "\t}}");
2245            }
2246        }
2247        "not_empty" => {
2248            // For optional struct pointers (not arrays), just check != nil.
2249            // For optional slice/string pointers, check nil and len.
2250            let field_is_array = {
2251                let rf = assertion.field.as_deref().unwrap_or("");
2252                let rn = field_resolver.resolve(rf);
2253                field_resolver.is_array(rn)
2254            };
2255            if is_optional && !field_is_array {
2256                // Struct pointer: non-empty means not nil.
2257                let _ = writeln!(out_ref, "\tif {field_expr} == nil {{");
2258            } else if is_optional && field_is_slice {
2259                // Slice optional: Go slices are already nil-able — no dereference needed.
2260                let _ = writeln!(out_ref, "\tif {field_expr} == nil || len({field_expr}) == 0 {{");
2261            } else if is_optional {
2262                // Pointer-to-slice (*[]T): dereference then len.
2263                let _ = writeln!(out_ref, "\tif {field_expr} == nil || len(*{field_expr}) == 0 {{");
2264            } else if result_is_simple && result_is_array {
2265                // Simple array result ([]T) — direct slice, not a pointer; check length only.
2266                let _ = writeln!(out_ref, "\tif len({field_expr}) == 0 {{");
2267            } else {
2268                let _ = writeln!(out_ref, "\tif len({field_expr}) == 0 {{");
2269            }
2270            let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected non-empty value\")");
2271            let _ = writeln!(out_ref, "\t}}");
2272        }
2273        "is_empty" => {
2274            let field_is_array = {
2275                let rf = assertion.field.as_deref().unwrap_or("");
2276                let rn = field_resolver.resolve(rf);
2277                field_resolver.is_array(rn)
2278            };
2279            // Special case: result_is_simple && !result_is_array && no field means the result is a pointer.
2280            // Empty means nil.
2281            if result_is_simple && !result_is_array && assertion.field.as_ref().is_none_or(|f| f.is_empty()) {
2282                // Pointer result (not dereferenced): empty means nil.
2283                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2284            } else if is_optional && !field_is_array {
2285                // Struct pointer: empty means nil.
2286                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2287            } else if is_optional && field_is_slice {
2288                // Slice optional: Go slices are already nil-able — no dereference needed.
2289                let _ = writeln!(out_ref, "\tif {field_expr} != nil && len({field_expr}) != 0 {{");
2290            } else if is_optional {
2291                // Pointer-to-slice (*[]T): dereference then len.
2292                let _ = writeln!(out_ref, "\tif {field_expr} != nil && len(*{field_expr}) != 0 {{");
2293            } else {
2294                let _ = writeln!(out_ref, "\tif len({field_expr}) != 0 {{");
2295            }
2296            let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected empty value, got %v\", {field_expr})");
2297            let _ = writeln!(out_ref, "\t}}");
2298        }
2299        "contains_any" => {
2300            if let Some(values) = &assertion.values {
2301                let resolved_field = assertion.field.as_deref().unwrap_or("");
2302                let resolved_name = field_resolver.resolve(resolved_field);
2303                let field_is_array = field_resolver.is_array(resolved_name);
2304                let is_opt =
2305                    is_optional && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()));
2306                let field_for_contains = if is_opt && field_is_array {
2307                    // Go slices are nil-able directly — no pointer dereference needed.
2308                    format!("jsonString({field_expr})")
2309                } else if is_opt {
2310                    format!("fmt.Sprint(*{field_expr})")
2311                } else if field_is_array {
2312                    format!("jsonString({field_expr})")
2313                } else {
2314                    format!("fmt.Sprint({field_expr})")
2315                };
2316                let _ = writeln!(out_ref, "\t{{");
2317                let _ = writeln!(out_ref, "\t\tfound := false");
2318                for val in values {
2319                    let go_val = json_to_go(val);
2320                    let _ = writeln!(
2321                        out_ref,
2322                        "\t\tif strings.Contains({field_for_contains}, {go_val}) {{ found = true }}"
2323                    );
2324                }
2325                let _ = writeln!(out_ref, "\t\tif !found {{");
2326                let _ = writeln!(
2327                    out_ref,
2328                    "\t\t\tt.Errorf(\"expected to contain at least one of the specified values\")"
2329                );
2330                let _ = writeln!(out_ref, "\t\t}}");
2331                let _ = writeln!(out_ref, "\t}}");
2332            }
2333        }
2334        "greater_than" => {
2335            if let Some(val) = &assertion.value {
2336                let go_val = json_to_go(val);
2337                // Use `< N+1` instead of `<= N` to avoid golangci-lint sloppyLen
2338                // warning when N is 0 (len(x) <= 0 → len(x) < 1).
2339                // For optional (pointer) fields, dereference and guard with nil check.
2340                if is_optional {
2341                    let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2342                    if let Some(n) = val.as_u64() {
2343                        let next = n + 1;
2344                        let _ = writeln!(out_ref, "\t\tif {deref_field_expr} < {next} {{");
2345                    } else {
2346                        let _ = writeln!(out_ref, "\t\tif {deref_field_expr} <= {go_val} {{");
2347                    }
2348                    let _ = writeln!(
2349                        out_ref,
2350                        "\t\t\tt.Errorf(\"expected > {go_val}, got %v\", {deref_field_expr})"
2351                    );
2352                    let _ = writeln!(out_ref, "\t\t}}");
2353                    let _ = writeln!(out_ref, "\t}}");
2354                } else if let Some(n) = val.as_u64() {
2355                    let next = n + 1;
2356                    let _ = writeln!(out_ref, "\tif {field_expr} < {next} {{");
2357                    let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected > {go_val}, got %v\", {field_expr})");
2358                    let _ = writeln!(out_ref, "\t}}");
2359                } else {
2360                    let _ = writeln!(out_ref, "\tif {field_expr} <= {go_val} {{");
2361                    let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected > {go_val}, got %v\", {field_expr})");
2362                    let _ = writeln!(out_ref, "\t}}");
2363                }
2364            }
2365        }
2366        "less_than" => {
2367            if let Some(val) = &assertion.value {
2368                let go_val = json_to_go(val);
2369                let _ = writeln!(out_ref, "\tif {field_expr} >= {go_val} {{");
2370                let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected < {go_val}, got %v\", {field_expr})");
2371                let _ = writeln!(out_ref, "\t}}");
2372            }
2373        }
2374        "greater_than_or_equal" => {
2375            if let Some(val) = &assertion.value {
2376                let go_val = json_to_go(val);
2377                if let Some(ref guard) = nil_guard_expr {
2378                    let _ = writeln!(out_ref, "\tif {guard} != nil {{");
2379                    let _ = writeln!(out_ref, "\t\tif {field_expr} < {go_val} {{");
2380                    let _ = writeln!(
2381                        out_ref,
2382                        "\t\t\tt.Errorf(\"expected >= {go_val}, got %v\", {field_expr})"
2383                    );
2384                    let _ = writeln!(out_ref, "\t\t}}");
2385                    let _ = writeln!(out_ref, "\t}}");
2386                } else if is_optional && !field_expr.starts_with("len(") {
2387                    // Optional pointer field: nil-guard and dereference before comparison.
2388                    let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2389                    let _ = writeln!(out_ref, "\t\tif {deref_field_expr} < {go_val} {{");
2390                    let _ = writeln!(
2391                        out_ref,
2392                        "\t\t\tt.Errorf(\"expected >= {go_val}, got %v\", {deref_field_expr})"
2393                    );
2394                    let _ = writeln!(out_ref, "\t\t}}");
2395                    let _ = writeln!(out_ref, "\t}}");
2396                } else {
2397                    let _ = writeln!(out_ref, "\tif {field_expr} < {go_val} {{");
2398                    let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected >= {go_val}, got %v\", {field_expr})");
2399                    let _ = writeln!(out_ref, "\t}}");
2400                }
2401            }
2402        }
2403        "less_than_or_equal" => {
2404            if let Some(val) = &assertion.value {
2405                let go_val = json_to_go(val);
2406                let _ = writeln!(out_ref, "\tif {field_expr} > {go_val} {{");
2407                let _ = writeln!(out_ref, "\t\tt.Errorf(\"expected <= {go_val}, got %v\", {field_expr})");
2408                let _ = writeln!(out_ref, "\t}}");
2409            }
2410        }
2411        "starts_with" => {
2412            if let Some(expected) = &assertion.value {
2413                let go_val = json_to_go(expected);
2414                let field_for_prefix = if is_optional
2415                    && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()))
2416                {
2417                    format!("string(*{field_expr})")
2418                } else {
2419                    format!("string({field_expr})")
2420                };
2421                let _ = writeln!(out_ref, "\tif !strings.HasPrefix({field_for_prefix}, {go_val}) {{");
2422                let _ = writeln!(
2423                    out_ref,
2424                    "\t\tt.Errorf(\"expected to start with %s, got %v\", {go_val}, {field_expr})"
2425                );
2426                let _ = writeln!(out_ref, "\t}}");
2427            }
2428        }
2429        "count_min" => {
2430            if let Some(val) = &assertion.value {
2431                if let Some(n) = val.as_u64() {
2432                    if is_optional {
2433                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2434                        // Slices are value types in Go — use len(slice) not len(*slice).
2435                        let len_expr = if field_is_slice {
2436                            format!("len({field_expr})")
2437                        } else {
2438                            format!("len(*{field_expr})")
2439                        };
2440                        let _ = writeln!(
2441                            out_ref,
2442                            "\t\tassert.GreaterOrEqual(t, {len_expr}, {n}, \"expected at least {n} elements\")"
2443                        );
2444                        let _ = writeln!(out_ref, "\t}}");
2445                    } else {
2446                        let _ = writeln!(
2447                            out_ref,
2448                            "\tassert.GreaterOrEqual(t, len({field_expr}), {n}, \"expected at least {n} elements\")"
2449                        );
2450                    }
2451                }
2452            }
2453        }
2454        "count_equals" => {
2455            if let Some(val) = &assertion.value {
2456                if let Some(n) = val.as_u64() {
2457                    if is_optional {
2458                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2459                        // Slices are value types in Go — use len(slice) not len(*slice).
2460                        let len_expr = if field_is_slice {
2461                            format!("len({field_expr})")
2462                        } else {
2463                            format!("len(*{field_expr})")
2464                        };
2465                        let _ = writeln!(
2466                            out_ref,
2467                            "\t\tassert.Equal(t, {len_expr}, {n}, \"expected exactly {n} elements\")"
2468                        );
2469                        let _ = writeln!(out_ref, "\t}}");
2470                    } else {
2471                        let _ = writeln!(
2472                            out_ref,
2473                            "\tassert.Equal(t, len({field_expr}), {n}, \"expected exactly {n} elements\")"
2474                        );
2475                    }
2476                }
2477            }
2478        }
2479        "is_true" => {
2480            if is_optional {
2481                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2482                let _ = writeln!(out_ref, "\t\tassert.True(t, *{field_expr}, \"expected true\")");
2483                let _ = writeln!(out_ref, "\t}}");
2484            } else {
2485                let _ = writeln!(out_ref, "\tassert.True(t, {field_expr}, \"expected true\")");
2486            }
2487        }
2488        "is_false" => {
2489            if is_optional {
2490                let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2491                let _ = writeln!(out_ref, "\t\tassert.False(t, *{field_expr}, \"expected false\")");
2492                let _ = writeln!(out_ref, "\t}}");
2493            } else {
2494                let _ = writeln!(out_ref, "\tassert.False(t, {field_expr}, \"expected false\")");
2495            }
2496        }
2497        "method_result" => {
2498            if let Some(method_name) = &assertion.method {
2499                let info = build_go_method_call(result_var, method_name, assertion.args.as_ref(), import_alias);
2500                let check = assertion.check.as_deref().unwrap_or("is_true");
2501                // For pointer-returning functions, dereference with `*`. Value-returning
2502                // functions (e.g., NodeInfo field access) are used directly.
2503                let deref_expr = if info.is_pointer {
2504                    format!("*{}", info.call_expr)
2505                } else {
2506                    info.call_expr.clone()
2507                };
2508                match check {
2509                    "equals" => {
2510                        if let Some(val) = &assertion.value {
2511                            if val.is_boolean() {
2512                                if val.as_bool() == Some(true) {
2513                                    let _ = writeln!(out_ref, "\tassert.True(t, {deref_expr}, \"expected true\")");
2514                                } else {
2515                                    let _ = writeln!(out_ref, "\tassert.False(t, {deref_expr}, \"expected false\")");
2516                                }
2517                            } else {
2518                                // Apply type cast to numeric literals when the method returns
2519                                // a typed uint (e.g., *uint) to avoid reflect.DeepEqual
2520                                // mismatches between int and uint in testify's assert.Equal.
2521                                let go_val = if let Some(cast) = info.value_cast {
2522                                    if val.is_number() {
2523                                        format!("{cast}({})", json_to_go(val))
2524                                    } else {
2525                                        json_to_go(val)
2526                                    }
2527                                } else {
2528                                    json_to_go(val)
2529                                };
2530                                let _ = writeln!(
2531                                    out_ref,
2532                                    "\tassert.Equal(t, {go_val}, {deref_expr}, \"method_result equals assertion failed\")"
2533                                );
2534                            }
2535                        }
2536                    }
2537                    "is_true" => {
2538                        let _ = writeln!(out_ref, "\tassert.True(t, {deref_expr}, \"expected true\")");
2539                    }
2540                    "is_false" => {
2541                        let _ = writeln!(out_ref, "\tassert.False(t, {deref_expr}, \"expected false\")");
2542                    }
2543                    "greater_than_or_equal" => {
2544                        if let Some(val) = &assertion.value {
2545                            let n = val.as_u64().unwrap_or(0);
2546                            // Use the value_cast type if available (e.g., uint for named_children_count).
2547                            let cast = info.value_cast.unwrap_or("uint");
2548                            let _ = writeln!(
2549                                out_ref,
2550                                "\tassert.GreaterOrEqual(t, {deref_expr}, {cast}({n}), \"expected >= {n}\")"
2551                            );
2552                        }
2553                    }
2554                    "count_min" => {
2555                        if let Some(val) = &assertion.value {
2556                            let n = val.as_u64().unwrap_or(0);
2557                            let _ = writeln!(
2558                                out_ref,
2559                                "\tassert.GreaterOrEqual(t, len({deref_expr}), {n}, \"expected at least {n} elements\")"
2560                            );
2561                        }
2562                    }
2563                    "contains" => {
2564                        if let Some(val) = &assertion.value {
2565                            let go_val = json_to_go(val);
2566                            let _ = writeln!(
2567                                out_ref,
2568                                "\tassert.Contains(t, {deref_expr}, {go_val}, \"expected result to contain value\")"
2569                            );
2570                        }
2571                    }
2572                    "is_error" => {
2573                        let _ = writeln!(out_ref, "\t{{");
2574                        let _ = writeln!(out_ref, "\t\t_, methodErr := {}", info.call_expr);
2575                        let _ = writeln!(out_ref, "\t\tassert.Error(t, methodErr)");
2576                        let _ = writeln!(out_ref, "\t}}");
2577                    }
2578                    other_check => {
2579                        panic!("Go e2e generator: unsupported method_result check type: {other_check}");
2580                    }
2581                }
2582            } else {
2583                panic!("Go e2e generator: method_result assertion missing 'method' field");
2584            }
2585        }
2586        "min_length" => {
2587            if let Some(val) = &assertion.value {
2588                if let Some(n) = val.as_u64() {
2589                    if is_optional {
2590                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2591                        let _ = writeln!(
2592                            out_ref,
2593                            "\t\tassert.GreaterOrEqual(t, len(*{field_expr}), {n}, \"expected length >= {n}\")"
2594                        );
2595                        let _ = writeln!(out_ref, "\t}}");
2596                    } else if field_expr.starts_with("len(") {
2597                        let _ = writeln!(
2598                            out_ref,
2599                            "\tassert.GreaterOrEqual(t, {field_expr}, {n}, \"expected length >= {n}\")"
2600                        );
2601                    } else {
2602                        let _ = writeln!(
2603                            out_ref,
2604                            "\tassert.GreaterOrEqual(t, len({field_expr}), {n}, \"expected length >= {n}\")"
2605                        );
2606                    }
2607                }
2608            }
2609        }
2610        "max_length" => {
2611            if let Some(val) = &assertion.value {
2612                if let Some(n) = val.as_u64() {
2613                    if is_optional {
2614                        let _ = writeln!(out_ref, "\tif {field_expr} != nil {{");
2615                        let _ = writeln!(
2616                            out_ref,
2617                            "\t\tassert.LessOrEqual(t, len(*{field_expr}), {n}, \"expected length <= {n}\")"
2618                        );
2619                        let _ = writeln!(out_ref, "\t}}");
2620                    } else if field_expr.starts_with("len(") {
2621                        let _ = writeln!(
2622                            out_ref,
2623                            "\tassert.LessOrEqual(t, {field_expr}, {n}, \"expected length <= {n}\")"
2624                        );
2625                    } else {
2626                        let _ = writeln!(
2627                            out_ref,
2628                            "\tassert.LessOrEqual(t, len({field_expr}), {n}, \"expected length <= {n}\")"
2629                        );
2630                    }
2631                }
2632            }
2633        }
2634        "ends_with" => {
2635            if let Some(expected) = &assertion.value {
2636                let go_val = json_to_go(expected);
2637                let field_for_suffix = if is_optional
2638                    && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()))
2639                {
2640                    format!("string(*{field_expr})")
2641                } else {
2642                    format!("string({field_expr})")
2643                };
2644                let _ = writeln!(out_ref, "\tif !strings.HasSuffix({field_for_suffix}, {go_val}) {{");
2645                let _ = writeln!(
2646                    out_ref,
2647                    "\t\tt.Errorf(\"expected to end with %s, got %v\", {go_val}, {field_expr})"
2648                );
2649                let _ = writeln!(out_ref, "\t}}");
2650            }
2651        }
2652        "matches_regex" => {
2653            if let Some(expected) = &assertion.value {
2654                let go_val = json_to_go(expected);
2655                let field_for_regex = if is_optional
2656                    && !optional_locals.contains_key(assertion.field.as_ref().unwrap_or(&String::new()))
2657                {
2658                    format!("*{field_expr}")
2659                } else {
2660                    field_expr.clone()
2661                };
2662                let _ = writeln!(
2663                    out_ref,
2664                    "\tassert.Regexp(t, {go_val}, {field_for_regex}, \"expected value to match regex\")"
2665                );
2666            }
2667        }
2668        "not_error" => {
2669            // Already handled by the `if err != nil` check above.
2670        }
2671        "error" => {
2672            // Handled at the test function level.
2673        }
2674        other => {
2675            panic!("Go e2e generator: unsupported assertion type: {other}");
2676        }
2677    }
2678
2679    // If the assertion accesses an array element via [0], wrap the generated code in a
2680    // bounds check to prevent an index-out-of-range panic when the array is empty.
2681    if let Some(ref arr) = array_guard {
2682        if !assertion_buf.is_empty() {
2683            let _ = writeln!(out, "\tif len({arr}) > 0 {{");
2684            // Re-indent each line by one additional tab level.
2685            for line in assertion_buf.lines() {
2686                let _ = writeln!(out, "\t{line}");
2687            }
2688            let _ = writeln!(out, "\t}}");
2689        }
2690    } else {
2691        out.push_str(&assertion_buf);
2692    }
2693}
2694
2695/// Metadata about the return type of a Go method call for `method_result` assertions.
2696struct GoMethodCallInfo {
2697    /// The call expression string.
2698    call_expr: String,
2699    /// Whether the return type is a pointer (needs `*` dereference for value comparison).
2700    is_pointer: bool,
2701    /// Optional Go type cast to apply to numeric literal values in `equals` assertions
2702    /// (e.g., `"uint"` so that `0` becomes `uint(0)` to match `*uint` deref type).
2703    value_cast: Option<&'static str>,
2704}
2705
2706/// Build a Go call expression for a `method_result` assertion on a tree-sitter Tree.
2707///
2708/// Maps method names to the appropriate Go function calls, matching the Go binding API
2709/// in `packages/go/binding.go`. Returns a [`GoMethodCallInfo`] describing the call and
2710/// its return type characteristics.
2711///
2712/// Return types by method:
2713/// - `has_error_nodes`, `contains_node_type` → `*bool` (pointer)
2714/// - `error_count` → `*uint` (pointer, value_cast = "uint")
2715/// - `tree_to_sexp` → `*string` (pointer)
2716/// - `root_node_type` → `string` via `RootNodeInfo(tree).Kind` (value)
2717/// - `named_children_count` → `uint` via `RootNodeInfo(tree).NamedChildCount` (value, value_cast = "uint")
2718/// - `find_nodes_by_type` → `*[]NodeInfo` (pointer to slice)
2719/// - `run_query` → `(*[]QueryMatch, error)` (pointer + error; use `is_error` check type)
2720fn build_go_method_call(
2721    result_var: &str,
2722    method_name: &str,
2723    args: Option<&serde_json::Value>,
2724    import_alias: &str,
2725) -> GoMethodCallInfo {
2726    match method_name {
2727        "root_node_type" => GoMethodCallInfo {
2728            call_expr: format!("{import_alias}.RootNodeInfo({result_var}).Kind"),
2729            is_pointer: false,
2730            value_cast: None,
2731        },
2732        "named_children_count" => GoMethodCallInfo {
2733            call_expr: format!("{import_alias}.RootNodeInfo({result_var}).NamedChildCount"),
2734            is_pointer: false,
2735            value_cast: Some("uint"),
2736        },
2737        "has_error_nodes" => GoMethodCallInfo {
2738            call_expr: format!("{import_alias}.TreeHasErrorNodes({result_var})"),
2739            is_pointer: true,
2740            value_cast: None,
2741        },
2742        "error_count" | "tree_error_count" => GoMethodCallInfo {
2743            call_expr: format!("{import_alias}.TreeErrorCount({result_var})"),
2744            is_pointer: true,
2745            value_cast: Some("uint"),
2746        },
2747        "tree_to_sexp" => GoMethodCallInfo {
2748            call_expr: format!("{import_alias}.TreeToSexp({result_var})"),
2749            is_pointer: true,
2750            value_cast: None,
2751        },
2752        "contains_node_type" => {
2753            let node_type = args
2754                .and_then(|a| a.get("node_type"))
2755                .and_then(|v| v.as_str())
2756                .unwrap_or("");
2757            GoMethodCallInfo {
2758                call_expr: format!("{import_alias}.TreeContainsNodeType({result_var}, \"{node_type}\")"),
2759                is_pointer: true,
2760                value_cast: None,
2761            }
2762        }
2763        "find_nodes_by_type" => {
2764            let node_type = args
2765                .and_then(|a| a.get("node_type"))
2766                .and_then(|v| v.as_str())
2767                .unwrap_or("");
2768            GoMethodCallInfo {
2769                call_expr: format!("{import_alias}.FindNodesByType({result_var}, \"{node_type}\")"),
2770                is_pointer: true,
2771                value_cast: None,
2772            }
2773        }
2774        "run_query" => {
2775            let query_source = args
2776                .and_then(|a| a.get("query_source"))
2777                .and_then(|v| v.as_str())
2778                .unwrap_or("");
2779            let language = args
2780                .and_then(|a| a.get("language"))
2781                .and_then(|v| v.as_str())
2782                .unwrap_or("");
2783            let query_lit = go_string_literal(query_source);
2784            let lang_lit = go_string_literal(language);
2785            // RunQuery returns (*[]QueryMatch, error) — use is_error check type.
2786            GoMethodCallInfo {
2787                call_expr: format!("{import_alias}.RunQuery({result_var}, {lang_lit}, {query_lit}, []byte(source))"),
2788                is_pointer: false,
2789                value_cast: None,
2790            }
2791        }
2792        other => {
2793            let method_pascal = other.to_upper_camel_case();
2794            GoMethodCallInfo {
2795                call_expr: format!("{result_var}.{method_pascal}()"),
2796                is_pointer: false,
2797                value_cast: None,
2798            }
2799        }
2800    }
2801}
2802
2803/// Convert a `serde_json::Value` to a Go literal string.
2804/// Recursively convert a JSON value for Go struct unmarshalling.
2805///
2806/// The Go binding's `ConversionOptions` struct uses:
2807/// - `snake_case` JSON field tags (e.g. `"code_block_style"` not `"codeBlockStyle"`)
2808/// - lowercase/snake_case string values for enums (e.g. `"indented"`, `"atx_closed"`)
2809///
2810/// Fixture JSON uses camelCase keys and PascalCase enum values (Python/TS conventions).
2811/// This function remaps both so the generated Go tests can unmarshal correctly.
2812fn convert_json_for_go(value: serde_json::Value) -> serde_json::Value {
2813    match value {
2814        serde_json::Value::Object(map) => {
2815            let new_map: serde_json::Map<String, serde_json::Value> = map
2816                .into_iter()
2817                .map(|(k, v)| (camel_to_snake_case(&k), convert_json_for_go(v)))
2818                .collect();
2819            serde_json::Value::Object(new_map)
2820        }
2821        serde_json::Value::Array(arr) => {
2822            // Check if this is a byte array (array of integers 0-255).
2823            // If so, encode as base64 string for Go json.Unmarshal compatibility.
2824            if is_byte_array(&arr) {
2825                let bytes: Vec<u8> = arr
2826                    .iter()
2827                    .filter_map(|v| v.as_u64().and_then(|n| if n <= 255 { Some(n as u8) } else { None }))
2828                    .collect();
2829                // Encode bytes as base64 for Go json.Unmarshal (Go expects []byte as base64 strings)
2830                let encoded = base64_encode(&bytes);
2831                serde_json::Value::String(encoded)
2832            } else {
2833                serde_json::Value::Array(arr.into_iter().map(convert_json_for_go).collect())
2834            }
2835        }
2836        serde_json::Value::String(s) => {
2837            // Convert PascalCase enum values to snake_case.
2838            // Only convert values that look like PascalCase (start with uppercase, no spaces).
2839            serde_json::Value::String(pascal_to_snake_case(&s))
2840        }
2841        other => other,
2842    }
2843}
2844
2845/// Check if an array looks like a byte array (all elements are integers 0-255).
2846fn is_byte_array(arr: &[serde_json::Value]) -> bool {
2847    if arr.is_empty() {
2848        return false;
2849    }
2850    arr.iter().all(|v| {
2851        if let serde_json::Value::Number(n) = v {
2852            n.is_u64() && n.as_u64().is_some_and(|u| u <= 255)
2853        } else {
2854            false
2855        }
2856    })
2857}
2858
2859/// Encode bytes as base64 string (standard alphabet without padding in this output,
2860/// though Go's json.Unmarshal handles both).
2861fn base64_encode(bytes: &[u8]) -> String {
2862    const TABLE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2863    let mut result = String::new();
2864    let mut i = 0;
2865
2866    while i + 2 < bytes.len() {
2867        let b1 = bytes[i];
2868        let b2 = bytes[i + 1];
2869        let b3 = bytes[i + 2];
2870
2871        result.push(TABLE[(b1 >> 2) as usize] as char);
2872        result.push(TABLE[(((b1 & 0x03) << 4) | (b2 >> 4)) as usize] as char);
2873        result.push(TABLE[(((b2 & 0x0f) << 2) | (b3 >> 6)) as usize] as char);
2874        result.push(TABLE[(b3 & 0x3f) as usize] as char);
2875
2876        i += 3;
2877    }
2878
2879    // Handle remaining bytes
2880    if i < bytes.len() {
2881        let b1 = bytes[i];
2882        result.push(TABLE[(b1 >> 2) as usize] as char);
2883
2884        if i + 1 < bytes.len() {
2885            let b2 = bytes[i + 1];
2886            result.push(TABLE[(((b1 & 0x03) << 4) | (b2 >> 4)) as usize] as char);
2887            result.push(TABLE[((b2 & 0x0f) << 2) as usize] as char);
2888            result.push('=');
2889        } else {
2890            result.push(TABLE[((b1 & 0x03) << 4) as usize] as char);
2891            result.push_str("==");
2892        }
2893    }
2894
2895    result
2896}
2897
2898/// Convert a camelCase or PascalCase string to snake_case.
2899fn camel_to_snake_case(s: &str) -> String {
2900    let mut result = String::new();
2901    let mut prev_upper = false;
2902    for (i, c) in s.char_indices() {
2903        if c.is_uppercase() {
2904            if i > 0 && !prev_upper {
2905                result.push('_');
2906            }
2907            result.push(c.to_lowercase().next().unwrap_or(c));
2908            prev_upper = true;
2909        } else {
2910            if prev_upper && i > 1 {
2911                // Handles sequences like "URLPath" → "url_path": insert _ before last uppercase
2912                // when transitioning from a run of uppercase back to lowercase.
2913                // This is tricky — use simple approach: detect Aa pattern.
2914            }
2915            result.push(c);
2916            prev_upper = false;
2917        }
2918    }
2919    result
2920}
2921
2922/// Convert a PascalCase string to snake_case (for enum values).
2923///
2924/// Only converts if the string looks like PascalCase (starts uppercase, no spaces/underscores).
2925/// Values that are already lowercase/snake_case are returned unchanged.
2926fn pascal_to_snake_case(s: &str) -> String {
2927    // Skip conversion for strings that already contain underscores, spaces, or start lowercase.
2928    let first_char = s.chars().next();
2929    if first_char.is_none() || !first_char.unwrap().is_uppercase() || s.contains('_') || s.contains(' ') {
2930        return s.to_string();
2931    }
2932    camel_to_snake_case(s)
2933}
2934
2935/// Map an `ArgMapping.element_type` to a Go slice type. Used for `json_object` args
2936/// whose fixture value is a JSON array. The element type is wrapped in `[]…` so an
2937/// element of `String` becomes `[]string` and `Vec<String>` becomes `[][]string`.
2938fn element_type_to_go_slice(element_type: Option<&str>, import_alias: &str) -> String {
2939    let elem = element_type.unwrap_or("String").trim();
2940    let go_elem = rust_type_to_go(elem, import_alias);
2941    format!("[]{go_elem}")
2942}
2943
2944/// Map a small subset of Rust scalar / `Vec<T>` types to their Go equivalents.
2945/// For unknown types, qualify with the import alias (e.g., "kreuzberg.BatchBytesItem").
2946fn rust_type_to_go(rust: &str, import_alias: &str) -> String {
2947    let trimmed = rust.trim();
2948    if let Some(inner) = trimmed.strip_prefix("Vec<").and_then(|s| s.strip_suffix('>')) {
2949        return format!("[]{}", rust_type_to_go(inner, import_alias));
2950    }
2951    match trimmed {
2952        "String" | "&str" | "str" => "string".to_string(),
2953        "bool" => "bool".to_string(),
2954        "f32" => "float32".to_string(),
2955        "f64" => "float64".to_string(),
2956        "i8" => "int8".to_string(),
2957        "i16" => "int16".to_string(),
2958        "i32" => "int32".to_string(),
2959        "i64" | "isize" => "int64".to_string(),
2960        "u8" => "uint8".to_string(),
2961        "u16" => "uint16".to_string(),
2962        "u32" => "uint32".to_string(),
2963        "u64" | "usize" => "uint64".to_string(),
2964        _ => format!("{import_alias}.{trimmed}"),
2965    }
2966}
2967
2968fn json_to_go(value: &serde_json::Value) -> String {
2969    match value {
2970        serde_json::Value::String(s) => go_string_literal(s),
2971        serde_json::Value::Bool(b) => b.to_string(),
2972        serde_json::Value::Number(n) => n.to_string(),
2973        serde_json::Value::Null => "nil".to_string(),
2974        // For complex types, serialize to JSON string and pass as literal.
2975        other => go_string_literal(&other.to_string()),
2976    }
2977}
2978
2979// ---------------------------------------------------------------------------
2980// Visitor generation
2981// ---------------------------------------------------------------------------
2982
2983/// Derive a unique, exported Go struct name for a visitor from a fixture ID.
2984///
2985/// E.g. `visitor_continue_default` → `visitorContinueDefault` (unexported, avoids
2986/// polluting the exported API of the test package while still being package-level).
2987fn visitor_struct_name(fixture_id: &str) -> String {
2988    use heck::ToUpperCamelCase;
2989    // Use UpperCamelCase so Go treats it as exported — required for method sets.
2990    format!("testVisitor{}", fixture_id.to_upper_camel_case())
2991}
2992
2993/// Emit a package-level Go struct declaration and all its visitor methods.
2994///
2995/// The struct embeds `BaseVisitor` to satisfy all interface methods not
2996/// explicitly overridden by the fixture callbacks.
2997fn emit_go_visitor_struct(
2998    out: &mut String,
2999    struct_name: &str,
3000    visitor_spec: &crate::fixture::VisitorSpec,
3001    import_alias: &str,
3002) {
3003    let _ = writeln!(out, "type {struct_name} struct{{");
3004    let _ = writeln!(out, "\t{import_alias}.BaseVisitor");
3005    let _ = writeln!(out, "}}");
3006    for (method_name, action) in &visitor_spec.callbacks {
3007        emit_go_visitor_method(out, struct_name, method_name, action, import_alias);
3008    }
3009}
3010
3011/// Emit a Go visitor method for a callback action on the named struct.
3012fn emit_go_visitor_method(
3013    out: &mut String,
3014    struct_name: &str,
3015    method_name: &str,
3016    action: &CallbackAction,
3017    import_alias: &str,
3018) {
3019    let camel_method = method_to_camel(method_name);
3020    // Parameter signatures must exactly match the htmltomarkdown.Visitor interface.
3021    // Optional fields use pointer types (*string, *uint32, etc.) to indicate nil-ability.
3022    let params = match method_name {
3023        "visit_link" => format!("_ {import_alias}.NodeContext, href string, text string, title *string"),
3024        "visit_image" => format!("_ {import_alias}.NodeContext, src string, alt string, title *string"),
3025        "visit_heading" => format!("_ {import_alias}.NodeContext, level uint32, text string, id *string"),
3026        "visit_code_block" => format!("_ {import_alias}.NodeContext, lang *string, code string"),
3027        "visit_code_inline"
3028        | "visit_strong"
3029        | "visit_emphasis"
3030        | "visit_strikethrough"
3031        | "visit_underline"
3032        | "visit_subscript"
3033        | "visit_superscript"
3034        | "visit_mark"
3035        | "visit_button"
3036        | "visit_summary"
3037        | "visit_figcaption"
3038        | "visit_definition_term"
3039        | "visit_definition_description" => format!("_ {import_alias}.NodeContext, text string"),
3040        "visit_text" => format!("_ {import_alias}.NodeContext, text string"),
3041        "visit_list_item" => {
3042            format!("_ {import_alias}.NodeContext, ordered bool, marker string, text string")
3043        }
3044        "visit_blockquote" => format!("_ {import_alias}.NodeContext, content string, depth uint"),
3045        "visit_table_row" => format!("_ {import_alias}.NodeContext, cells []string, isHeader bool"),
3046        "visit_custom_element" => format!("_ {import_alias}.NodeContext, tagName string, html string"),
3047        "visit_form" => format!("_ {import_alias}.NodeContext, action *string, method *string"),
3048        "visit_input" => {
3049            format!("_ {import_alias}.NodeContext, inputType string, name *string, value *string")
3050        }
3051        "visit_audio" | "visit_video" | "visit_iframe" => {
3052            format!("_ {import_alias}.NodeContext, src *string")
3053        }
3054        "visit_details" => format!("_ {import_alias}.NodeContext, open bool"),
3055        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
3056            format!("_ {import_alias}.NodeContext, output string")
3057        }
3058        "visit_list_start" => format!("_ {import_alias}.NodeContext, ordered bool"),
3059        "visit_list_end" => format!("_ {import_alias}.NodeContext, ordered bool, output string"),
3060        _ => format!("_ {import_alias}.NodeContext"),
3061    };
3062
3063    let _ = writeln!(
3064        out,
3065        "func (v *{struct_name}) {camel_method}({params}) {import_alias}.VisitResult {{"
3066    );
3067    match action {
3068        CallbackAction::Skip => {
3069            let _ = writeln!(out, "\treturn {import_alias}.VisitResultSkip()");
3070        }
3071        CallbackAction::Continue => {
3072            let _ = writeln!(out, "\treturn {import_alias}.VisitResultContinue()");
3073        }
3074        CallbackAction::PreserveHtml => {
3075            let _ = writeln!(out, "\treturn {import_alias}.VisitResultPreserveHTML()");
3076        }
3077        CallbackAction::Custom { output } => {
3078            let escaped = go_string_literal(output);
3079            let _ = writeln!(out, "\treturn {import_alias}.VisitResultCustom({escaped})");
3080        }
3081        CallbackAction::CustomTemplate { template } => {
3082            // Convert {var} placeholders to %s format verbs and collect arg names.
3083            // E.g. `QUOTE: "{text}"` → fmt.Sprintf("QUOTE: \"%s\"", text)
3084            //
3085            // For pointer-typed params (e.g. `src *string`), dereference with `*`
3086            // — the test fixtures always supply a non-nil value for methods that
3087            // fire a custom template, so this is safe in practice.
3088            let ptr_params = go_visitor_ptr_params(method_name);
3089            let (fmt_str, fmt_args) = template_to_sprintf(template, &ptr_params);
3090            let escaped_fmt = go_string_literal(&fmt_str);
3091            if fmt_args.is_empty() {
3092                let _ = writeln!(out, "\treturn {import_alias}.VisitResultCustom({escaped_fmt})");
3093            } else {
3094                let args_str = fmt_args.join(", ");
3095                let _ = writeln!(
3096                    out,
3097                    "\treturn {import_alias}.VisitResultCustom(fmt.Sprintf({escaped_fmt}, {args_str}))"
3098                );
3099            }
3100        }
3101    }
3102    let _ = writeln!(out, "}}");
3103}
3104
3105/// Return the set of camelCase parameter names that are pointer types (`*string`) for a
3106/// given visitor method name.  Used to dereference pointers in template `fmt.Sprintf` calls.
3107fn go_visitor_ptr_params(method_name: &str) -> std::collections::HashSet<&'static str> {
3108    match method_name {
3109        "visit_link" => ["title"].into(),
3110        "visit_image" => ["title"].into(),
3111        "visit_heading" => ["id"].into(),
3112        "visit_code_block" => ["lang"].into(),
3113        "visit_form" => ["action", "method"].into(),
3114        "visit_input" => ["name", "value"].into(),
3115        "visit_audio" | "visit_video" | "visit_iframe" => ["src"].into(),
3116        _ => std::collections::HashSet::new(),
3117    }
3118}
3119
3120/// Convert a `{var}` template string into a `fmt.Sprintf` format string and argument list.
3121///
3122/// For example, `QUOTE: "{text}"` becomes `("QUOTE: \"%s\"", vec!["text"])`.
3123///
3124/// Placeholder names in the template use snake_case (matching fixture field names); they
3125/// are converted to Go camelCase parameter names using `go_param_name` so they match the
3126/// generated visitor method signatures (e.g. `{input_type}` → `inputType`).
3127///
3128/// `ptr_params` — camelCase names of parameters that are `*string`; these are
3129/// dereferenced with `*` when used as `fmt.Sprintf` arguments.  The fixtures that
3130/// use `custom_template` on pointer-param methods always supply a non-nil value.
3131fn template_to_sprintf(template: &str, ptr_params: &std::collections::HashSet<&str>) -> (String, Vec<String>) {
3132    let mut fmt_str = String::new();
3133    let mut args: Vec<String> = Vec::new();
3134    let mut chars = template.chars().peekable();
3135    while let Some(c) = chars.next() {
3136        if c == '{' {
3137            // Collect placeholder name until '}'.
3138            let mut name = String::new();
3139            for inner in chars.by_ref() {
3140                if inner == '}' {
3141                    break;
3142                }
3143                name.push(inner);
3144            }
3145            fmt_str.push_str("%s");
3146            // Convert snake_case placeholder to Go camelCase to match method param names.
3147            let go_name = go_param_name(&name);
3148            // Dereference pointer params so fmt.Sprintf receives a string value.
3149            let arg_expr = if ptr_params.contains(go_name.as_str()) {
3150                format!("*{go_name}")
3151            } else {
3152                go_name
3153            };
3154            args.push(arg_expr);
3155        } else {
3156            fmt_str.push(c);
3157        }
3158    }
3159    (fmt_str, args)
3160}
3161
3162/// Convert snake_case method names to Go camelCase.
3163fn method_to_camel(snake: &str) -> String {
3164    use heck::ToUpperCamelCase;
3165    snake.to_upper_camel_case()
3166}
3167
3168#[cfg(test)]
3169mod tests {
3170    use super::*;
3171    use crate::config::{CallConfig, E2eConfig};
3172    use crate::field_access::FieldResolver;
3173    use crate::fixture::{Assertion, Fixture};
3174
3175    fn make_fixture(id: &str) -> Fixture {
3176        Fixture {
3177            id: id.to_string(),
3178            category: None,
3179            description: "test fixture".to_string(),
3180            tags: vec![],
3181            skip: None,
3182            env: None,
3183            call: None,
3184            input: serde_json::Value::Null,
3185            mock_response: Some(crate::fixture::MockResponse {
3186                status: 200,
3187                body: Some(serde_json::Value::Null),
3188                stream_chunks: None,
3189                headers: std::collections::HashMap::new(),
3190            }),
3191            source: String::new(),
3192            http: None,
3193            assertions: vec![Assertion {
3194                assertion_type: "not_error".to_string(),
3195                ..Default::default()
3196            }],
3197            visitor: None,
3198        }
3199    }
3200
3201    /// snake_case function names in `[e2e.call]` must be routed through `to_go_name`
3202    /// so the emitted Go call uses the idiomatic CamelCase (e.g. `CleanExtractedText`
3203    /// instead of `clean_extracted_text`).
3204    #[test]
3205    fn test_go_method_name_uses_go_casing() {
3206        let e2e_config = E2eConfig {
3207            call: CallConfig {
3208                function: "clean_extracted_text".to_string(),
3209                module: "github.com/example/mylib".to_string(),
3210                result_var: "result".to_string(),
3211                returns_result: true,
3212                ..CallConfig::default()
3213            },
3214            ..E2eConfig::default()
3215        };
3216
3217        let fixture = make_fixture("basic_text");
3218        let resolver = FieldResolver::new(
3219            &std::collections::HashMap::new(),
3220            &std::collections::HashSet::new(),
3221            &std::collections::HashSet::new(),
3222            &std::collections::HashSet::new(),
3223            &std::collections::HashSet::new(),
3224        );
3225        let mut out = String::new();
3226        render_test_function(&mut out, &fixture, "kreuzberg", &resolver, &e2e_config);
3227
3228        assert!(
3229            out.contains("kreuzberg.CleanExtractedText("),
3230            "expected Go-cased method name 'CleanExtractedText', got:\n{out}"
3231        );
3232        assert!(
3233            !out.contains("kreuzberg.clean_extracted_text("),
3234            "must not emit raw snake_case method name, got:\n{out}"
3235        );
3236    }
3237}