Skip to main content

alef_e2e/codegen/rust/
test_file.rs

1//! Per-category test file generation for Rust e2e tests.
2
3use std::fmt::Write as FmtWrite;
4
5use crate::config::E2eConfig;
6use crate::escape::sanitize_filename;
7use crate::field_access::FieldResolver;
8use crate::fixture::{Fixture, FixtureGroup};
9
10use super::args::{emit_rust_visitor_method, render_rust_arg, resolve_visitor_trait};
11use super::assertions::render_assertion;
12use super::http::render_http_test_function;
13use super::mock_server::render_mock_server_setup;
14
15pub(super) fn resolve_function_name_for_call(call_config: &crate::config::CallConfig) -> String {
16    call_config
17        .overrides
18        .get("rust")
19        .and_then(|o| o.function.clone())
20        .unwrap_or_else(|| call_config.function.clone())
21}
22
23pub(super) fn resolve_module(e2e_config: &E2eConfig, dep_name: &str) -> String {
24    resolve_module_for_call(&e2e_config.call, dep_name)
25}
26
27pub(super) fn resolve_module_for_call(call_config: &crate::config::CallConfig, dep_name: &str) -> String {
28    // For Rust, the module name is the crate identifier (underscores).
29    // Priority: override.crate_name > override.module > dep_name
30    let overrides = call_config.overrides.get("rust");
31    overrides
32        .and_then(|o| o.crate_name.clone())
33        .or_else(|| overrides.and_then(|o| o.module.clone()))
34        .unwrap_or_else(|| dep_name.to_string())
35}
36
37pub(super) fn is_skipped(fixture: &Fixture, language: &str) -> bool {
38    fixture.skip.as_ref().is_some_and(|s| s.should_skip(language))
39}
40
41pub fn render_test_file(
42    category: &str,
43    fixtures: &[&Fixture],
44    e2e_config: &E2eConfig,
45    dep_name: &str,
46    needs_mock_server: bool,
47) -> String {
48    let mut out = String::new();
49    out.push_str(&alef_core::hash::header(alef_core::hash::CommentStyle::DoubleSlash));
50    let _ = writeln!(out, "//! E2e tests for category: {category}");
51    let _ = writeln!(out);
52
53    let module = resolve_module(e2e_config, dep_name);
54    let field_resolver = FieldResolver::new(
55        &e2e_config.fields,
56        &e2e_config.fields_optional,
57        &e2e_config.result_fields,
58        &e2e_config.fields_array,
59        &e2e_config.fields_method_calls,
60    );
61
62    // Check if this file has http-fixture tests (separate from call-based tests).
63    let file_has_http = fixtures.iter().any(|f| f.http.is_some());
64    // Call-based: has mock_response OR is a plain function-call fixture (no http, no mock) with a
65    // configured function name. Pure schema/spec stubs (function name empty) use the stub path.
66    let file_has_call_based = fixtures.iter().any(|f| {
67        if f.mock_response.is_some() {
68            return true;
69        }
70        if f.http.is_none() && f.mock_response.is_none() {
71            let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
72            let fn_name = resolve_function_name_for_call(call_config);
73            return !fn_name.is_empty();
74        }
75        false
76    });
77
78    // Collect all unique (module, function) pairs needed across call-based fixtures only.
79    // Resolve client_factory from the default call's rust override. When set, the generated tests
80    // create a client via `module::factory(...)` and call methods on it rather than importing and
81    // calling free functions. In that case we skip the function `use` imports entirely.
82    let rust_call_override = e2e_config.call.overrides.get("rust");
83    let client_factory = rust_call_override.and_then(|o| o.client_factory.as_deref());
84
85    // Http fixtures and pure stub fixtures use different code paths and don't import the call function.
86    if file_has_call_based && client_factory.is_none() {
87        let mut imported: std::collections::BTreeSet<(String, String)> = std::collections::BTreeSet::new();
88        for fixture in fixtures.iter().filter(|f| {
89            if f.mock_response.is_some() {
90                return true;
91            }
92            if f.http.is_none() && f.mock_response.is_none() {
93                let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
94                let fn_name = resolve_function_name_for_call(call_config);
95                return !fn_name.is_empty();
96            }
97            false
98        }) {
99            let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
100            let fn_name = resolve_function_name_for_call(call_config);
101            let mod_name = resolve_module_for_call(call_config, dep_name);
102            imported.insert((mod_name, fn_name));
103        }
104        // Emit use statements, grouping by module when possible.
105        let mut by_module: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
106        for (mod_name, fn_name) in &imported {
107            by_module.entry(mod_name.clone()).or_default().push(fn_name.clone());
108        }
109        for (mod_name, fns) in &by_module {
110            if fns.len() == 1 {
111                let _ = writeln!(out, "use {mod_name}::{};", fns[0]);
112            } else {
113                let joined = fns.join(", ");
114                let _ = writeln!(out, "use {mod_name}::{{{joined}}};");
115            }
116        }
117    }
118
119    // Http fixtures use App + RequestContext for integration tests.
120    if file_has_http {
121        let _ = writeln!(out, "use {module}::{{App, RequestContext}};");
122    }
123
124    // Import handle constructor functions and the config type they use.
125    let has_handle_args = e2e_config.call.args.iter().any(|a| a.arg_type == "handle");
126    if has_handle_args {
127        let _ = writeln!(out, "use {module}::CrawlConfig;");
128    }
129    for arg in &e2e_config.call.args {
130        if arg.arg_type == "handle" {
131            use heck::ToSnakeCase;
132            let constructor_name = format!("create_{}", arg.name.to_snake_case());
133            let _ = writeln!(out, "use {module}::{constructor_name};");
134        }
135    }
136
137    // When client_factory is set, emit trait imports required to call methods on the client object.
138    // Traits like LlmClient, FileClient, etc. must be in scope for method dispatch to work.
139    if client_factory.is_some() && file_has_call_based {
140        let trait_imports: Vec<String> = e2e_config
141            .call
142            .overrides
143            .get("rust")
144            .map(|o| o.trait_imports.clone())
145            .unwrap_or_default();
146        for trait_name in &trait_imports {
147            let _ = writeln!(out, "use {module}::{trait_name};");
148        }
149    }
150
151    // Import mock_server and common modules when any fixture in this file uses mock_response.
152    let file_needs_mock = needs_mock_server
153        && fixtures
154            .iter()
155            .any(|f| f.mock_response.is_some() || f.needs_mock_server());
156    if file_needs_mock {
157        let _ = writeln!(out, "mod common;");
158        let _ = writeln!(out, "mod mock_server;");
159        let _ = writeln!(out, "use mock_server::{{MockRoute, MockServer}};");
160    }
161
162    // Import the visitor trait, result enum, and node context when any fixture
163    // in this file declares a `visitor` block. Without these, the inline
164    // `impl <visitor_trait> for _TestVisitor` block fails to resolve.
165    // Visitor types live in the `visitor` sub-module of the crate, not the crate root.
166    // The trait name is read from `[e2e.call.overrides.rust] visitor_trait`; omitting it
167    // while a fixture declares a visitor is a configuration error.
168    let file_needs_visitor = fixtures.iter().any(|f| f.visitor.is_some());
169    if file_needs_visitor {
170        let visitor_trait = resolve_visitor_trait(rust_call_override).unwrap_or_else(|| {
171            panic!(
172                "category '{}': fixture declares a visitor block but \
173                 `[e2e.call.overrides.rust] visitor_trait` is not configured",
174                category
175            )
176        });
177        let _ = writeln!(
178            out,
179            "use {module}::visitor::{{{visitor_trait}, NodeContext, VisitResult}};"
180        );
181    }
182
183    // When the rust override specifies an `options_type` (e.g. `ConversionOptions`),
184    // type annotations are emitted on json_object bindings so that `Default::default()`
185    // and `serde_json::from_value(…)` can be resolved without a trailing positional arg.
186    // Import the named type so it is in scope in every test function in this file.
187    if file_has_call_based {
188        let rust_options_type = e2e_config
189            .call
190            .overrides
191            .get("rust")
192            .and_then(|o| o.options_type.as_deref());
193        if let Some(opts_type) = rust_options_type {
194            // Only emit if the call has a json_object arg (the type annotation is only
195            // added to json_object bindings).
196            let has_json_object_arg = e2e_config.call.args.iter().any(|a| a.arg_type == "json_object");
197            if has_json_object_arg {
198                let _ = writeln!(out, "use {module}::{opts_type};");
199            }
200        }
201    }
202
203    // Collect and import element types from json_object args that have an element_type specified.
204    // These types are used in serde_json::from_value::<Vec<{elem}>>() for batch operations.
205    // Collect from all calls used in call-based fixtures (not just the default call).
206    if file_has_call_based {
207        let mut element_types: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
208        for fixture in fixtures.iter().filter(|f| {
209            if f.mock_response.is_some() {
210                return true;
211            }
212            if f.http.is_none() && f.mock_response.is_none() {
213                let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
214                let fn_name = resolve_function_name_for_call(call_config);
215                return !fn_name.is_empty();
216            }
217            false
218        }) {
219            let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
220            for arg in &call_config.args {
221                if arg.arg_type == "json_object" {
222                    if let Some(ref elem_type) = arg.element_type {
223                        element_types.insert(elem_type.clone());
224                    }
225                }
226            }
227        }
228        for elem_type in &element_types {
229            // Skip primitive / std types — they're already in scope via the Rust prelude
230            // and emitting `use kreuzberg::String;` (etc.) would fail with E0432.
231            if matches!(
232                elem_type.as_str(),
233                "String"
234                    | "str"
235                    | "bool"
236                    | "i8"
237                    | "i16"
238                    | "i32"
239                    | "i64"
240                    | "i128"
241                    | "isize"
242                    | "u8"
243                    | "u16"
244                    | "u32"
245                    | "u64"
246                    | "u128"
247                    | "usize"
248                    | "f32"
249                    | "f64"
250                    | "char"
251            ) {
252                continue;
253            }
254            let _ = writeln!(out, "use {module}::{elem_type};");
255        }
256    }
257
258    let _ = writeln!(out);
259
260    for fixture in fixtures {
261        render_test_function(&mut out, fixture, e2e_config, dep_name, &field_resolver, client_factory);
262        let _ = writeln!(out);
263    }
264
265    if !out.ends_with('\n') {
266        out.push('\n');
267    }
268    out
269}
270
271pub fn render_test_function(
272    out: &mut String,
273    fixture: &Fixture,
274    e2e_config: &E2eConfig,
275    dep_name: &str,
276    field_resolver: &FieldResolver,
277    client_factory: Option<&str>,
278) {
279    // Http fixtures get their own integration test code path.
280    if fixture.http.is_some() {
281        render_http_test_function(out, fixture, dep_name);
282        return;
283    }
284
285    // Fixtures that have neither `http` nor `mock_response` may be either:
286    //  - schema/spec validation fixtures (asyncapi, grpc, graphql_schema, …) with no callable
287    //    function → emit a TODO stub so the suite compiles and preserves test count.
288    //  - plain function-call fixtures (e.g. kreuzberg::extract_file) with a configured
289    //    `[e2e.call]` → fall through to the real function-call code path below.
290    if fixture.http.is_none() && fixture.mock_response.is_none() {
291        let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
292        let resolved_fn_name = resolve_function_name_for_call(call_config);
293        if resolved_fn_name.is_empty() {
294            let fn_name = crate::escape::sanitize_ident(&fixture.id);
295            let description = &fixture.description;
296            let _ = writeln!(out, "#[tokio::test]");
297            let _ = writeln!(out, "async fn test_{fn_name}() {{");
298            let _ = writeln!(out, "    // {description}");
299            let _ = writeln!(
300                out,
301                "    // TODO: implement when a callable API is available for this fixture type."
302            );
303            let _ = writeln!(out, "}}");
304            return;
305        }
306        // Non-empty function name: fall through to emit a real function call below.
307    }
308
309    let fn_name = crate::escape::sanitize_ident(&fixture.id);
310    let description = &fixture.description;
311    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
312    let function_name = resolve_function_name_for_call(call_config);
313    let module = resolve_module_for_call(call_config, dep_name);
314    let result_var = &call_config.result_var;
315    let has_mock = fixture.mock_response.is_some();
316
317    // Resolve Rust-specific overrides early since we need them for returns_result.
318    let rust_overrides = call_config.overrides.get("rust");
319
320    // Determine if this call returns Result<T, E>. Per-rust override takes precedence.
321    // When client_factory is set, methods always return Result<T>.
322    let returns_result = rust_overrides
323        .and_then(|o| o.returns_result)
324        .unwrap_or(if client_factory.is_some() {
325            true
326        } else {
327            call_config.returns_result
328        });
329
330    // Tests with a mock server are always async (Axum requires a Tokio runtime).
331    let is_async = call_config.r#async || has_mock;
332    if is_async {
333        let _ = writeln!(out, "#[tokio::test]");
334        let _ = writeln!(out, "async fn test_{fn_name}() {{");
335    } else {
336        let _ = writeln!(out, "#[test]");
337        let _ = writeln!(out, "fn test_{fn_name}() {{");
338    }
339    let _ = writeln!(out, "    // {description}");
340
341    // Emit mock server setup before building arguments so arg expressions can
342    // reference `mock_server.url` when needed.
343    if has_mock {
344        render_mock_server_setup(out, fixture, e2e_config);
345    }
346
347    // Check if any assertion is an error assertion.
348    let has_error_assertion = fixture.assertions.iter().any(|a| a.assertion_type == "error");
349
350    // Extract additional overrides for argument shaping.
351    let wrap_options_in_some = rust_overrides.is_some_and(|o| o.wrap_options_in_some);
352    let extra_args: Vec<String> = rust_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
353    // options_type from the rust override (e.g. "ConversionOptions") — used to annotate
354    // `Default::default()` and `serde_json::from_value(…)` bindings so Rust can infer
355    // the concrete type without a trailing positional argument to guide inference.
356    let options_type: Option<String> = rust_overrides.and_then(|o| o.options_type.clone());
357
358    // When the fixture declares a visitor that is passed via an options-field (the
359    // html-to-markdown core `convert` API accepts visitor only through
360    // `ConversionOptions.visitor`), the options binding must be `mut` so we can
361    // assign the visitor field before the call.
362    let visitor_via_options = fixture.visitor.is_some() && rust_overrides.is_none_or(|o| o.visitor_function.is_none());
363
364    // Emit input variable bindings from args config.
365    let mut arg_exprs: Vec<String> = Vec::new();
366    // Track the name of the json_object options arg so we can inject the visitor later.
367    let mut options_arg_name: Option<String> = None;
368    for arg in &call_config.args {
369        let value = crate::codegen::resolve_field(&fixture.input, &arg.field);
370        let var_name = &arg.name;
371        let (mut bindings, expr) = render_rust_arg(
372            var_name,
373            value,
374            &arg.arg_type,
375            arg.optional,
376            &module,
377            &fixture.id,
378            if has_mock {
379                Some("mock_server.url.as_str()")
380            } else {
381                None
382            },
383            arg.owned,
384            arg.element_type.as_deref(),
385            &e2e_config.test_documents_dir,
386        );
387        // Add explicit type annotation to json_object bindings so Rust can resolve
388        // `Default::default()` and `serde_json::from_value(…)` without a trailing
389        // positional argument to guide inference.
390        if arg.arg_type == "json_object" {
391            if let Some(ref opts_type) = options_type {
392                bindings = bindings
393                    .into_iter()
394                    .map(|b| {
395                        // `let {name} = …` → `let {name}: {opts_type} = …`
396                        let prefix = format!("let {var_name} = ");
397                        if b.starts_with(&prefix) {
398                            format!("let {var_name}: {opts_type} = {}", &b[prefix.len()..])
399                        } else {
400                            b
401                        }
402                    })
403                    .collect();
404            }
405        }
406        // When the visitor will be injected via the options field, the options binding
407        // must be declared `mut` so we can assign `options.visitor = Some(visitor)`.
408        if visitor_via_options && arg.arg_type == "json_object" {
409            options_arg_name = Some(var_name.clone());
410            bindings = bindings
411                .into_iter()
412                .map(|b| {
413                    // `let {name}` → `let mut {name}`
414                    let prefix = format!("let {var_name}");
415                    if b.starts_with(&prefix) {
416                        format!("let mut {}", &b[4..])
417                    } else {
418                        b
419                    }
420                })
421                .collect();
422        }
423        for binding in &bindings {
424            let _ = writeln!(out, "    {binding}");
425        }
426        // For functions whose options slot is owned `Option<T>` rather than `&T`,
427        // wrap the json_object expression in `Some(...).clone()` so it matches
428        // the parameter shape. Other arg types pass through unchanged.
429        let final_expr = if wrap_options_in_some && arg.arg_type == "json_object" {
430            if visitor_via_options {
431                // Visitor will be injected into options before the call; pass by move
432                // (no .clone() needed).
433                let name = if let Some(rest) = expr.strip_prefix('&') {
434                    rest.to_string()
435                } else {
436                    expr.clone()
437                };
438                format!("Some({name})")
439            } else if let Some(rest) = expr.strip_prefix('&') {
440                format!("Some({rest}.clone())")
441            } else {
442                format!("Some({expr})")
443            }
444        } else {
445            expr
446        };
447        arg_exprs.push(final_expr);
448    }
449
450    // Emit visitor if present in fixture.
451    if let Some(visitor_spec) = &fixture.visitor {
452        // The visitor trait name must be configured via
453        // `[e2e.call.overrides.rust] visitor_trait`; we propagate the error to the caller.
454        let visitor_trait = resolve_visitor_trait(rust_overrides)
455            .expect("visitor_trait must be set in [e2e.call.overrides.rust] when a fixture declares a visitor block");
456        // The visitor trait requires `std::fmt::Debug`; derive it on the inline struct.
457        let _ = writeln!(out, "    #[derive(Debug)]");
458        let _ = writeln!(out, "    struct _TestVisitor;");
459        let _ = writeln!(out, "    impl {visitor_trait} for _TestVisitor {{");
460        for (method_name, action) in &visitor_spec.callbacks {
461            emit_rust_visitor_method(out, method_name, action);
462        }
463        let _ = writeln!(out, "    }}");
464        let _ = writeln!(
465            out,
466            "    let visitor = std::rc::Rc::new(std::cell::RefCell::new(_TestVisitor));"
467        );
468        if visitor_via_options {
469            // Inject the visitor via the options field rather than as a positional arg.
470            let opts_name = options_arg_name.as_deref().unwrap_or("options");
471            let _ = writeln!(out, "    {opts_name}.visitor = Some(visitor);");
472        } else {
473            // Binding uses a visitor_function override that takes visitor as positional arg.
474            arg_exprs.push("Some(visitor)".to_string());
475        }
476    } else {
477        // No fixture-supplied visitor: append any extra positional args declared in
478        // the rust override (e.g. trailing `None` for an Option<VisitorParam> slot).
479        arg_exprs.extend(extra_args);
480    }
481
482    let args_str = arg_exprs.join(", ");
483
484    let await_suffix = if is_async { ".await" } else { "" };
485
486    // When client_factory is configured, emit a `create_client` call and dispatch
487    // methods on the returned client object instead of calling free functions.
488    // The mock server URL (when present) is passed as `base_url`; otherwise `None`.
489    let call_expr = if let Some(factory) = client_factory {
490        let base_url_arg = if has_mock {
491            "Some(mock_server.url.clone())"
492        } else {
493            "None"
494        };
495        let _ = writeln!(
496            out,
497            "    let client = {module}::{factory}(\"test-key\".to_string(), {base_url_arg}, None, None, None).unwrap();"
498        );
499        format!("client.{function_name}({args_str})")
500    } else {
501        format!("{function_name}({args_str})")
502    };
503
504    let result_is_tree = call_config.result_var == "tree";
505    // When the call config or rust override sets result_is_simple, the function
506    // returns a plain type (String, Vec<T>, etc.) — field-access assertions use
507    // the result var directly.
508    let result_is_simple = call_config.result_is_simple || rust_overrides.is_some_and(|o| o.result_is_simple);
509    // When result_is_vec is set, the function returns Vec<T>. Field-path assertions
510    // are wrapped in `.iter().all(|r| ...)` so every element is checked.
511    let result_is_vec = rust_overrides.is_some_and(|o| o.result_is_vec);
512    // When result_is_option is set, the function returns Option<T>. Field-path
513    // assertions unwrap first via `.as_ref().expect("Option should be Some")`.
514    let result_is_option = call_config.result_is_option || rust_overrides.is_some_and(|o| o.result_is_option);
515
516    if has_error_assertion {
517        let _ = writeln!(out, "    let {result_var} = {call_expr}{await_suffix};");
518        // Check if any assertion accesses fields on the Ok value (not error-path fields).
519        // Assertions on `error.*` fields access the Err value and do not need `result_ok`.
520        let has_non_error_assertions = fixture.assertions.iter().any(|a| {
521            !matches!(a.assertion_type.as_str(), "error" | "not_error")
522                && !a.field.as_ref().is_some_and(|f| f.starts_with("error."))
523        });
524        // When returns_result=true and there are field assertions (non-error), we need to
525        // handle the Result wrapper: unwrap Ok for field assertions, extract Err for error assertions.
526        if returns_result && has_non_error_assertions {
527            // Emit a temporary binding for the unwrapped Ok value.
528            let _ = writeln!(out, "    let {result_var}_ok = {result_var}.as_ref().ok();");
529        }
530        // Render error assertions.
531        for assertion in &fixture.assertions {
532            render_assertion(
533                out,
534                assertion,
535                result_var,
536                &module,
537                dep_name,
538                true,
539                &[],
540                field_resolver,
541                result_is_tree,
542                result_is_simple,
543                false,
544                false,
545                returns_result,
546            );
547        }
548        let _ = writeln!(out, "}}");
549        return;
550    }
551
552    // Non-error path: unwrap the result.
553    let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
554
555    // Detect streaming fixtures: is_streaming_mock() checks for stream_chunks in mock_response.
556    // Also treat fixtures with streaming-virtual-field assertions as streaming so the
557    // collect snippet is emitted (handles empty_stream and similar edge-case fixtures
558    // whose mock_response has no stream_chunks but whose assertions reference `chunks`).
559    let is_streaming = fixture.is_streaming_mock()
560        || fixture.assertions.iter().any(|a| {
561            a.field
562                .as_deref()
563                .is_some_and(|f| !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f))
564        });
565    // Name of the stream-level variable (the raw stream returned by the call).
566    let stream_var = "stream";
567    // Name of the collected-list variable produced by draining the stream.
568    let chunks_var = "chunks";
569
570    // Check if any assertion actually uses the result variable.
571    // If all assertions are skipped (field not on result type), use `_` to avoid
572    // Rust's "variable never used" warning.
573    // For streaming fixtures: streaming virtual fields count as usable — they resolve
574    // against the `chunks` collected variable rather than the result type.
575    let has_usable_assertion = fixture.assertions.iter().any(|a| {
576        if a.assertion_type == "not_error" || a.assertion_type == "error" {
577            return false;
578        }
579        if a.assertion_type == "method_result" {
580            // method_result assertions that would generate only a TODO comment don't use the
581            // result variable. These are: missing `method` field, or unsupported `check` type.
582            let supported_checks = [
583                "equals",
584                "is_true",
585                "is_false",
586                "greater_than_or_equal",
587                "count_min",
588                "is_error",
589                "contains",
590                "not_empty",
591                "is_empty",
592            ];
593            let check = a.check.as_deref().unwrap_or("is_true");
594            if a.method.is_none() || !supported_checks.contains(&check) {
595                return false;
596            }
597        }
598        match &a.field {
599            Some(f) if !f.is_empty() => {
600                if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
601                    return true;
602                }
603                field_resolver.is_valid_for_result(f)
604            }
605            _ => true,
606        }
607    });
608
609    // For streaming fixtures the stream itself is stored in `stream` and the
610    // collected list in `chunks`.  Non-streaming fixtures use result_var / `_`.
611    let result_binding = if is_streaming {
612        stream_var.to_string()
613    } else if has_usable_assertion {
614        result_var.to_string()
615    } else {
616        "_".to_string()
617    };
618
619    // Detect Option-returning functions: only skip unwrap when ALL assertions are
620    // pure emptiness/bool checks with NO field access (is_none/is_some on the result itself).
621    // If any assertion accesses a field (e.g. `html`), we need the inner value, so unwrap.
622    let has_field_access = fixture
623        .assertions
624        .iter()
625        .any(|a| a.field.as_ref().is_some_and(|f| !f.is_empty()));
626    let only_emptiness_checks = !has_field_access
627        && fixture.assertions.iter().all(|a| {
628            matches!(
629                a.assertion_type.as_str(),
630                "is_empty" | "is_false" | "not_empty" | "is_true" | "not_error"
631            )
632        });
633
634    let unwrap_suffix = if returns_result {
635        ".expect(\"should succeed\")"
636    } else {
637        ""
638    };
639    if is_streaming {
640        // Streaming: bind the raw stream, then drain it into a Vec.
641        let _ = writeln!(out, "    let {stream_var} = {call_expr}{await_suffix}{unwrap_suffix};");
642        if let Some(collect) = crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(
643            "rust", stream_var, chunks_var,
644        ) {
645            let _ = writeln!(out, "    {collect}");
646        }
647    } else if !returns_result || (only_emptiness_checks && !has_not_error) {
648        // Option-returning or non-Result-returning (and not a not_error check): bind raw value, no unwrap.
649        // When returns_result=true and has_not_error, fall through to emit .expect() so errors panic.
650        let _ = writeln!(out, "    let {result_binding} = {call_expr}{await_suffix};");
651    } else if has_not_error || !fixture.assertions.is_empty() {
652        let _ = writeln!(
653            out,
654            "    let {result_binding} = {call_expr}{await_suffix}{unwrap_suffix};"
655        );
656    } else {
657        let _ = writeln!(out, "    let {result_binding} = {call_expr}{await_suffix};");
658    }
659
660    // Emit Option field unwrap bindings for any fields accessed in assertions.
661    // Use FieldResolver to handle optional fields, including nested/aliased paths.
662    // Skipped when the call returns Vec<T>: per-element iteration is emitted by
663    // `render_assertion` itself, so the call-site has no single result struct
664    // to unwrap fields off of.
665    let string_assertion_types = [
666        "equals",
667        "contains",
668        "contains_all",
669        "contains_any",
670        "not_contains",
671        "starts_with",
672        "ends_with",
673        "min_length",
674        "max_length",
675        "matches_regex",
676    ];
677    let mut unwrapped_fields: Vec<(String, String)> = Vec::new(); // (fixture_field, local_var)
678    if !result_is_vec {
679        for assertion in &fixture.assertions {
680            if let Some(f) = &assertion.field {
681                if !f.is_empty()
682                    && string_assertion_types.contains(&assertion.assertion_type.as_str())
683                    && !unwrapped_fields.iter().any(|(ff, _)| ff == f)
684                {
685                    // Only unwrap optional string fields — numeric optionals (u64, usize)
686                    // don't support .as_deref() and should be compared directly.
687                    let is_string_assertion = assertion.value.as_ref().is_none_or(|v| v.is_string());
688                    if !is_string_assertion {
689                        continue;
690                    }
691                    if let Some((binding, local_var)) = field_resolver.rust_unwrap_binding(f, result_var) {
692                        let _ = writeln!(out, "    {binding}");
693                        unwrapped_fields.push((f.clone(), local_var));
694                    }
695                }
696            }
697        }
698    }
699
700    // Render assertions.
701    for assertion in &fixture.assertions {
702        if assertion.assertion_type == "not_error" {
703            // Already handled by .expect() above.
704            continue;
705        }
706        render_assertion(
707            out,
708            assertion,
709            result_var,
710            &module,
711            dep_name,
712            false,
713            &unwrapped_fields,
714            field_resolver,
715            result_is_tree,
716            result_is_simple,
717            result_is_vec,
718            result_is_option,
719            returns_result,
720        );
721    }
722
723    let _ = writeln!(out, "}}");
724}
725
726/// Collect test file names for use in build.zig and similar build scripts.
727pub fn collect_test_filenames(groups: &[FixtureGroup]) -> Vec<String> {
728    groups
729        .iter()
730        .filter(|g| !g.fixtures.is_empty())
731        .map(|g| format!("{}_test.rs", sanitize_filename(&g.category)))
732        .collect()
733}
734
735#[cfg(test)]
736mod tests {
737    use super::*;
738
739    #[test]
740    fn resolve_module_for_call_prefers_crate_name_override() {
741        use crate::config::CallConfig;
742        use std::collections::HashMap;
743        let mut overrides = HashMap::new();
744        overrides.insert(
745            "rust".to_string(),
746            crate::config::CallOverride {
747                crate_name: Some("custom_crate".to_string()),
748                module: Some("ignored_module".to_string()),
749                ..Default::default()
750            },
751        );
752        let call = CallConfig {
753            overrides,
754            ..Default::default()
755        };
756        let result = resolve_module_for_call(&call, "dep_name");
757        assert_eq!(result, "custom_crate");
758    }
759}