Skip to main content

alef_e2e/codegen/
swift.rs

1//! Swift e2e test generator using XCTest.
2//!
3//! Generates test files for the swift package in `packages/swift/Tests/<Module>Tests/`.
4//!
5//! IMPORTANT: Due to SwiftPM 6.0 limitations (forbids inter-package `.package(path:)`
6//! references within a monorepo), generated test files are placed directly inside
7//! the `packages/swift` package (not in a separate `e2e/swift` package). This allows
8//! tests to depend on the library target without an explicit package dependency.
9//!
10//! The generated `Package.swift` is placed in `e2e/swift/` for documentation and CI
11//! reference but is NOT used for running tests — tests are run from the
12//! `packages/swift/` directory using `swift test`.
13
14use crate::config::E2eConfig;
15use crate::escape::{escape_java as escape_swift_str, expand_fixture_templates, sanitize_filename, sanitize_ident};
16use crate::field_access::FieldResolver;
17use crate::fixture::{Assertion, Fixture, FixtureGroup, ValidationErrorExpectation};
18use alef_core::backend::GeneratedFile;
19use alef_core::config::ResolvedCrateConfig;
20use alef_core::hash::{self, CommentStyle};
21use alef_core::template_versions::toolchain;
22use anyhow::Result;
23use heck::{ToLowerCamelCase, ToUpperCamelCase};
24use std::collections::HashSet;
25use std::fmt::Write as FmtWrite;
26use std::path::PathBuf;
27
28use super::E2eCodegen;
29use super::client;
30
31/// Swift e2e code generator.
32pub struct SwiftE2eCodegen;
33
34impl E2eCodegen for SwiftE2eCodegen {
35    fn generate(
36        &self,
37        groups: &[FixtureGroup],
38        e2e_config: &E2eConfig,
39        config: &ResolvedCrateConfig,
40        _type_defs: &[alef_core::ir::TypeDef],
41    ) -> Result<Vec<GeneratedFile>> {
42        let lang = self.language_name();
43        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
44
45        let mut files = Vec::new();
46
47        // Resolve call config with overrides.
48        let call = &e2e_config.call;
49        let overrides = call.overrides.get(lang);
50        let function_name = overrides
51            .and_then(|o| o.function.as_ref())
52            .cloned()
53            .unwrap_or_else(|| call.function.clone());
54        let result_var = &call.result_var;
55        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
56
57        // Resolve package config.
58        let swift_pkg = e2e_config.resolve_package("swift");
59        let pkg_name = swift_pkg
60            .as_ref()
61            .and_then(|p| p.name.as_ref())
62            .cloned()
63            .unwrap_or_else(|| config.name.to_upper_camel_case());
64        let pkg_path = swift_pkg
65            .as_ref()
66            .and_then(|p| p.path.as_ref())
67            .cloned()
68            .unwrap_or_else(|| "../../packages/swift".to_string());
69        let pkg_version = swift_pkg
70            .as_ref()
71            .and_then(|p| p.version.as_ref())
72            .cloned()
73            .or_else(|| config.resolved_version())
74            .unwrap_or_else(|| "0.1.0".to_string());
75
76        // The Swift module name: UpperCamelCase of the package name.
77        let module_name = pkg_name.as_str();
78
79        // Resolve the registry URL: derive from the configured repository when
80        // available (with a `.git` suffix per SwiftPM convention). Falls back
81        // to a vendor-neutral placeholder when no repo is configured.
82        let registry_url = config
83            .try_github_repo()
84            .map(|repo| {
85                let base = repo.trim_end_matches('/').trim_end_matches(".git");
86                format!("{base}.git")
87            })
88            .unwrap_or_else(|_| format!("https://example.invalid/{module_name}.git"));
89
90        // Generate Package.swift (kept for tooling/CI reference but not used
91        // for running tests — see note below).
92        files.push(GeneratedFile {
93            path: output_base.join("Package.swift"),
94            content: render_package_swift(module_name, &registry_url, &pkg_path, &pkg_version, e2e_config.dep_mode),
95            generated_header: false,
96        });
97
98        // Swift e2e tests are written into the *packages/swift* package rather
99        // than into the separate e2e/swift package.  SwiftPM 6.0 forbids local
100        // `.package(path:)` references between packages inside the same git
101        // repository, so a standalone e2e/swift package cannot depend on
102        // packages/swift.  Placing the test files directly inside
103        // packages/swift/Tests/<Module>Tests/ sidesteps the restriction: the
104        // tests are part of the same SwiftPM package that defines the library
105        // target, so no inter-package dependency is needed.
106        //
107        // `pkg_path` is expressed relative to the e2e/<lang> directory (e.g.
108        // "../../packages/swift").  Joining it onto `output_base` and
109        // normalising collapses the traversals to the actual project-root-
110        // relative path (e.g. "packages/swift").
111        let tests_base = normalize_path(&output_base.join(&pkg_path));
112
113        let field_resolver = FieldResolver::new(
114            &e2e_config.fields,
115            &e2e_config.fields_optional,
116            &e2e_config.result_fields,
117            &e2e_config.fields_array,
118            &e2e_config.fields_method_calls,
119        );
120
121        // Resolve client_factory override for swift (enables client-instance dispatch).
122        let client_factory: Option<&str> = overrides.and_then(|o| o.client_factory.as_deref());
123
124        // One test file per fixture group.
125        for group in groups {
126            let active: Vec<&Fixture> = group
127                .fixtures
128                .iter()
129                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
130                .collect();
131
132            if active.is_empty() {
133                continue;
134            }
135
136            let class_name = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
137            let filename = format!("{class_name}.swift");
138            let content = render_test_file(
139                &group.category,
140                &active,
141                e2e_config,
142                module_name,
143                &class_name,
144                &function_name,
145                result_var,
146                &e2e_config.call.args,
147                &field_resolver,
148                result_is_simple,
149                &e2e_config.fields_enum,
150                client_factory,
151            );
152            files.push(GeneratedFile {
153                path: tests_base
154                    .join("Tests")
155                    .join(format!("{module_name}Tests"))
156                    .join(filename),
157                content,
158                generated_header: true,
159            });
160        }
161
162        Ok(files)
163    }
164
165    fn language_name(&self) -> &'static str {
166        "swift"
167    }
168}
169
170// ---------------------------------------------------------------------------
171// Rendering
172// ---------------------------------------------------------------------------
173
174fn render_package_swift(
175    module_name: &str,
176    registry_url: &str,
177    pkg_path: &str,
178    pkg_version: &str,
179    dep_mode: crate::config::DependencyMode,
180) -> String {
181    let min_macos = toolchain::SWIFT_MIN_MACOS;
182
183    // For local deps SwiftPM identity = last path component (e.g. "../../packages/swift" → "swift").
184    // For registry deps identity is inferred from the URL.
185    // Use explicit .product(name:package:) to avoid ambiguity under tools-version 6.0.
186    let (dep_block, product_dep) = match dep_mode {
187        crate::config::DependencyMode::Registry => {
188            let dep = format!(r#"        .package(url: "{registry_url}", from: "{pkg_version}")"#);
189            let pkg_id = registry_url
190                .trim_end_matches('/')
191                .trim_end_matches(".git")
192                .split('/')
193                .next_back()
194                .unwrap_or(module_name);
195            let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
196            (dep, prod)
197        }
198        crate::config::DependencyMode::Local => {
199            let dep = format!(r#"        .package(path: "{pkg_path}")"#);
200            let pkg_id = pkg_path
201                .trim_end_matches('/')
202                .split('/')
203                .next_back()
204                .unwrap_or(module_name);
205            let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
206            (dep, prod)
207        }
208    };
209    // SwiftPM platform enums use the major version only (.v13, .v14, ...);
210    // strip patch components to match the scaffold's `Package.swift`.
211    let min_macos_major = min_macos.split('.').next().unwrap_or(min_macos);
212    // iOS (.v14) is always included — swift-bridge supports both macOS and iOS targets
213    // and the generated Package.swift is used as a CI reference for both platforms.
214    format!(
215        r#"// swift-tools-version: 6.0
216import PackageDescription
217
218let package = Package(
219    name: "E2eSwift",
220    platforms: [
221        .macOS(.v{min_macos_major}),
222        .iOS(.v14),
223    ],
224    dependencies: [
225{dep_block},
226    ],
227    targets: [
228        .testTarget(
229            name: "{module_name}Tests",
230            dependencies: [{product_dep}]
231        ),
232    ]
233)
234"#
235    )
236}
237
238#[allow(clippy::too_many_arguments)]
239fn render_test_file(
240    category: &str,
241    fixtures: &[&Fixture],
242    e2e_config: &E2eConfig,
243    module_name: &str,
244    class_name: &str,
245    function_name: &str,
246    result_var: &str,
247    args: &[crate::config::ArgMapping],
248    field_resolver: &FieldResolver,
249    result_is_simple: bool,
250    enum_fields: &HashSet<String>,
251    client_factory: Option<&str>,
252) -> String {
253    // Detect whether any fixture in this group uses a file_path or bytes arg — if so
254    // the test class chdir's to <repo>/test_documents at setUp time so the
255    // fixture-relative paths in test bodies (e.g. "docx/fake.docx") resolve correctly.
256    // The Swift binding's `extractBytes`/`extractFile` e2e wrappers consult
257    // `FIXTURES_DIR` first, otherwise resolve against the current directory.
258    // Mirrors the Ruby/Python conftest pattern that chdirs to test_documents.
259    let needs_chdir = fixtures.iter().any(|f| {
260        let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
261        call_config
262            .args
263            .iter()
264            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
265    });
266
267    let mut out = String::new();
268    out.push_str(&hash::header(CommentStyle::DoubleSlash));
269    let _ = writeln!(out, "import XCTest");
270    let _ = writeln!(out, "import Foundation");
271    let _ = writeln!(out, "import {module_name}");
272    let _ = writeln!(out, "import RustBridge");
273    let _ = writeln!(out);
274    let _ = writeln!(out, "/// E2e tests for category: {category}.");
275    let _ = writeln!(out, "final class {class_name}: XCTestCase {{");
276
277    if needs_chdir {
278        // Chdir once at class setUp so all fixture file_path arguments resolve relative
279        // to the repository's test_documents directory.
280        //
281        // #filePath = <repo>/packages/swift/Tests/<Module>Tests/<Class>.swift
282        // 5 deletingLastPathComponent() calls climb to the repo root before appending
283        // "test_documents". Mirrors the Ruby/Python conftest pattern that chdirs to
284        // test_documents.
285        let _ = writeln!(out, "    override class func setUp() {{");
286        let _ = writeln!(out, "        super.setUp()");
287        let _ = writeln!(out, "        let _testDocs = URL(fileURLWithPath: #filePath)");
288        let _ = writeln!(out, "            .deletingLastPathComponent() // <Module>Tests/");
289        let _ = writeln!(out, "            .deletingLastPathComponent() // Tests/");
290        let _ = writeln!(out, "            .deletingLastPathComponent() // swift/");
291        let _ = writeln!(out, "            .deletingLastPathComponent() // packages/");
292        let _ = writeln!(out, "            .deletingLastPathComponent() // <repo root>");
293        let _ = writeln!(
294            out,
295            "            .appendingPathComponent(\"{}\")",
296            e2e_config.test_documents_dir
297        );
298        let _ = writeln!(
299            out,
300            "        if FileManager.default.fileExists(atPath: _testDocs.path) {{"
301        );
302        let _ = writeln!(
303            out,
304            "            FileManager.default.changeCurrentDirectoryPath(_testDocs.path)"
305        );
306        let _ = writeln!(out, "        }}");
307        let _ = writeln!(out, "    }}");
308        let _ = writeln!(out);
309    }
310
311    for fixture in fixtures {
312        if fixture.is_http_test() {
313            render_http_test_method(&mut out, fixture);
314        } else {
315            render_test_method(
316                &mut out,
317                fixture,
318                e2e_config,
319                function_name,
320                result_var,
321                args,
322                field_resolver,
323                result_is_simple,
324                enum_fields,
325                client_factory,
326            );
327        }
328        let _ = writeln!(out);
329    }
330
331    let _ = writeln!(out, "}}");
332    out
333}
334
335// ---------------------------------------------------------------------------
336// HTTP test rendering — TestClientRenderer impl + thin driver wrapper
337// ---------------------------------------------------------------------------
338
339/// Renderer that emits XCTest `func test...() throws` methods using `URLSession`
340/// against the mock server (`ProcessInfo.processInfo.environment["MOCK_SERVER_URL"]`).
341struct SwiftTestClientRenderer;
342
343impl client::TestClientRenderer for SwiftTestClientRenderer {
344    fn language_name(&self) -> &'static str {
345        "swift"
346    }
347
348    fn sanitize_test_name(&self, id: &str) -> String {
349        // Swift test methods are `func testFoo()` — upper-camel-case after "test".
350        sanitize_ident(id).to_upper_camel_case()
351    }
352
353    /// Emit `func test{FnName}() throws {` (or a skip stub when the fixture is skipped).
354    ///
355    /// XCTest has no first-class skip annotation prior to Swift Testing (`@Test`).
356    /// For skipped fixtures we emit `try XCTSkipIf(true, reason)` inside the
357    /// function body so XCTest records them as skipped rather than omitting them.
358    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
359        let _ = writeln!(out, "    /// {description}");
360        let _ = writeln!(out, "    func test{fn_name}() throws {{");
361        if let Some(reason) = skip_reason {
362            let escaped = escape_swift(reason);
363            let _ = writeln!(out, "        try XCTSkipIf(true, \"{escaped}\")");
364        }
365    }
366
367    fn render_test_close(&self, out: &mut String) {
368        let _ = writeln!(out, "    }}");
369    }
370
371    /// Emit a synchronous `URLSession` round-trip to the mock server.
372    ///
373    /// `ProcessInfo.processInfo.environment["MOCK_SERVER_URL"]!` provides the base
374    /// URL; the fixture path is appended directly.  The call uses a semaphore so the
375    /// generated test body stays synchronous (compatible with `throws` functions —
376    /// no `async` XCTest support needed).
377    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
378        let method = ctx.method.to_uppercase();
379        let fixture_path = escape_swift(ctx.path);
380
381        let _ = writeln!(
382            out,
383            "        let _baseURL = ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]!"
384        );
385        let _ = writeln!(
386            out,
387            "        var _req = URLRequest(url: URL(string: _baseURL + \"{fixture_path}\")!)"
388        );
389        let _ = writeln!(out, "        _req.httpMethod = \"{method}\"");
390
391        // Headers
392        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
393        header_pairs.sort_by_key(|(k, _)| k.as_str());
394        for (k, v) in &header_pairs {
395            let expanded_v = expand_fixture_templates(v);
396            let ek = escape_swift(k);
397            let ev = escape_swift(&expanded_v);
398            let _ = writeln!(out, "        _req.setValue(\"{ev}\", forHTTPHeaderField: \"{ek}\")");
399        }
400
401        // Body
402        if let Some(body) = ctx.body {
403            let json_str = serde_json::to_string(body).unwrap_or_default();
404            let escaped_body = escape_swift(&json_str);
405            let _ = writeln!(out, "        _req.httpBody = \"{escaped_body}\".data(using: .utf8)");
406            let _ = writeln!(
407                out,
408                "        _req.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")"
409            );
410        }
411
412        let _ = writeln!(out, "        var {}: HTTPURLResponse?", ctx.response_var);
413        let _ = writeln!(out, "        var _responseData: Data?");
414        let _ = writeln!(out, "        let _sema = DispatchSemaphore(value: 0)");
415        let _ = writeln!(
416            out,
417            "        URLSession.shared.dataTask(with: _req) {{ data, resp, _ in"
418        );
419        let _ = writeln!(out, "            {} = resp as? HTTPURLResponse", ctx.response_var);
420        let _ = writeln!(out, "            _responseData = data");
421        let _ = writeln!(out, "            _sema.signal()");
422        let _ = writeln!(out, "        }}.resume()");
423        let _ = writeln!(out, "        _sema.wait()");
424        let _ = writeln!(out, "        let _resp = try XCTUnwrap({})", ctx.response_var);
425    }
426
427    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
428        let _ = writeln!(out, "        XCTAssertEqual(_resp.statusCode, {status})");
429    }
430
431    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
432        let lower_name = name.to_lowercase();
433        let header_expr = format!("_resp.value(forHTTPHeaderField: \"{}\")", escape_swift(&lower_name));
434        match expected {
435            "<<present>>" => {
436                let _ = writeln!(out, "        XCTAssertNotNil({header_expr})");
437            }
438            "<<absent>>" => {
439                let _ = writeln!(out, "        XCTAssertNil({header_expr})");
440            }
441            "<<uuid>>" => {
442                let _ = writeln!(out, "        let _hdrVal_{lower_name} = try XCTUnwrap({header_expr})");
443                let _ = writeln!(
444                    out,
445                    "        XCTAssertNotNil(_hdrVal_{lower_name}.range(of: #\"^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$\"#, options: .regularExpression))"
446                );
447            }
448            exact => {
449                let escaped = escape_swift(exact);
450                let _ = writeln!(out, "        XCTAssertEqual({header_expr}, \"{escaped}\")");
451            }
452        }
453    }
454
455    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
456        if let serde_json::Value::String(s) = expected {
457            let escaped = escape_swift(s);
458            let _ = writeln!(
459                out,
460                "        let _bodyStr = String(data: try XCTUnwrap(_responseData), encoding: .utf8) ?? \"\""
461            );
462            let _ = writeln!(
463                out,
464                "        XCTAssertEqual(_bodyStr.trimmingCharacters(in: .whitespacesAndNewlines), \"{escaped}\")"
465            );
466        } else {
467            let json_str = serde_json::to_string(expected).unwrap_or_default();
468            let escaped = escape_swift(&json_str);
469            let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
470            let _ = writeln!(
471                out,
472                "        let _expected = try JSONSerialization.jsonObject(with: \"{escaped}\".data(using: .utf8)!)"
473            );
474            let _ = writeln!(
475                out,
476                "        let _actual = try JSONSerialization.jsonObject(with: _bodyData)"
477            );
478            let _ = writeln!(
479                out,
480                "        XCTAssertEqual(NSDictionary(dictionary: _expected as? [String: AnyHashable] ?? [:]), NSDictionary(dictionary: _actual as? [String: AnyHashable] ?? [:]))"
481            );
482        }
483    }
484
485    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
486        if let Some(obj) = expected.as_object() {
487            let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
488            let _ = writeln!(
489                out,
490                "        let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
491            );
492            for (key, val) in obj {
493                let escaped_key = escape_swift(key);
494                let swift_val = json_to_swift(val);
495                let _ = writeln!(
496                    out,
497                    "        XCTAssertEqual(_bodyObj[\"{escaped_key}\"] as? AnyHashable, ({swift_val}) as AnyHashable)"
498                );
499            }
500        }
501    }
502
503    fn render_assert_validation_errors(
504        &self,
505        out: &mut String,
506        _response_var: &str,
507        errors: &[ValidationErrorExpectation],
508    ) {
509        let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
510        let _ = writeln!(
511            out,
512            "        let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
513        );
514        let _ = writeln!(
515            out,
516            "        let _errors = _bodyObj[\"errors\"] as? [[String: Any]] ?? []"
517        );
518        for ve in errors {
519            let escaped_msg = escape_swift(&ve.msg);
520            let _ = writeln!(
521                out,
522                "        XCTAssertTrue(_errors.contains(where: {{ ($0[\"msg\"] as? String)?.contains(\"{escaped_msg}\") == true }}), \"expected validation error: {escaped_msg}\")"
523            );
524        }
525    }
526}
527
528/// Render an XCTest method for an HTTP server fixture via the shared driver.
529///
530/// HTTP 101 (WebSocket upgrade) is emitted as a skip stub because `URLSession`
531/// cannot handle Upgrade responses.
532fn render_http_test_method(out: &mut String, fixture: &Fixture) {
533    let Some(http) = &fixture.http else {
534        return;
535    };
536
537    // HTTP 101 (WebSocket upgrade) — URLSession cannot handle upgrade responses.
538    if http.expected_response.status_code == 101 {
539        let method_name = sanitize_ident(&fixture.id).to_upper_camel_case();
540        let description = fixture.description.replace('"', "\\\"");
541        let _ = writeln!(out, "    /// {description}");
542        let _ = writeln!(out, "    func test{method_name}() throws {{");
543        let _ = writeln!(
544            out,
545            "        try XCTSkipIf(true, \"HTTP 101 WebSocket upgrade cannot be tested via URLSession\")"
546        );
547        let _ = writeln!(out, "    }}");
548        return;
549    }
550
551    client::http_call::render_http_test(out, &SwiftTestClientRenderer, fixture);
552}
553
554// ---------------------------------------------------------------------------
555// Function-call test rendering
556// ---------------------------------------------------------------------------
557
558#[allow(clippy::too_many_arguments)]
559fn render_test_method(
560    out: &mut String,
561    fixture: &Fixture,
562    e2e_config: &E2eConfig,
563    _function_name: &str,
564    _result_var: &str,
565    _args: &[crate::config::ArgMapping],
566    field_resolver: &FieldResolver,
567    result_is_simple: bool,
568    enum_fields: &HashSet<String>,
569    global_client_factory: Option<&str>,
570) {
571    // Resolve per-fixture call config.
572    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
573    let lang = "swift";
574    let call_overrides = call_config.overrides.get(lang);
575    let function_name = call_overrides
576        .and_then(|o| o.function.as_ref())
577        .cloned()
578        .unwrap_or_else(|| call_config.function.to_lower_camel_case());
579    // Per-call client_factory takes precedence over the global one.
580    let client_factory: Option<&str> = call_overrides
581        .and_then(|o| o.client_factory.as_deref())
582        .or(global_client_factory);
583    let result_var = &call_config.result_var;
584    let args = &call_config.args;
585    // Per-call flags: base call flag OR per-language override OR global flag.
586    let result_is_simple =
587        call_config.result_is_simple || call_overrides.is_some_and(|o| o.result_is_simple) || result_is_simple;
588    let result_is_array = call_config.result_is_array;
589
590    let method_name = fixture.id.to_upper_camel_case();
591    let description = &fixture.description;
592    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
593    let is_async = call_config.r#async;
594
595    // Detect whether this call has any json_object args that cannot be constructed
596    // in Swift — swift-bridge opaque types do not provide a fromJson initialiser.
597    // When such args exist and no `options_via` is configured for swift, emit a
598    // skip stub so the test compiles but is recorded as skipped rather than
599    // generating invalid code that passes `nil` or a string literal where a
600    // strongly-typed request object is required.
601    let has_unresolvable_json_object_arg = {
602        let options_via = call_overrides.and_then(|o| o.options_via.as_deref());
603        options_via.is_none() && args.iter().any(|a| a.arg_type == "json_object" && a.name != "config")
604    };
605
606    if has_unresolvable_json_object_arg {
607        if is_async {
608            let _ = writeln!(out, "    func test{method_name}() async throws {{");
609        } else {
610            let _ = writeln!(out, "    func test{method_name}() throws {{");
611        }
612        let _ = writeln!(out, "        // {description}");
613        let _ = writeln!(
614            out,
615            "        try XCTSkipIf(true, \"swift: json_object request construction requires options_via configuration (fixture: {})\");",
616            fixture.id
617        );
618        let _ = writeln!(out, "    }}");
619        return;
620    }
621
622    // Resolve extra_args from per-call swift overrides (e.g. `nil` for optional
623    // query-param arguments on list_files/list_batches that have no fixture-level
624    // input field).
625    let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
626
627    // Merge per-call enum_fields keys into the effective enum set so that
628    // fields like "status" (BatchStatus, BatchObject) are treated as enum-typed
629    // even when they are not globally listed in fields_enum (they are context-
630    // dependent — BatchStatus on BatchObject but plain String on ResponseObject).
631    let effective_enum_fields: std::borrow::Cow<HashSet<String>> = {
632        let per_call = call_overrides.map(|o| &o.enum_fields);
633        if let Some(pc) = per_call {
634            if !pc.is_empty() {
635                let mut merged = enum_fields.clone();
636                merged.extend(pc.keys().cloned());
637                std::borrow::Cow::Owned(merged)
638            } else {
639                std::borrow::Cow::Borrowed(enum_fields)
640            }
641        } else {
642            std::borrow::Cow::Borrowed(enum_fields)
643        }
644    };
645
646    let (setup_lines, args_str) = build_args_and_setup(&fixture.input, args, &fixture.id, &function_name);
647
648    // Append extra_args to the argument list.
649    let args_str = if extra_args.is_empty() {
650        args_str
651    } else if args_str.is_empty() {
652        extra_args.join(", ")
653    } else {
654        format!("{args_str}, {}", extra_args.join(", "))
655    };
656
657    // When a client_factory is set, dispatch via a client instance:
658    //   let client = try <FactoryType>(apiKey: "test-key", baseUrl: <mock_url>)
659    //   try await client.<method>(args)
660    // Otherwise fall back to free-function call (Kreuzberg / non-client-factory libraries).
661    let has_mock = fixture.mock_response.is_some();
662    let (call_setup, call_expr) = if let Some(_factory) = client_factory {
663        let mock_url = format!(
664            "ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\"",
665            fixture.id
666        );
667        let client_constructor = if has_mock {
668            format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
669        } else {
670            // Live API: check for api_key_var; if not present use mock URL anyway.
671            if let Some(env_var) = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref()) {
672                format!(
673                    "let _apiKey = ProcessInfo.processInfo.environment[\"{env_var}\"]\n        \
674                     let _baseUrl: String? = _apiKey != nil ? nil : {mock_url}\n        \
675                     let _client = try DefaultClient(apiKey: _apiKey ?? \"test-key\", baseUrl: _baseUrl)"
676                )
677            } else {
678                format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
679            }
680        };
681        let expr = if is_async {
682            format!("try await _client.{function_name}({args_str})")
683        } else {
684            format!("try _client.{function_name}({args_str})")
685        };
686        (Some(client_constructor), expr)
687    } else {
688        // Free-function call (no client_factory).
689        let expr = if is_async {
690            format!("try await {function_name}({args_str})")
691        } else {
692            format!("try {function_name}({args_str})")
693        };
694        (None, expr)
695    };
696    // For backwards compatibility: qualified_function_name unused when client_factory is set.
697    let _ = function_name;
698
699    if is_async {
700        let _ = writeln!(out, "    func test{method_name}() async throws {{");
701    } else {
702        let _ = writeln!(out, "    func test{method_name}() throws {{");
703    }
704    let _ = writeln!(out, "        // {description}");
705
706    for line in &setup_lines {
707        let _ = writeln!(out, "        {line}");
708    }
709
710    // Emit client construction if a client_factory is configured.
711    if let Some(setup) = &call_setup {
712        let _ = writeln!(out, "        {setup}");
713    }
714
715    if expects_error {
716        if is_async {
717            // XCTAssertThrowsError is a synchronous macro; for async-throwing
718            // functions use a do/catch with explicit XCTFail to enforce that
719            // the throw actually happens. `await XCTAssertThrowsError(...)` is
720            // not valid Swift — it evaluates `await` against a non-async expr.
721            let _ = writeln!(out, "        do {{");
722            let _ = writeln!(out, "            _ = {call_expr}");
723            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
724            let _ = writeln!(out, "        }} catch {{");
725            let _ = writeln!(out, "            // success");
726            let _ = writeln!(out, "        }}");
727        } else {
728            let _ = writeln!(out, "        XCTAssertThrowsError({call_expr})");
729        }
730        let _ = writeln!(out, "    }}");
731        return;
732    }
733
734    let _ = writeln!(out, "        let {result_var} = {call_expr}");
735
736    for assertion in &fixture.assertions {
737        render_assertion(
738            out,
739            assertion,
740            result_var,
741            field_resolver,
742            result_is_simple,
743            result_is_array,
744            &effective_enum_fields,
745        );
746    }
747
748    let _ = writeln!(out, "    }}");
749}
750
751/// Build setup lines and the argument list for the function call.
752///
753/// Swift-bridge wrappers require strongly-typed values that don't have implicit
754/// Swift literal conversions:
755///
756/// - `bytes` args become `RustVec<UInt8>` — fixture supplies a relative file path
757///   string which is read at test time and pushed into a `RustVec<UInt8>` setup
758///   variable. A literal byte array is base64-decoded or UTF-8 encoded inline.
759/// - `json_object` args become opaque `ExtractionConfig` (or sibling) instances —
760///   a JSON string is decoded via `extractionConfigFromJson(...)` in a setup line.
761/// - Optional args missing from the fixture must still appear at the call site
762///   as `nil` whenever a later positional arg is present, otherwise Swift slots
763///   subsequent values into the wrong parameter.
764fn build_args_and_setup(
765    input: &serde_json::Value,
766    args: &[crate::config::ArgMapping],
767    fixture_id: &str,
768    function_name: &str,
769) -> (Vec<String>, String) {
770    if args.is_empty() {
771        return (Vec::new(), String::new());
772    }
773
774    let mut setup_lines: Vec<String> = Vec::new();
775    let mut parts: Vec<String> = Vec::new();
776
777    // Pre-compute, for each arg index, whether any later arg has a fixture-provided
778    // value (or is required and will emit a default). When an optional arg is empty
779    // but a later arg WILL emit, we must keep the slot with `nil` so positional
780    // alignment is preserved.
781    let later_emits: Vec<bool> = (0..args.len())
782        .map(|i| {
783            args.iter().skip(i + 1).any(|a| {
784                let f = a.field.strip_prefix("input.").unwrap_or(&a.field);
785                let v = input.get(f);
786                let has_value = matches!(v, Some(x) if !x.is_null());
787                has_value || !a.optional || (a.arg_type == "json_object" && a.name == "config")
788            })
789        })
790        .collect();
791
792    for (idx, arg) in args.iter().enumerate() {
793        if arg.arg_type == "mock_url" {
794            setup_lines.push(format!(
795                "let {} = ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\"",
796                arg.name,
797            ));
798            parts.push(arg.name.clone());
799            continue;
800        }
801
802        if arg.arg_type == "handle" {
803            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
804            setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
805            parts.push(var_name);
806            continue;
807        }
808
809        // bytes args: fixture stores a fixture-relative path string. Generate
810        // setup that reads it into a Data and pushes each byte into a
811        // RustVec<UInt8>. Literal byte arrays inline the bytes; missing values
812        // produce an empty vec (or `nil` when optional).
813        if arg.arg_type == "bytes" {
814            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
815            let val = input.get(field);
816            match val {
817                None | Some(serde_json::Value::Null) if arg.optional => {
818                    if later_emits[idx] {
819                        parts.push("nil".to_string());
820                    }
821                }
822                None | Some(serde_json::Value::Null) => {
823                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
824                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
825                    parts.push(var_name);
826                }
827                Some(serde_json::Value::String(s)) => {
828                    let escaped = escape_swift(s);
829                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
830                    let data_var = format!("{}Data", arg.name.to_lower_camel_case());
831                    setup_lines.push(format!(
832                        "let {data_var} = try Data(contentsOf: URL(fileURLWithPath: \"{escaped}\"))"
833                    ));
834                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
835                    setup_lines.push(format!("for _byte in {data_var} {{ {var_name}.push(value: _byte) }}"));
836                    parts.push(var_name);
837                }
838                Some(serde_json::Value::Array(arr)) => {
839                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
840                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
841                    for v in arr {
842                        if let Some(n) = v.as_u64() {
843                            setup_lines.push(format!("{var_name}.push(value: UInt8({n}))"));
844                        }
845                    }
846                    parts.push(var_name);
847                }
848                Some(other) => {
849                    // Fallback: encode the JSON serialisation as UTF-8 bytes.
850                    let json_str = serde_json::to_string(other).unwrap_or_default();
851                    let escaped = escape_swift(&json_str);
852                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
853                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
854                    setup_lines.push(format!(
855                        "for _byte in Array(\"{escaped}\".utf8) {{ {var_name}.push(value: _byte) }}"
856                    ));
857                    parts.push(var_name);
858                }
859            }
860            continue;
861        }
862
863        // json_object "config" args: the swift-bridge wrapper requires an opaque
864        // `ExtractionConfig` (or sibling) instance, not a JSON string. Use the
865        // generated `extractionConfigFromJson(_:)` helper from RustBridge.
866        // Batch functions (batchExtract*) hardcode config internally — skip it.
867        let is_config_arg = arg.name == "config" && arg.arg_type == "json_object";
868        let is_batch_fn = function_name.starts_with("batch") || function_name.starts_with("Batch");
869        if is_config_arg && !is_batch_fn {
870            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
871            let val = input.get(field);
872            let json_str = match val {
873                None | Some(serde_json::Value::Null) => "{}".to_string(),
874                Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
875            };
876            let escaped = escape_swift(&json_str);
877            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
878            setup_lines.push(format!("let {var_name} = try extractionConfigFromJson(\"{escaped}\")"));
879            parts.push(var_name);
880            continue;
881        }
882
883        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
884        let val = input.get(field);
885        match val {
886            None | Some(serde_json::Value::Null) if arg.optional => {
887                // Optional arg with no fixture value: keep the slot with `nil`
888                // when a later arg will emit, so positional alignment matches
889                // the swift-bridge wrapper signature.
890                if later_emits[idx] {
891                    parts.push("nil".to_string());
892                }
893            }
894            None | Some(serde_json::Value::Null) => {
895                let default_val = match arg.arg_type.as_str() {
896                    "string" => "\"\"".to_string(),
897                    "int" | "integer" => "0".to_string(),
898                    "float" | "number" => "0.0".to_string(),
899                    "bool" | "boolean" => "false".to_string(),
900                    _ => "nil".to_string(),
901                };
902                parts.push(default_val);
903            }
904            Some(v) => {
905                parts.push(json_to_swift(v));
906            }
907        }
908    }
909
910    (setup_lines, parts.join(", "))
911}
912
913fn render_assertion(
914    out: &mut String,
915    assertion: &Assertion,
916    result_var: &str,
917    field_resolver: &FieldResolver,
918    result_is_simple: bool,
919    result_is_array: bool,
920    enum_fields: &HashSet<String>,
921) {
922    // Skip assertions on fields that don't exist on the result type.
923    if let Some(f) = &assertion.field {
924        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
925            let _ = writeln!(out, "        // skipped: field '{{f}}' not available on result type");
926            return;
927        }
928    }
929
930    // Skip assertions that traverse a tagged-union variant boundary.
931    // In Swift, FormatMetadata and similar enum-backed opaque types are exposed as
932    // plain classes by swift-bridge — variant accessor methods (e.g., `.excel()`)
933    // are not generated, so such assertions cannot be expressed.
934    if let Some(f) = &assertion.field {
935        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
936            let _ = writeln!(
937                out,
938                "        // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Swift)"
939            );
940            return;
941        }
942    }
943
944    // Determine if this field is an enum type.
945    let field_is_enum = assertion
946        .field
947        .as_deref()
948        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
949
950    let field_is_optional = assertion.field.as_deref().is_some_and(|f| {
951        !f.is_empty() && (field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f)))
952    });
953    let field_is_array = assertion.field.as_deref().is_some_and(|f| {
954        !f.is_empty() && (field_resolver.is_array(f) || field_resolver.is_array(field_resolver.resolve(f)))
955    });
956
957    let field_expr = if result_is_simple {
958        result_var.to_string()
959    } else {
960        match &assertion.field {
961            Some(f) if !f.is_empty() => field_resolver.accessor(f, "swift", result_var),
962            _ => result_var.to_string(),
963        }
964    };
965
966    // In Swift, optional chaining with `?.` makes the result optional even if the
967    // called method's return type isn't marked optional. For example:
968    // `result.markdown()?.content()` returns `Optional<RustString>` because
969    // `markdown()` is optional and the `?.` operator wraps the result.
970    // Detect this by checking if the accessor contains `?.`.
971    let accessor_is_optional = field_expr.contains("?.");
972
973    // For enum fields, need to handle the string representation differently in Swift.
974    // Swift enums don't have `.rawValue` unless they're explicitly RawRepresentable.
975    // Check if this is an enum type and handle accordingly.
976    // For optional fields (Optional<RustString>), use optional chaining before toString().
977    // For other fields: swift-bridge returns all Rust `String` fields as `RustString`.
978    // We add .toString() here so string assertions (contains, hasPrefix, etc.) work.
979    // Non-string opaque fields (DocumentStructure, etc.) should not appear in string
980    // assertions — the fixture schema controls which assertions apply to which fields.
981    let string_expr = if field_is_enum {
982        // Swift enums generated by swift-bridge are plain enums (not RawRepresentable).
983        // To get a string representation, we need to match on the enum or use a description.
984        // For now, just use the enum name directly without .rawValue.
985        field_expr.clone()
986    } else if field_is_optional {
987        // Leaf field itself is Optional<RustString> — need ?.toString() to unwrap.
988        format!("({field_expr}?.toString() ?? \"\")")
989    } else if accessor_is_optional {
990        // Ancestor optional chain propagates; leaf is non-optional RustString within chain.
991        // Use .toString() directly — the whole expr is Optional<String> due to propagation.
992        format!("({field_expr}.toString() ?? \"\")")
993    } else {
994        format!("{field_expr}.toString()")
995    };
996
997    match assertion.assertion_type.as_str() {
998        "equals" => {
999            if let Some(expected) = &assertion.value {
1000                let swift_val = json_to_swift(expected);
1001                if expected.is_string() {
1002                    if field_is_enum {
1003                        // For enum fields, compare the string representation of the enum case.
1004                        // Use String(describing:) to get the case name.
1005                        let enum_str = format!("String(describing: {field_expr})");
1006                        let trim_expr = format!("{enum_str}.trimmingCharacters(in: CharacterSet.whitespaces)");
1007                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1008                    } else {
1009                        // For optional strings (String?), use ?? to coalesce before trimming.
1010                        // `.toString()` converts RustString → Swift String before calling
1011                        // `.trimmingCharacters`, which requires a concrete String type.
1012                        // string_expr already incorporates field_is_optional via ?.toString() ?? "".
1013                        let trim_expr = format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespaces)");
1014                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1015                    }
1016                } else {
1017                    let _ = writeln!(out, "        XCTAssertEqual({field_expr}, {swift_val})");
1018                }
1019            }
1020        }
1021        "contains" => {
1022            if let Some(expected) = &assertion.value {
1023                let swift_val = json_to_swift(expected);
1024                // When the root result IS the array (result_is_simple + result_is_array) and
1025                // there is no field path, check array membership via map+contains.
1026                let no_field = assertion.field.as_deref().is_none_or(|f| f.is_empty());
1027                if result_is_simple && result_is_array && no_field {
1028                    // RustVec<RustString> iteration yields RustStringRef (no `toString()`);
1029                    // use `.as_str().toString()` to convert each element to a Swift String.
1030                    let _ = writeln!(
1031                        out,
1032                        "        XCTAssertTrue({result_var}.map {{ $0.as_str().toString() }}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1033                    );
1034                } else {
1035                    // For array fields (RustVec<RustString>), check membership via map+contains.
1036                    let field_is_array = assertion
1037                        .field
1038                        .as_deref()
1039                        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1040                    if field_is_array {
1041                        let contains_expr =
1042                            swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1043                        let _ = writeln!(
1044                            out,
1045                            "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1046                        );
1047                    } else if field_is_enum {
1048                        // For enum fields, check if the string representation contains the substring.
1049                        let enum_str = format!("String(describing: {field_expr})");
1050                        let _ = writeln!(
1051                            out,
1052                            "        XCTAssertTrue({enum_str}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1053                        );
1054                    } else {
1055                        let _ = writeln!(
1056                            out,
1057                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1058                        );
1059                    }
1060                }
1061            }
1062        }
1063        "contains_all" => {
1064            if let Some(values) = &assertion.values {
1065                // For array fields (RustVec<RustString>), check membership via map+contains.
1066                let field_is_array = assertion
1067                    .field
1068                    .as_deref()
1069                    .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1070                if field_is_array {
1071                    let contains_expr =
1072                        swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1073                    for val in values {
1074                        let swift_val = json_to_swift(val);
1075                        let _ = writeln!(
1076                            out,
1077                            "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1078                        );
1079                    }
1080                } else if field_is_enum {
1081                    // For enum fields, check if the string representation contains all substrings.
1082                    let enum_str = format!("String(describing: {field_expr})");
1083                    for val in values {
1084                        let swift_val = json_to_swift(val);
1085                        let _ = writeln!(
1086                            out,
1087                            "        XCTAssertTrue({enum_str}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1088                        );
1089                    }
1090                } else {
1091                    for val in values {
1092                        let swift_val = json_to_swift(val);
1093                        let _ = writeln!(
1094                            out,
1095                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1096                        );
1097                    }
1098                }
1099            }
1100        }
1101        "not_contains" => {
1102            if let Some(expected) = &assertion.value {
1103                let swift_val = json_to_swift(expected);
1104                let _ = writeln!(
1105                    out,
1106                    "        XCTAssertFalse({string_expr}.contains({swift_val}), \"expected NOT to contain: \\({swift_val})\")"
1107                );
1108            }
1109        }
1110        "not_empty" => {
1111            // For optional fields (Optional<T>), check that the value is non-nil.
1112            // For array fields (RustVec<T>), check .isEmpty on the vec directly.
1113            // For result_is_simple (e.g. Data, String), use .isEmpty directly on
1114            // the result — avoids calling .toString() on non-RustString types.
1115            // For string fields, convert to Swift String and check .isEmpty.
1116            if field_is_optional {
1117                let _ = writeln!(out, "        XCTAssertNotNil({field_expr}, \"expected non-nil value\")");
1118            } else if field_is_array {
1119                let _ = writeln!(
1120                    out,
1121                    "        XCTAssertFalse({field_expr}.isEmpty, \"expected non-empty value\")"
1122                );
1123            } else if result_is_simple {
1124                // result_is_simple: result is a primitive (Data, String, etc.) — use .isEmpty directly.
1125                let _ = writeln!(
1126                    out,
1127                    "        XCTAssertFalse({result_var}.isEmpty, \"expected non-empty value\")"
1128                );
1129            } else {
1130                // string_expr has .toString() appended; .isEmpty works on Swift String.
1131                let _ = writeln!(
1132                    out,
1133                    "        XCTAssertFalse({string_expr}.isEmpty, \"expected non-empty value\")"
1134                );
1135            }
1136        }
1137        "is_empty" => {
1138            if field_is_optional {
1139                let _ = writeln!(out, "        XCTAssertNil({field_expr}, \"expected nil value\")");
1140            } else if field_is_array {
1141                let _ = writeln!(
1142                    out,
1143                    "        XCTAssertTrue({field_expr}.isEmpty, \"expected empty value\")"
1144                );
1145            } else {
1146                let _ = writeln!(
1147                    out,
1148                    "        XCTAssertTrue({string_expr}.isEmpty, \"expected empty value\")"
1149                );
1150            }
1151        }
1152        "contains_any" => {
1153            if let Some(values) = &assertion.values {
1154                let checks: Vec<String> = values
1155                    .iter()
1156                    .map(|v| {
1157                        let swift_val = json_to_swift(v);
1158                        format!("{string_expr}.contains({swift_val})")
1159                    })
1160                    .collect();
1161                let joined = checks.join(" || ");
1162                let _ = writeln!(
1163                    out,
1164                    "        XCTAssertTrue({joined}, \"expected to contain at least one of the specified values\")"
1165                );
1166            }
1167        }
1168        "greater_than" => {
1169            if let Some(val) = &assertion.value {
1170                let swift_val = json_to_swift(val);
1171                // For optional numeric fields (or when the accessor chain is optional),
1172                // coalesce to 0 before comparing so the expression is non-optional.
1173                let field_is_optional = accessor_is_optional
1174                    || assertion.field.as_deref().is_some_and(|f| {
1175                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1176                    });
1177                let compare_expr = if field_is_optional {
1178                    format!("({field_expr} ?? 0)")
1179                } else {
1180                    field_expr.clone()
1181                };
1182                let _ = writeln!(out, "        XCTAssertGreaterThan({compare_expr}, {swift_val})");
1183            }
1184        }
1185        "less_than" => {
1186            if let Some(val) = &assertion.value {
1187                let swift_val = json_to_swift(val);
1188                let field_is_optional = accessor_is_optional
1189                    || assertion.field.as_deref().is_some_and(|f| {
1190                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1191                    });
1192                let compare_expr = if field_is_optional {
1193                    format!("({field_expr} ?? 0)")
1194                } else {
1195                    field_expr.clone()
1196                };
1197                let _ = writeln!(out, "        XCTAssertLessThan({compare_expr}, {swift_val})");
1198            }
1199        }
1200        "greater_than_or_equal" => {
1201            if let Some(val) = &assertion.value {
1202                let swift_val = json_to_swift(val);
1203                // For optional numeric fields (or when the accessor chain is optional),
1204                // coalesce to 0 before comparing so the expression is non-optional.
1205                let field_is_optional = accessor_is_optional
1206                    || assertion.field.as_deref().is_some_and(|f| {
1207                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1208                    });
1209                let compare_expr = if field_is_optional {
1210                    format!("({field_expr} ?? 0)")
1211                } else {
1212                    field_expr.clone()
1213                };
1214                let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({compare_expr}, {swift_val})");
1215            }
1216        }
1217        "less_than_or_equal" => {
1218            if let Some(val) = &assertion.value {
1219                let swift_val = json_to_swift(val);
1220                let field_is_optional = accessor_is_optional
1221                    || assertion.field.as_deref().is_some_and(|f| {
1222                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1223                    });
1224                let compare_expr = if field_is_optional {
1225                    format!("({field_expr} ?? 0)")
1226                } else {
1227                    field_expr.clone()
1228                };
1229                let _ = writeln!(out, "        XCTAssertLessThanOrEqual({compare_expr}, {swift_val})");
1230            }
1231        }
1232        "starts_with" => {
1233            if let Some(expected) = &assertion.value {
1234                let swift_val = json_to_swift(expected);
1235                let _ = writeln!(
1236                    out,
1237                    "        XCTAssertTrue({string_expr}.hasPrefix({swift_val}), \"expected to start with: \\({swift_val})\")"
1238                );
1239            }
1240        }
1241        "ends_with" => {
1242            if let Some(expected) = &assertion.value {
1243                let swift_val = json_to_swift(expected);
1244                let _ = writeln!(
1245                    out,
1246                    "        XCTAssertTrue({string_expr}.hasSuffix({swift_val}), \"expected to end with: \\({swift_val})\")"
1247                );
1248            }
1249        }
1250        "min_length" => {
1251            if let Some(val) = &assertion.value {
1252                if let Some(n) = val.as_u64() {
1253                    // Use string_expr.count: for RustString fields string_expr already has
1254                    // .toString() appended, giving a Swift String whose .count is character count.
1255                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({string_expr}.count, {n})");
1256                }
1257            }
1258        }
1259        "max_length" => {
1260            if let Some(val) = &assertion.value {
1261                if let Some(n) = val.as_u64() {
1262                    let _ = writeln!(out, "        XCTAssertLessThanOrEqual({string_expr}.count, {n})");
1263                }
1264            }
1265        }
1266        "count_min" => {
1267            if let Some(val) = &assertion.value {
1268                if let Some(n) = val.as_u64() {
1269                    // For fields nested inside an optional parent (e.g. document.nodes where
1270                    // document is Optional), the accessor generates `result.document().nodes()`
1271                    // which doesn't compile in Swift without optional chaining.
1272                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1273                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({count_expr}, {n})");
1274                }
1275            }
1276        }
1277        "count_equals" => {
1278            if let Some(val) = &assertion.value {
1279                if let Some(n) = val.as_u64() {
1280                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1281                    let _ = writeln!(out, "        XCTAssertEqual({count_expr}, {n})");
1282                }
1283            }
1284        }
1285        "is_true" => {
1286            let _ = writeln!(out, "        XCTAssertTrue({field_expr})");
1287        }
1288        "is_false" => {
1289            let _ = writeln!(out, "        XCTAssertFalse({field_expr})");
1290        }
1291        "matches_regex" => {
1292            if let Some(expected) = &assertion.value {
1293                let swift_val = json_to_swift(expected);
1294                let _ = writeln!(
1295                    out,
1296                    "        XCTAssertNotNil({string_expr}.range(of: {swift_val}, options: .regularExpression), \"expected value to match regex: \\({swift_val})\")"
1297                );
1298            }
1299        }
1300        "not_error" => {
1301            // Already handled by the call succeeding without exception.
1302        }
1303        "error" => {
1304            // Handled at the test method level.
1305        }
1306        "method_result" => {
1307            let _ = writeln!(out, "        // method_result assertions not yet implemented for Swift");
1308        }
1309        other => {
1310            panic!("Swift e2e generator: unsupported assertion type: {other}");
1311        }
1312    }
1313}
1314
1315/// Build a Swift accessor path for the given fixture field, inserting `()` on
1316/// every segment and `?` after every optional non-leaf segment.
1317///
1318/// This is the core helper for count/contains helpers that need to reconstruct
1319/// the path with correct optional chaining from the raw fixture field name.
1320///
1321/// Returns `(accessor_expr, has_optional)` where `has_optional` is true when
1322/// at least one `?.` was inserted.
1323fn swift_build_accessor(field: &str, result_var: &str, field_resolver: &FieldResolver) -> (String, bool) {
1324    let resolved = field_resolver.resolve(field);
1325    let parts: Vec<&str> = resolved.split('.').collect();
1326
1327    // Build a set of optional prefix paths for O(1) lookup during the walk.
1328    // We track path_so_far incrementally.
1329    let mut out = result_var.to_string();
1330    let mut has_optional = false;
1331    let mut path_so_far = String::new();
1332    let total = parts.len();
1333    for (i, part) in parts.iter().enumerate() {
1334        let is_leaf = i == total - 1;
1335        // Handle array index subscripts within a segment, e.g. `data[0]`.
1336        // `data[0]` must become `.data()[0]` not `.data[0]()`.
1337        // Split at the first `[` if present.
1338        let (field_name, subscript): (&str, Option<&str>) = if let Some(bracket_pos) = part.find('[') {
1339            (&part[..bracket_pos], Some(&part[bracket_pos..]))
1340        } else {
1341            (part, None)
1342        };
1343
1344        if !path_so_far.is_empty() {
1345            path_so_far.push('.');
1346        }
1347        path_so_far.push_str(part);
1348        out.push('.');
1349        out.push_str(field_name);
1350        out.push_str("()");
1351        if let Some(sub) = subscript {
1352            out.push_str(sub);
1353        }
1354        // Insert `?` after the last `()` (or subscript) for any non-leaf optional field
1355        // so the next member access becomes `?.`.
1356        if !is_leaf && field_resolver.is_optional(&path_so_far) {
1357            out.push('?');
1358            has_optional = true;
1359        }
1360    }
1361    (out, has_optional)
1362}
1363
1364/// Generate a `[String]?` expression for a `RustVec<RustString>` (or optional variant) field
1365/// so that `contains` membership checks work against plain Swift Strings.
1366///
1367/// The result is `Optional<[String]>` — callers should coalesce with `?? []`.
1368///
1369/// We use `?.map { $0.as_str().toString() }` because:
1370/// 1. Iterating a `RustVec<RustString>` yields `RustStringRef` (not `RustString`), which
1371///    only has `as_str()` but not `toString()` directly.
1372/// 2. The accessor may end with an `Optional<RustVec<RustString>>` (e.g. `sheet_names()` is
1373///    `Option<Vec<String>>` in Rust, which becomes `Optional<RustVec<RustString>>` in Swift).
1374/// 3. Optional chaining from parent `?.` already produces `Optional<RustVec<T>>`.
1375///
1376/// `?.map { $0.as_str().toString() }` converts each `RustStringRef` to a Swift `String`,
1377/// giving `[String]` wrapped in `Optional`. The `?? []` in callers coalesces nil to an empty
1378/// array.
1379fn swift_array_contains_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
1380    let Some(f) = field else {
1381        return format!("{result_var}.map {{ $0.as_str().toString() }}");
1382    };
1383    let (accessor, _has_optional) = swift_build_accessor(f, result_var, field_resolver);
1384    // Always use `?.map` — the array field (sheet_names, etc.) may itself return
1385    // Optional<RustVec<T>> even if not listed in fields_optional.
1386    format!("{accessor}?.map {{ $0.as_str().toString() }}")
1387}
1388
1389/// Generate a `.count` expression for an array field that may be nested inside optional parents.
1390///
1391/// Swift-bridge exposes all Rust fields as methods with `()`. When ancestor segments are
1392/// optional, we use `?.` chaining. The final count is coalesced with `?? 0` when there
1393/// are optional ancestors so the XCTAssert macro receives a non-optional `Int`.
1394///
1395/// Also check if the field itself (the leaf) is optional, which happens when the field
1396/// returns Optional<RustVec<T>> (e.g., `links()` may return Optional).
1397fn swift_array_count_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
1398    let Some(f) = field else {
1399        return format!("{result_var}.count");
1400    };
1401    let (accessor, mut has_optional) = swift_build_accessor(f, result_var, field_resolver);
1402    // Also check if the leaf field itself is optional.
1403    if field_resolver.is_optional(f) {
1404        has_optional = true;
1405    }
1406    if has_optional {
1407        // In Swift, accessing .count on an optional with ?. returns Optional<Int>,
1408        // so we coalesce with ?? 0 to get a concrete Int for XCTAssert.
1409        if accessor.contains("?.") {
1410            format!("{accessor}.count ?? 0")
1411        } else {
1412            // If no ?. but field is optional, the field_expr itself is Optional<RustVec<T>>
1413            // so we need ?. to call count.
1414            format!("({accessor}?.count ?? 0)")
1415        }
1416    } else {
1417        format!("{accessor}.count")
1418    }
1419}
1420
1421/// Normalise a path by resolving `..` components without hitting the filesystem.
1422///
1423/// This mirrors what `std::fs::canonicalize` does but works on paths that do
1424/// not yet exist on disk (generated-file paths).  Only `..` traversals are
1425/// collapsed; `.` components are dropped; nothing else is changed.
1426fn normalize_path(path: &std::path::Path) -> std::path::PathBuf {
1427    let mut components = std::path::PathBuf::new();
1428    for component in path.components() {
1429        match component {
1430            std::path::Component::ParentDir => {
1431                // Pop the last pushed component if there is one that isn't
1432                // already a `..` (avoids over-collapsing `../../foo`).
1433                if !components.as_os_str().is_empty() {
1434                    components.pop();
1435                } else {
1436                    components.push(component);
1437                }
1438            }
1439            std::path::Component::CurDir => {}
1440            other => components.push(other),
1441        }
1442    }
1443    components
1444}
1445
1446/// Convert a `serde_json::Value` to a Swift literal string.
1447fn json_to_swift(value: &serde_json::Value) -> String {
1448    match value {
1449        serde_json::Value::String(s) => format!("\"{}\"", escape_swift(s)),
1450        serde_json::Value::Bool(b) => b.to_string(),
1451        serde_json::Value::Number(n) => n.to_string(),
1452        serde_json::Value::Null => "nil".to_string(),
1453        serde_json::Value::Array(arr) => {
1454            let items: Vec<String> = arr.iter().map(json_to_swift).collect();
1455            format!("[{}]", items.join(", "))
1456        }
1457        serde_json::Value::Object(_) => {
1458            let json_str = serde_json::to_string(value).unwrap_or_default();
1459            format!("\"{}\"", escape_swift(&json_str))
1460        }
1461    }
1462}
1463
1464/// Escape a string for embedding in a Swift double-quoted string literal.
1465fn escape_swift(s: &str) -> String {
1466    escape_swift_str(s)
1467}