Skip to main content

alef_e2e/codegen/
dart.rs

1//! Dart e2e test generator using package:test and package:http.
2//!
3//! Generates `e2e/dart/test/<category>_test.dart` files from JSON fixtures.
4//! HTTP fixtures hit the mock server at `MOCK_SERVER_URL/fixtures/<id>`.
5//! Non-HTTP fixtures without a dart-specific call override emit a skip stub.
6
7use crate::codegen::resolve_field;
8use crate::config::E2eConfig;
9use crate::escape::sanitize_filename;
10use crate::fixture::{Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::ResolvedCrateConfig;
13use alef_core::hash::{self, CommentStyle};
14use alef_core::template_versions::pub_dev;
15use anyhow::Result;
16use std::cell::Cell;
17use std::fmt::Write as FmtWrite;
18use std::path::PathBuf;
19
20use super::E2eCodegen;
21use super::client;
22
23/// Dart e2e code generator.
24pub struct DartE2eCodegen;
25
26impl E2eCodegen for DartE2eCodegen {
27    fn generate(
28        &self,
29        groups: &[FixtureGroup],
30        e2e_config: &E2eConfig,
31        config: &ResolvedCrateConfig,
32        _type_defs: &[alef_core::ir::TypeDef],
33    ) -> Result<Vec<GeneratedFile>> {
34        let lang = self.language_name();
35        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
36
37        let mut files = Vec::new();
38
39        // Resolve package config.
40        let dart_pkg = e2e_config.resolve_package("dart");
41        let pkg_name = dart_pkg
42            .as_ref()
43            .and_then(|p| p.name.as_ref())
44            .cloned()
45            .unwrap_or_else(|| config.dart_pubspec_name());
46        let pkg_path = dart_pkg
47            .as_ref()
48            .and_then(|p| p.path.as_ref())
49            .cloned()
50            .unwrap_or_else(|| "../../packages/dart".to_string());
51        let pkg_version = dart_pkg
52            .as_ref()
53            .and_then(|p| p.version.as_ref())
54            .cloned()
55            .or_else(|| config.resolved_version())
56            .unwrap_or_else(|| "0.1.0".to_string());
57
58        // Generate pubspec.yaml with http dependency for HTTP client tests.
59        files.push(GeneratedFile {
60            path: output_base.join("pubspec.yaml"),
61            content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
62            generated_header: false,
63        });
64
65        // Generate dart_test.yaml to limit parallelism — the mock server uses keep-alive
66        // connections and gets overwhelmed when test files run in parallel.
67        files.push(GeneratedFile {
68            path: output_base.join("dart_test.yaml"),
69            content: concat!(
70                "# Generated by alef — DO NOT EDIT.\n",
71                "# Run test files sequentially to avoid overwhelming the mock server with\n",
72                "# concurrent keep-alive connections.\n",
73                "concurrency: 1\n",
74            )
75            .to_string(),
76            generated_header: false,
77        });
78
79        let test_base = output_base.join("test");
80
81        // One test file per fixture group.
82        for group in groups {
83            let active: Vec<&Fixture> = group
84                .fixtures
85                .iter()
86                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
87                .collect();
88
89            if active.is_empty() {
90                continue;
91            }
92
93            let filename = format!("{}_test.dart", sanitize_filename(&group.category));
94            let content = render_test_file(&group.category, &active, e2e_config, lang);
95            files.push(GeneratedFile {
96                path: test_base.join(filename),
97                content,
98                generated_header: true,
99            });
100        }
101
102        Ok(files)
103    }
104
105    fn language_name(&self) -> &'static str {
106        "dart"
107    }
108}
109
110// ---------------------------------------------------------------------------
111// Rendering
112// ---------------------------------------------------------------------------
113
114fn render_pubspec(
115    pkg_name: &str,
116    pkg_path: &str,
117    pkg_version: &str,
118    dep_mode: crate::config::DependencyMode,
119) -> String {
120    let test_ver = pub_dev::TEST_PACKAGE;
121    let http_ver = pub_dev::HTTP_PACKAGE;
122
123    let dep_block = match dep_mode {
124        crate::config::DependencyMode::Registry => {
125            format!("  {pkg_name}: ^{pkg_version}")
126        }
127        crate::config::DependencyMode::Local => {
128            format!("  {pkg_name}:\n    path: {pkg_path}")
129        }
130    };
131
132    format!(
133        r#"name: e2e_dart
134version: 0.1.0
135publish_to: none
136
137environment:
138  sdk: ">=3.0.0 <4.0.0"
139
140dependencies:
141{dep_block}
142
143dev_dependencies:
144  test: {test_ver}
145  http: {http_ver}
146"#
147    )
148}
149
150fn render_test_file(category: &str, fixtures: &[&Fixture], e2e_config: &E2eConfig, lang: &str) -> String {
151    let mut out = String::new();
152    out.push_str(&hash::header(CommentStyle::DoubleSlash));
153
154    // Check if any fixture needs the http package (HTTP server tests).
155    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
156
157    // Check if any fixture needs Uint8List.fromList (batch item byte arrays).
158    let has_batch_byte_items = fixtures.iter().any(|f| {
159        let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
160        call_config.args.iter().any(|a| {
161            a.element_type.as_deref() == Some("BatchBytesItem") && resolve_field(&f.input, &a.field).is_array()
162        })
163    });
164
165    // Detect whether any fixture uses file_path or bytes args — if so, setUpAll must chdir
166    // to the test_documents directory so that relative paths like "docx/fake.docx" resolve.
167    // Mirrors the Ruby/Python conftest and Swift setUp patterns.
168    let needs_chdir = fixtures.iter().any(|f| {
169        if f.is_http_test() {
170            return false;
171        }
172        let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
173        call_config
174            .args
175            .iter()
176            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
177    });
178
179    let _ = writeln!(out, "import 'package:test/test.dart';");
180    let _ = writeln!(out, "import 'dart:io';");
181    if has_batch_byte_items {
182        let _ = writeln!(out, "import 'dart:typed_data';");
183    }
184    let _ = writeln!(out, "import 'package:kreuzberg/kreuzberg.dart';");
185    // RustLib is the flutter_rust_bridge entrypoint; must be initialized before any FRB call.
186    // It lives in the FRB-generated frb_generated.dart inside kreuzberg_bridge_generated/.
187    let _ = writeln!(
188        out,
189        "import 'package:kreuzberg/src/kreuzberg_bridge_generated/frb_generated.dart' show RustLib;"
190    );
191    if has_http_fixtures {
192        let _ = writeln!(out, "import 'dart:async';");
193        let _ = writeln!(out, "import 'dart:convert';");
194    }
195    let _ = writeln!(out);
196
197    // Emit file-level HTTP client and serialization mutex.
198    //
199    // The shared HttpClient reuses keep-alive connections to minimize TCP overhead.
200    // The mutex (_lock) ensures requests are serialized within the file so the
201    // connection pool is not exercised concurrently by dart:test's async runner.
202    //
203    // _withRetry wraps the entire request closure with one automatic retry on
204    // transient connection errors (keep-alive connections can be silently closed
205    // by the server just as the client tries to reuse them).
206    if has_http_fixtures {
207        let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
208        let _ = writeln!(out);
209        let _ = writeln!(out, "var _lock = Future<void>.value();");
210        let _ = writeln!(out);
211        let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
212        let _ = writeln!(out, "  final current = _lock;");
213        let _ = writeln!(out, "  final next = Completer<void>();");
214        let _ = writeln!(out, "  _lock = next.future;");
215        let _ = writeln!(out, "  try {{");
216        let _ = writeln!(out, "    await current;");
217        let _ = writeln!(out, "    return await fn();");
218        let _ = writeln!(out, "  }} finally {{");
219        let _ = writeln!(out, "    next.complete();");
220        let _ = writeln!(out, "  }}");
221        let _ = writeln!(out, "}}");
222        let _ = writeln!(out);
223        // The `fn` here should be the full request closure — on socket failure we
224        // recreate the HttpClient (drops old pooled connections) and retry once.
225        let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
226        let _ = writeln!(out, "  try {{");
227        let _ = writeln!(out, "    return await fn();");
228        let _ = writeln!(out, "  }} on SocketException {{");
229        let _ = writeln!(out, "    _httpClient.close(force: true);");
230        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
231        let _ = writeln!(out, "    return fn();");
232        let _ = writeln!(out, "  }} on HttpException {{");
233        let _ = writeln!(out, "    _httpClient.close(force: true);");
234        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
235        let _ = writeln!(out, "    return fn();");
236        let _ = writeln!(out, "  }}");
237        let _ = writeln!(out, "}}");
238        let _ = writeln!(out);
239    }
240
241    let _ = writeln!(out, "// E2e tests for category: {category}");
242    let _ = writeln!(out, "void main() {{");
243
244    // Emit setUpAll to initialize the flutter_rust_bridge before any test runs and,
245    // when fixtures load files by path, chdir to test_documents so that relative
246    // paths like "docx/fake.docx" resolve correctly.
247    //
248    // The test_documents directory lives two levels above e2e/dart/ (at the repo root).
249    // The FIXTURES_DIR environment variable can override this for CI environments.
250    let _ = writeln!(out, "  setUpAll(() async {{");
251    let _ = writeln!(out, "    await RustLib.init();");
252    if needs_chdir {
253        let _ = writeln!(
254            out,
255            "    final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '../../test_documents';"
256        );
257        let _ = writeln!(out, "    final _dir = Directory(_testDocs);");
258        let _ = writeln!(out, "    if (_dir.existsSync()) Directory.current = _dir;");
259    }
260    let _ = writeln!(out, "  }});");
261    let _ = writeln!(out);
262
263    // Close the shared client after all tests in this file complete.
264    if has_http_fixtures {
265        let _ = writeln!(out, "  tearDownAll(() => _httpClient.close());");
266        let _ = writeln!(out);
267    }
268
269    for fixture in fixtures {
270        render_test_case(&mut out, fixture, e2e_config, lang);
271    }
272
273    let _ = writeln!(out, "}}");
274    out
275}
276
277fn render_test_case(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig, lang: &str) {
278    // HTTP fixtures: hit the mock server.
279    if let Some(http) = &fixture.http {
280        render_http_test_case(out, fixture, http);
281        return;
282    }
283
284    // Non-HTTP fixtures: render a call-based test using the resolved call config.
285    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
286    let call_overrides = call_config.overrides.get(lang);
287    let mut function_name = call_overrides
288        .and_then(|o| o.function.as_ref())
289        .cloned()
290        .unwrap_or_else(|| call_config.function.clone());
291    // Convert snake_case function names to camelCase for Dart conventions.
292    function_name = function_name
293        .split('_')
294        .enumerate()
295        .map(|(i, part)| {
296            if i == 0 {
297                part.to_string()
298            } else {
299                let mut chars = part.chars();
300                match chars.next() {
301                    None => String::new(),
302                    Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
303                }
304            }
305        })
306        .collect::<Vec<_>>()
307        .join("");
308    let result_var = &call_config.result_var;
309    let description = escape_dart(&fixture.description);
310    // `is_async` retained for future use (e.g. non-FRB backends); unused with FRB since
311    // all wrappers return Future<T>.
312    let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);
313
314    // Build argument list from fixture.input and call_config.args.
315    // Use `resolve_field` (respects the `field` path like "input.data") rather than
316    // looking up by `arg_def.name` directly — the name and the field key may differ.
317    //
318    // For `extract_file_sync` / `extract_file` fixtures that omit `mime_type`,
319    // derive the MIME from the path extension so `extractBytesSync`/`extractBytes`
320    // can be called (both require an explicit MIME type).
321    let file_path_for_mime: Option<&str> = call_config
322        .args
323        .iter()
324        .find(|a| a.arg_type == "file_path")
325        .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());
326
327    // Detect whether this call converts a file_path arg to bytes at test-run time.
328    // Dart cannot pass OS-level file paths through the FRB bridge — the idiomatic API
329    // is always bytes. When a file_path arg is present (and no caller-supplied dart
330    // function override has already been applied), remap the function name:
331    //   extractFile      → extractBytes
332    //   extractFileSync  → extractBytesSync
333    let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
334    // Apply the remap only when no per-fixture dart override has already specified the
335    // function — if the fixture author set a dart-specific function name we trust it.
336    let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
337    if has_file_path_arg && !caller_supplied_override {
338        function_name = match function_name.as_str() {
339            "extractFile" => "extractBytes".to_string(),
340            "extractFileSync" => "extractBytesSync".to_string(),
341            other => other.to_string(),
342        };
343    }
344
345    let mut args = Vec::new();
346    for arg_def in &call_config.args {
347        let arg_value = resolve_field(&fixture.input, &arg_def.field);
348        match arg_def.arg_type.as_str() {
349            "bytes" | "file_path" => {
350                // `bytes`: value is a file path string; load file contents at test-run time.
351                // `file_path`: also loaded as bytes for dart — extractBytes/extractBytesSync is
352                // the idiomatic Dart API since the Dart runtime cannot pass OS-level file paths
353                // through the FFI bridge.
354                if let serde_json::Value::String(file_path) = arg_value {
355                    args.push(format!("File('{}').readAsBytesSync()", file_path));
356                }
357            }
358            "string" => {
359                match arg_value {
360                    serde_json::Value::String(s) => {
361                        args.push(format!("'{}'", escape_dart(s)));
362                    }
363                    serde_json::Value::Null
364                        if arg_def.optional
365                        // Optional string absent from fixture — try to infer MIME from path
366                        // when the arg name looks like a MIME-type parameter.
367                        && arg_def.name == "mime_type" =>
368                    {
369                        let inferred = file_path_for_mime
370                            .and_then(mime_from_extension)
371                            .unwrap_or("application/octet-stream");
372                        args.push(format!("'{inferred}'"));
373                    }
374                    // Other optional strings with null value are omitted.
375                    _ => {}
376                }
377            }
378            "json_object" => {
379                // Handle batch item arrays (BatchBytesItem / BatchFileItem).
380                if let Some(elem_type) = &arg_def.element_type {
381                    if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && arg_value.is_array() {
382                        let dart_items = emit_dart_batch_item_array(arg_value, elem_type);
383                        args.push(dart_items);
384                    }
385                } else if arg_def.name == "config" {
386                    if let serde_json::Value::Object(map) = &arg_value {
387                        // Fixture provides config overrides — build an ExtractionConfig constructor
388                        // with defaults, overriding only the fields present in the fixture JSON.
389                        // This handles error-triggering configs like {force_ocr:true, disable_ocr:true}.
390                        if !map.is_empty() {
391                            args.push(emit_extraction_config_dart(map));
392                        }
393                    }
394                    // If config is null/absent, the wrapper supplies the default ExtractionConfig.
395                }
396            }
397            _ => {}
398        }
399    }
400
401    // All KreuzbergBridge methods return Future<T> because FRB v2 wraps every Rust
402    // function as async in Dart — even "sync" Rust functions. Always emit an async
403    // test body and await the call so the test framework waits for the future.
404    let _ = writeln!(out, "  test('{description}', () async {{");
405
406    // Emit the receiver class name and arguments
407    let args_str = args.join(", ");
408    let receiver_class = call_overrides
409        .and_then(|o| o.class.as_ref())
410        .cloned()
411        .unwrap_or_else(|| "KreuzbergBridge".to_string());
412
413    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
414
415    if expects_error {
416        // flutter_rust_bridge 2.x decodes Rust errors as raw String values (not Exception
417        // subtypes), so throwsException will not match. Use throwsA(anything) which matches
418        // any thrown object regardless of type. Note: `anything` is a const Matcher value,
419        // not a function — do not write `anything()` (Dart 3 / matcher-0.12.x compile error).
420        let _ = writeln!(
421            out,
422            "    await expectLater({receiver_class}.{function_name}({args_str}), throwsA(anything));"
423        );
424    } else {
425        let _ = writeln!(
426            out,
427            "    final {result_var} = await {receiver_class}.{function_name}({args_str});"
428        );
429    }
430
431    let _ = writeln!(out, "  }});");
432    let _ = writeln!(out);
433}
434
435/// Converts a snake_case JSON key to Dart camelCase.
436fn snake_to_camel(s: &str) -> String {
437    let mut result = String::with_capacity(s.len());
438    let mut next_upper = false;
439    for ch in s.chars() {
440        if ch == '_' {
441            next_upper = true;
442        } else if next_upper {
443            result.extend(ch.to_uppercase());
444            next_upper = false;
445        } else {
446            result.push(ch);
447        }
448    }
449    result
450}
451
452/// Emits a Dart `ExtractionConfig(...)` constructor with default values, overriding
453/// fields present in `overrides` (from fixture JSON, snake_case keys).
454///
455/// Only simple scalar overrides (bool, int) are supported. Complex nested types
456/// (ocr, chunking, etc.) are left at their defaults (null).
457fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
458    // Collect scalar overrides; convert keys to camelCase.
459    let mut field_overrides: std::collections::HashMap<String, String> = std::collections::HashMap::new();
460    for (key, val) in overrides {
461        let camel = snake_to_camel(key);
462        let dart_val = match val {
463            serde_json::Value::Bool(b) => {
464                if *b {
465                    "true".to_string()
466                } else {
467                    "false".to_string()
468                }
469            }
470            serde_json::Value::Number(n) => n.to_string(),
471            serde_json::Value::String(s) => format!("'{s}'"),
472            _ => continue, // skip complex nested objects
473        };
474        field_overrides.insert(camel, dart_val);
475    }
476
477    let use_cache = field_overrides.remove("useCache").unwrap_or_else(|| "true".to_string());
478    let enable_quality_processing = field_overrides
479        .remove("enableQualityProcessing")
480        .unwrap_or_else(|| "true".to_string());
481    let force_ocr = field_overrides
482        .remove("forceOcr")
483        .unwrap_or_else(|| "false".to_string());
484    let disable_ocr = field_overrides
485        .remove("disableOcr")
486        .unwrap_or_else(|| "false".to_string());
487    let include_document_structure = field_overrides
488        .remove("includeDocumentStructure")
489        .unwrap_or_else(|| "false".to_string());
490    let max_archive_depth = field_overrides
491        .remove("maxArchiveDepth")
492        .unwrap_or_else(|| "3".to_string());
493
494    format!(
495        "ExtractionConfig(useCache: {use_cache}, enableQualityProcessing: {enable_quality_processing}, forceOcr: {force_ocr}, disableOcr: {disable_ocr}, resultFormat: ResultFormat.unified, outputFormat: OutputFormat.plain(), includeDocumentStructure: {include_document_structure}, maxArchiveDepth: {max_archive_depth})"
496    )
497}
498
499// ---------------------------------------------------------------------------
500// HTTP server test rendering — DartTestClientRenderer impl + thin driver wrapper
501// ---------------------------------------------------------------------------
502
503/// Renderer that emits `package:test` `test(...)` blocks using `dart:io HttpClient`
504/// against the mock server (`Platform.environment['MOCK_SERVER_URL']`).
505///
506/// Skipped tests are emitted as self-contained stubs (complete test block with
507/// `markTestSkipped`) entirely inside `render_test_open`. `render_test_close` uses
508/// `in_skip` to emit the right closing token: nothing extra for skip stubs (already
509/// closed) vs. `})));` for regular tests.
510///
511/// `is_redirect` must be set to `true` before invoking the shared driver for 3xx
512/// fixtures so that `render_call` can inject `ioReq.followRedirects = false` after
513/// the `openUrl` call.
514struct DartTestClientRenderer {
515    /// Set to `true` when `render_test_open` is called with a skip reason so that
516    /// `render_test_close` can match the opening shape.
517    in_skip: Cell<bool>,
518    /// Pre-set to `true` by the thin wrapper when the fixture expects a 3xx response.
519    /// `render_call` injects `ioReq.followRedirects = false` when this is `true`.
520    is_redirect: Cell<bool>,
521}
522
523impl DartTestClientRenderer {
524    fn new(is_redirect: bool) -> Self {
525        Self {
526            in_skip: Cell::new(false),
527            is_redirect: Cell::new(is_redirect),
528        }
529    }
530}
531
532impl client::TestClientRenderer for DartTestClientRenderer {
533    fn language_name(&self) -> &'static str {
534        "dart"
535    }
536
537    /// Emit the test opening.
538    ///
539    /// For skipped fixtures: emit the entire self-contained stub (open + body +
540    /// close + blank line) and set `in_skip = true` so `render_test_close` is a
541    /// no-op.
542    ///
543    /// For active fixtures: emit `test('desc', () => _serialized(() => _withRetry(() async {`
544    /// leaving the block open for the assertion primitives.
545    fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
546        let escaped_desc = escape_dart(description);
547        if let Some(reason) = skip_reason {
548            let escaped_reason = escape_dart(reason);
549            let _ = writeln!(out, "  test('{escaped_desc}', () {{");
550            let _ = writeln!(out, "    markTestSkipped('{escaped_reason}');");
551            let _ = writeln!(out, "  }});");
552            let _ = writeln!(out);
553            self.in_skip.set(true);
554        } else {
555            let _ = writeln!(
556                out,
557                "  test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
558            );
559            self.in_skip.set(false);
560        }
561    }
562
563    /// Emit the test closing token.
564    ///
565    /// No-op for skip stubs (the stub was fully closed in `render_test_open`).
566    /// Emits `})));` followed by a blank line for regular tests.
567    fn render_test_close(&self, out: &mut String) {
568        if self.in_skip.get() {
569            // Stub was already closed in render_test_open.
570            return;
571        }
572        let _ = writeln!(out, "  }})));");
573        let _ = writeln!(out);
574    }
575
576    /// Emit the full `dart:io HttpClient` request scaffolding.
577    ///
578    /// Emits:
579    /// - URL construction from `MOCK_SERVER_URL`.
580    /// - `_httpClient.openUrl(method, uri)`.
581    /// - `followRedirects = false` when `is_redirect` is pre-set on the renderer.
582    /// - Content-Type header, request headers, cookies, optional body bytes.
583    /// - `ioReq.close()` → `ioResp`.
584    /// - Response-body drain into `bodyStr` (skipped for redirect responses).
585    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
586        // dart:io restricted headers (handled automatically by the HTTP stack).
587        const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];
588
589        let method = ctx.method.to_uppercase();
590        let escaped_method = escape_dart(&method);
591
592        // Fixture path is `/fixtures/<id>` — extract the id portion for URL construction.
593        let fixture_path = escape_dart(ctx.path);
594
595        // Determine effective content-type.
596        let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
597        let effective_content_type = if has_explicit_content_type {
598            ctx.headers
599                .iter()
600                .find(|(k, _)| k.to_lowercase() == "content-type")
601                .map(|(_, v)| v.as_str())
602                .unwrap_or("application/json")
603        } else if ctx.body.is_some() {
604            ctx.content_type.unwrap_or("application/json")
605        } else {
606            ""
607        };
608
609        let _ = writeln!(
610            out,
611            "    final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
612        );
613        let _ = writeln!(out, "    final uri = Uri.parse('$baseUrl{fixture_path}');");
614        let _ = writeln!(
615            out,
616            "    final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
617        );
618
619        // Disable automatic redirect following for 3xx fixtures so the test can
620        // assert on the redirect status code itself.
621        if self.is_redirect.get() {
622            let _ = writeln!(out, "    ioReq.followRedirects = false;");
623        }
624
625        // Set content-type header.
626        if !effective_content_type.is_empty() {
627            let escaped_ct = escape_dart(effective_content_type);
628            let _ = writeln!(out, "    ioReq.headers.set('content-type', '{escaped_ct}');");
629        }
630
631        // Set request headers (skip dart:io restricted headers and content-type, already handled).
632        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
633        header_pairs.sort_by_key(|(k, _)| k.as_str());
634        for (name, value) in &header_pairs {
635            if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
636                continue;
637            }
638            if name.to_lowercase() == "content-type" {
639                continue; // Already handled above.
640            }
641            let escaped_name = escape_dart(&name.to_lowercase());
642            let escaped_value = escape_dart(value);
643            let _ = writeln!(out, "    ioReq.headers.set('{escaped_name}', '{escaped_value}');");
644        }
645
646        // Add cookies.
647        if !ctx.cookies.is_empty() {
648            let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
649            cookie_pairs.sort_by_key(|(k, _)| k.as_str());
650            let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
651            let cookie_header = escape_dart(&cookie_str.join("; "));
652            let _ = writeln!(out, "    ioReq.headers.set('cookie', '{cookie_header}');");
653        }
654
655        // Write body bytes if present (bypass charset-based encoding issues).
656        if let Some(body) = ctx.body {
657            let json_str = serde_json::to_string(body).unwrap_or_default();
658            let escaped = escape_dart(&json_str);
659            let _ = writeln!(out, "    final bodyBytes = utf8.encode('{escaped}');");
660            let _ = writeln!(out, "    ioReq.add(bodyBytes);");
661        }
662
663        let _ = writeln!(out, "    final ioResp = await ioReq.close();");
664        // Drain the response body to bind `bodyStr` for assertion primitives and to
665        // allow the server to cleanly close the connection (prevents RST packets).
666        // Redirect responses have no body to drain — skip to avoid a potential hang.
667        if !self.is_redirect.get() {
668            let _ = writeln!(out, "    final bodyStr = await ioResp.transform(utf8.decoder).join();");
669        };
670    }
671
672    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
673        let _ = writeln!(
674            out,
675            "    expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
676        );
677    }
678
679    /// Emit a single header assertion, handling special tokens `<<present>>`,
680    /// `<<absent>>`, and `<<uuid>>`.
681    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
682        let escaped_name = escape_dart(&name.to_lowercase());
683        match expected {
684            "<<present>>" => {
685                let _ = writeln!(
686                    out,
687                    "    expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
688                );
689            }
690            "<<absent>>" => {
691                let _ = writeln!(
692                    out,
693                    "    expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
694                );
695            }
696            "<<uuid>>" => {
697                let _ = writeln!(
698                    out,
699                    "    expect(ioResp.headers.value('{escaped_name}'), matches(RegExp(r'^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$')), reason: 'header {escaped_name} should be a UUID');"
700                );
701            }
702            exact => {
703                let escaped_value = escape_dart(exact);
704                let _ = writeln!(
705                    out,
706                    "    expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
707                );
708            }
709        }
710    }
711
712    /// Emit an exact-equality body assertion.
713    ///
714    /// String bodies are compared as decoded text; structured JSON bodies are
715    /// compared via `jsonDecode`.
716    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
717        match expected {
718            serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
719                let json_str = serde_json::to_string(expected).unwrap_or_default();
720                let escaped = escape_dart(&json_str);
721                let _ = writeln!(out, "    final bodyJson = jsonDecode(bodyStr);");
722                let _ = writeln!(out, "    final expectedJson = jsonDecode('{escaped}');");
723                let _ = writeln!(
724                    out,
725                    "    expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
726                );
727            }
728            serde_json::Value::String(s) => {
729                let escaped = escape_dart(s);
730                let _ = writeln!(
731                    out,
732                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
733                );
734            }
735            other => {
736                let escaped = escape_dart(&other.to_string());
737                let _ = writeln!(
738                    out,
739                    "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
740                );
741            }
742        }
743    }
744
745    /// Emit partial-body assertions — every key in `expected` must match the
746    /// corresponding field in the parsed JSON response.
747    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
748        let _ = writeln!(
749            out,
750            "    final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
751        );
752        if let Some(obj) = expected.as_object() {
753            for (idx, (key, val)) in obj.iter().enumerate() {
754                let escaped_key = escape_dart(key);
755                let json_val = serde_json::to_string(val).unwrap_or_default();
756                let escaped_val = escape_dart(&json_val);
757                // Use an index-based variable name so keys with special characters
758                // don't produce invalid Dart identifiers.
759                let _ = writeln!(out, "    final _expectedField{idx} = jsonDecode('{escaped_val}');");
760                let _ = writeln!(
761                    out,
762                    "    expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
763                );
764            }
765        }
766    }
767
768    /// Emit validation-error assertions for 422 responses.
769    fn render_assert_validation_errors(
770        &self,
771        out: &mut String,
772        _response_var: &str,
773        errors: &[ValidationErrorExpectation],
774    ) {
775        let _ = writeln!(out, "    final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
776        let _ = writeln!(out, "    final errList = (errBody['errors'] ?? []) as List<dynamic>;");
777        for ve in errors {
778            let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
779            let loc_str = loc_dart.join(", ");
780            let escaped_msg = escape_dart(&ve.msg);
781            let _ = writeln!(
782                out,
783                "    expect(errList.any((e) => e is Map && (e['loc'] as List?)?.join(',') == [{loc_str}].join(',') && (e['msg'] as String? ?? '').contains('{escaped_msg}')), isTrue, reason: 'validation error not found: {escaped_msg}');"
784            );
785        }
786    }
787}
788
789/// Render a `package:test` `test(...)` block for an HTTP server fixture.
790///
791/// Delegates to the shared [`client::http_call::render_http_test`] driver via
792/// [`DartTestClientRenderer`]. HTTP 101 (WebSocket upgrade) fixtures are emitted
793/// as skip stubs before reaching the driver because `dart:io HttpClient` cannot
794/// handle protocol-switch responses.
795fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
796    // HTTP 101 (WebSocket upgrade) — dart:io HttpClient cannot handle upgrade responses.
797    if http.expected_response.status_code == 101 {
798        let description = escape_dart(&fixture.description);
799        let _ = writeln!(out, "  test('{description}', () {{");
800        let _ = writeln!(
801            out,
802            "    markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
803        );
804        let _ = writeln!(out, "  }});");
805        let _ = writeln!(out);
806        return;
807    }
808
809    // Pre-set `is_redirect` on the renderer so `render_call` can inject
810    // `ioReq.followRedirects = false` for 3xx fixtures. The shared driver has no
811    // concept of expected status code so we thread it through renderer state.
812    let is_redirect = http.expected_response.status_code / 100 == 3;
813    client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
814}
815
816/// Infer a MIME type from a file path extension.
817///
818/// Returns `None` when the extension is unknown so the caller can supply a fallback.
819/// Used in dart e2e tests when a fixture omits `mime_type` but uses a `file_path` arg.
820fn mime_from_extension(path: &str) -> Option<&'static str> {
821    let ext = path.rsplit('.').next()?;
822    match ext.to_lowercase().as_str() {
823        "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
824        "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
825        "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
826        "pdf" => Some("application/pdf"),
827        "txt" | "text" => Some("text/plain"),
828        "html" | "htm" => Some("text/html"),
829        "json" => Some("application/json"),
830        "xml" => Some("application/xml"),
831        "csv" => Some("text/csv"),
832        "md" | "markdown" => Some("text/markdown"),
833        "png" => Some("image/png"),
834        "jpg" | "jpeg" => Some("image/jpeg"),
835        "gif" => Some("image/gif"),
836        "zip" => Some("application/zip"),
837        "odt" => Some("application/vnd.oasis.opendocument.text"),
838        "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
839        "odp" => Some("application/vnd.oasis.opendocument.presentation"),
840        "rtf" => Some("application/rtf"),
841        "epub" => Some("application/epub+zip"),
842        "msg" => Some("application/vnd.ms-outlook"),
843        "eml" => Some("message/rfc822"),
844        _ => None,
845    }
846}
847
848/// Emit Dart constructors for a batch item array (`BatchBytesItem` or `BatchFileItem`).
849///
850/// Returns a Dart list literal like:
851/// ```dart
852/// [BatchBytesItem(content: Uint8List.fromList([72, 101, ...]), mimeType: 'text/plain')]
853/// ```
854fn emit_dart_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
855    let items: Vec<String> = arr
856        .as_array()
857        .map(|a| a.as_slice())
858        .unwrap_or_default()
859        .iter()
860        .filter_map(|item| {
861            let obj = item.as_object()?;
862            match elem_type {
863                "BatchBytesItem" => {
864                    let content_bytes = obj
865                        .get("content")
866                        .and_then(|v| v.as_array())
867                        .map(|arr| {
868                            let nums: Vec<String> =
869                                arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
870                            format!("Uint8List.fromList([{}])", nums.join(", "))
871                        })
872                        .unwrap_or_else(|| "Uint8List(0)".to_string());
873                    let mime_type = obj
874                        .get("mime_type")
875                        .and_then(|v| v.as_str())
876                        .unwrap_or("application/octet-stream");
877                    Some(format!(
878                        "BatchBytesItem(content: {content_bytes}, mimeType: '{}')",
879                        escape_dart(mime_type)
880                    ))
881                }
882                "BatchFileItem" => {
883                    let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
884                    Some(format!("BatchFileItem(path: '{}')", escape_dart(path)))
885                }
886                _ => None,
887            }
888        })
889        .collect();
890    format!("[{}]", items.join(", "))
891}
892
893/// Escape a string for embedding in a Dart single-quoted string literal.
894fn escape_dart(s: &str) -> String {
895    s.replace('\\', "\\\\")
896        .replace('\'', "\\'")
897        .replace('\n', "\\n")
898        .replace('\r', "\\r")
899        .replace('\t', "\\t")
900        .replace('$', "\\$")
901}