1use crate::config::E2eConfig;
7use crate::escape::{escape_zig, sanitize_filename};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, Fixture, FixtureGroup};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::ResolvedCrateConfig;
12use alef_core::hash::{self, CommentStyle};
13use alef_core::template_versions::toolchain;
14use anyhow::Result;
15use heck::ToSnakeCase;
16use std::collections::HashSet;
17use std::fmt::Write as FmtWrite;
18use std::path::PathBuf;
19
20use super::E2eCodegen;
21use super::client;
22use super::streaming_assertions::{StreamingFieldResolver, is_streaming_virtual_field};
23
24pub struct ZigE2eCodegen;
26
27impl E2eCodegen for ZigE2eCodegen {
28 fn generate(
29 &self,
30 groups: &[FixtureGroup],
31 e2e_config: &E2eConfig,
32 config: &ResolvedCrateConfig,
33 _type_defs: &[alef_core::ir::TypeDef],
34 ) -> Result<Vec<GeneratedFile>> {
35 let lang = self.language_name();
36 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38 let mut files = Vec::new();
39
40 let call = &e2e_config.call;
42 let overrides = call.overrides.get(lang);
43 let _module_path = overrides
44 .and_then(|o| o.module.as_ref())
45 .cloned()
46 .unwrap_or_else(|| call.module.clone());
47 let function_name = overrides
48 .and_then(|o| o.function.as_ref())
49 .cloned()
50 .unwrap_or_else(|| call.function.clone());
51 let result_var = &call.result_var;
52
53 let zig_pkg = e2e_config.resolve_package("zig");
55 let pkg_path = zig_pkg
56 .as_ref()
57 .and_then(|p| p.path.as_ref())
58 .cloned()
59 .unwrap_or_else(|| "../../packages/zig".to_string());
60 let pkg_name = zig_pkg
61 .as_ref()
62 .and_then(|p| p.name.as_ref())
63 .cloned()
64 .unwrap_or_else(|| config.name.to_snake_case());
65
66 files.push(GeneratedFile {
68 path: output_base.join("build.zig.zon"),
69 content: render_build_zig_zon(&pkg_name, &pkg_path, e2e_config.dep_mode),
70 generated_header: false,
71 });
72
73 let module_name = config.zig_module_name();
75
76 let field_resolver = FieldResolver::new(
78 &e2e_config.fields,
79 &e2e_config.fields_optional,
80 &e2e_config.result_fields,
81 &e2e_config.fields_array,
82 &e2e_config.fields_method_calls,
83 );
84
85 let mut test_filenames: Vec<String> = Vec::new();
87 for group in groups {
88 let active: Vec<&Fixture> = group
89 .fixtures
90 .iter()
91 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
92 .collect();
93
94 if active.is_empty() {
95 continue;
96 }
97
98 let filename = format!("{}_test.zig", sanitize_filename(&group.category));
99 test_filenames.push(filename.clone());
100 let content = render_test_file(
101 &group.category,
102 &active,
103 e2e_config,
104 &function_name,
105 result_var,
106 &e2e_config.call.args,
107 &field_resolver,
108 &e2e_config.fields_enum,
109 &module_name,
110 );
111 files.push(GeneratedFile {
112 path: output_base.join("src").join(filename),
113 content,
114 generated_header: true,
115 });
116 }
117
118 files.insert(
120 files
121 .iter()
122 .position(|f| f.path.file_name().is_some_and(|n| n == "build.zig.zon"))
123 .unwrap_or(1),
124 GeneratedFile {
125 path: output_base.join("build.zig"),
126 content: render_build_zig(
127 &test_filenames,
128 &pkg_name,
129 &module_name,
130 &config.ffi_lib_name(),
131 &config.ffi_crate_path(),
132 &e2e_config.test_documents_relative_from(0),
133 ),
134 generated_header: false,
135 },
136 );
137
138 Ok(files)
139 }
140
141 fn language_name(&self) -> &'static str {
142 "zig"
143 }
144}
145
146fn render_build_zig_zon(pkg_name: &str, pkg_path: &str, dep_mode: crate::config::DependencyMode) -> String {
151 let dep_block = match dep_mode {
152 crate::config::DependencyMode::Registry => {
153 format!(
155 r#".{{
156 .url = "https://registry.example.com/{pkg_name}/v0.1.0.tar.gz",
157 .hash = "0000000000000000000000000000000000000000000000000000000000000000",
158 }}"#
159 )
160 }
161 crate::config::DependencyMode::Local => {
162 format!(r#".{{ .path = "{pkg_path}" }}"#)
163 }
164 };
165
166 let min_zig = toolchain::MIN_ZIG_VERSION;
167 let name_bytes: &[u8] = b"e2e_zig";
169 let mut crc: u32 = 0xffff_ffff;
170 for byte in name_bytes {
171 crc ^= *byte as u32;
172 for _ in 0..8 {
173 let mask = (crc & 1).wrapping_neg();
174 crc = (crc >> 1) ^ (0xedb8_8320 & mask);
175 }
176 }
177 let name_crc: u32 = !crc;
178 let mut id: u32 = 0x811c_9dc5;
179 for byte in name_bytes {
180 id ^= *byte as u32;
181 id = id.wrapping_mul(0x0100_0193);
182 }
183 if id == 0 || id == 0xffff_ffff {
184 id = 0x1;
185 }
186 let fingerprint: u64 = ((name_crc as u64) << 32) | (id as u64);
187 format!(
188 r#".{{
189 .name = .e2e_zig,
190 .version = "0.1.0",
191 .fingerprint = 0x{fingerprint:016x},
192 .minimum_zig_version = "{min_zig}",
193 .dependencies = .{{
194 .{pkg_name} = {dep_block},
195 }},
196 .paths = .{{
197 "build.zig",
198 "build.zig.zon",
199 "src",
200 }},
201}}
202"#
203 )
204}
205
206fn render_build_zig(
207 test_filenames: &[String],
208 pkg_name: &str,
209 module_name: &str,
210 ffi_lib_name: &str,
211 ffi_crate_path: &str,
212 test_documents_path: &str,
213) -> String {
214 if test_filenames.is_empty() {
215 return r#"const std = @import("std");
216
217pub fn build(b: *std.Build) void {
218 const target = b.standardTargetOptions(.{});
219 const optimize = b.standardOptimizeOption(.{});
220
221 const test_step = b.step("test", "Run tests");
222}
223"#
224 .to_string();
225 }
226
227 let mut content = String::from("const std = @import(\"std\");\n\npub fn build(b: *std.Build) void {\n");
237 content.push_str(" const target = b.standardTargetOptions(.{});\n");
238 content.push_str(" const optimize = b.standardOptimizeOption(.{});\n");
239 content.push_str(" const test_step = b.step(\"test\", \"Run tests\");\n");
240 let _ = writeln!(
241 content,
242 " const ffi_path = b.option([]const u8, \"ffi_path\", \"Path to directory containing lib{ffi_lib_name}\") orelse \"../../target/debug\";"
243 );
244 let _ = writeln!(
245 content,
246 " const ffi_include = b.option([]const u8, \"ffi_include_path\", \"Path to directory containing FFI header\") orelse \"{ffi_crate_path}/include\";"
247 );
248 let _ = writeln!(content);
249 let _ = writeln!(
250 content,
251 " const {module_name}_module = b.addModule(\"{module_name}\", .{{"
252 );
253 let _ = writeln!(
254 content,
255 " .root_source_file = b.path(\"../../packages/zig/src/{pkg_name}.zig\"),"
256 );
257 content.push_str(" .target = target,\n");
258 content.push_str(" .optimize = optimize,\n");
259 content.push_str(" });\n");
260 let _ = writeln!(
261 content,
262 " {module_name}_module.addLibraryPath(.{{ .cwd_relative = ffi_path }});"
263 );
264 let _ = writeln!(
265 content,
266 " {module_name}_module.addIncludePath(.{{ .cwd_relative = ffi_include }});"
267 );
268 let _ = writeln!(
269 content,
270 " {module_name}_module.linkSystemLibrary(\"{ffi_lib_name}\", .{{}});"
271 );
272 let _ = writeln!(content);
273
274 for filename in test_filenames {
275 let test_name = filename.trim_end_matches("_test.zig");
277 content.push_str(&format!(" const {test_name}_module = b.createModule(.{{\n"));
278 content.push_str(&format!(" .root_source_file = b.path(\"src/{filename}\"),\n"));
279 content.push_str(" .target = target,\n");
280 content.push_str(" .optimize = optimize,\n");
281 content.push_str(" });\n");
282 content.push_str(&format!(
283 " {test_name}_module.addImport(\"{module_name}\", {module_name}_module);\n"
284 ));
285 content.push_str(&format!(" const {test_name}_tests = b.addTest(.{{\n"));
286 content.push_str(&format!(" .root_module = {test_name}_module,\n"));
287 content.push_str(" });\n");
288 content.push_str(&format!(
289 " const {test_name}_run = b.addRunArtifact({test_name}_tests);\n"
290 ));
291 content.push_str(&format!(
292 " {test_name}_run.setCwd(b.path(\"{test_documents_path}\"));\n"
293 ));
294 content.push_str(&format!(" test_step.dependOn(&{test_name}_run.step);\n\n"));
295 }
296
297 content.push_str("}\n");
298 content
299}
300
301struct ZigTestClientRenderer;
309
310impl client::TestClientRenderer for ZigTestClientRenderer {
311 fn language_name(&self) -> &'static str {
312 "zig"
313 }
314
315 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
316 if let Some(reason) = skip_reason {
317 let _ = writeln!(out, "test \"{fn_name}\" {{");
318 let _ = writeln!(out, " // {description}");
319 let _ = writeln!(out, " // skipped: {reason}");
320 let _ = writeln!(out, " return error.SkipZigTest;");
321 } else {
322 let _ = writeln!(out, "test \"{fn_name}\" {{");
323 let _ = writeln!(out, " // {description}");
324 }
325 }
326
327 fn render_test_close(&self, out: &mut String) {
328 let _ = writeln!(out, "}}");
329 }
330
331 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
332 let method = ctx.method.to_uppercase();
333 let fixture_id = ctx.path.trim_start_matches("/fixtures/");
334
335 let _ = writeln!(out, " var gpa: std.heap.DebugAllocator(.{{}}) = .init;");
336 let _ = writeln!(out, " defer _ = gpa.deinit();");
337 let _ = writeln!(out, " const allocator = gpa.allocator();");
338
339 let _ = writeln!(out, " var url_buf: [512]u8 = undefined;");
340 let _ = writeln!(
341 out,
342 " const url = try std.fmt.bufPrint(&url_buf, \"{{s}}/fixtures/{fixture_id}\", .{{if (std.c.getenv(\"MOCK_SERVER_URL\")) |v| std.mem.span(v) else \"http://localhost:8080\"}});"
343 );
344
345 if !ctx.headers.is_empty() {
347 let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
348 header_pairs.sort_by_key(|(k, _)| k.as_str());
349 let _ = writeln!(out, " const headers = [_]std.http.Header{{");
350 for (k, v) in &header_pairs {
351 let ek = escape_zig(k);
352 let ev = escape_zig(v);
353 let _ = writeln!(out, " .{{ .name = \"{ek}\", .value = \"{ev}\" }},");
354 }
355 let _ = writeln!(out, " }};");
356 }
357
358 if let Some(body) = ctx.body {
360 let json_str = serde_json::to_string(body).unwrap_or_default();
361 let escaped = escape_zig(&json_str);
362 let _ = writeln!(out, " const body_bytes: []const u8 = \"{escaped}\";");
363 }
364
365 let headers_arg = if ctx.headers.is_empty() { "&.{}" } else { "&headers" };
366 let has_body = ctx.body.is_some();
367
368 let _ = writeln!(
369 out,
370 " var http_client = std.http.Client{{ .allocator = allocator }};"
371 );
372 let _ = writeln!(out, " defer http_client.deinit();");
373 let _ = writeln!(out, " var response_body = std.ArrayList(u8).init(allocator);");
374 let _ = writeln!(out, " defer response_body.deinit();");
375
376 let method_zig = match method.as_str() {
377 "GET" => ".GET",
378 "POST" => ".POST",
379 "PUT" => ".PUT",
380 "DELETE" => ".DELETE",
381 "PATCH" => ".PATCH",
382 "HEAD" => ".HEAD",
383 "OPTIONS" => ".OPTIONS",
384 _ => ".GET",
385 };
386
387 let payload_field = if has_body { ", .payload = body_bytes" } else { "" };
388 let _ = writeln!(
389 out,
390 " const {rv} = try http_client.fetch(.{{ .location = .{{ .url = url }}, .method = {method_zig}, .extra_headers = {headers_arg}{payload_field}, .response_storage = .{{ .dynamic = &response_body }} }});",
391 rv = ctx.response_var,
392 );
393 }
394
395 fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
396 let _ = writeln!(
397 out,
398 " try testing.expectEqual(@as(u10, {status}), @intFromEnum({response_var}.status));"
399 );
400 }
401
402 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
403 let ename = escape_zig(&name.to_lowercase());
404 match expected {
405 "<<present>>" => {
406 let _ = writeln!(
407 out,
408 " // assert header '{ename}' is present (header inspection not yet implemented)"
409 );
410 }
411 "<<absent>>" => {
412 let _ = writeln!(
413 out,
414 " // assert header '{ename}' is absent (header inspection not yet implemented)"
415 );
416 }
417 "<<uuid>>" => {
418 let _ = writeln!(
419 out,
420 " // assert header '{ename}' matches UUID pattern (header inspection not yet implemented)"
421 );
422 }
423 exact => {
424 let evalue = escape_zig(exact);
425 let _ = writeln!(
426 out,
427 " // assert header '{ename}' == \"{evalue}\" (header inspection not yet implemented)"
428 );
429 }
430 }
431 }
432
433 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
434 let json_str = serde_json::to_string(expected).unwrap_or_default();
435 let escaped = escape_zig(&json_str);
436 let _ = writeln!(
437 out,
438 " try testing.expectEqualStrings(\"{escaped}\", response_body.items);"
439 );
440 }
441
442 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
443 if let Some(obj) = expected.as_object() {
444 for (key, val) in obj {
445 let ekey = escape_zig(key);
446 let eval = escape_zig(&serde_json::to_string(val).unwrap_or_default());
447 let _ = writeln!(
448 out,
449 " // assert body contains field \"{ekey}\" = \"{eval}\" (partial JSON not yet implemented)"
450 );
451 }
452 }
453 }
454
455 fn render_assert_validation_errors(
456 &self,
457 out: &mut String,
458 _response_var: &str,
459 errors: &[crate::fixture::ValidationErrorExpectation],
460 ) {
461 for ve in errors {
462 let loc = ve.loc.join(".");
463 let escaped_loc = escape_zig(&loc);
464 let escaped_msg = escape_zig(&ve.msg);
465 let _ = writeln!(
466 out,
467 " // assert validation error at \"{escaped_loc}\": \"{escaped_msg}\" (not yet implemented)"
468 );
469 }
470 }
471}
472
473fn render_http_test_case(out: &mut String, fixture: &Fixture) {
478 client::http_call::render_http_test(out, &ZigTestClientRenderer, fixture);
479}
480
481#[allow(clippy::too_many_arguments)]
486fn render_test_file(
487 category: &str,
488 fixtures: &[&Fixture],
489 e2e_config: &E2eConfig,
490 function_name: &str,
491 result_var: &str,
492 args: &[crate::config::ArgMapping],
493 field_resolver: &FieldResolver,
494 enum_fields: &HashSet<String>,
495 module_name: &str,
496) -> String {
497 let mut out = String::new();
498 out.push_str(&hash::header(CommentStyle::DoubleSlash));
499 let _ = writeln!(out, "const std = @import(\"std\");");
500 let _ = writeln!(out, "const testing = std.testing;");
501 let _ = writeln!(out, "const {module_name} = @import(\"{module_name}\");");
502 let _ = writeln!(out);
503
504 let _ = writeln!(out, "// E2e tests for category: {category}");
505 let _ = writeln!(out);
506
507 for fixture in fixtures {
508 if fixture.http.is_some() {
509 render_http_test_case(&mut out, fixture);
510 } else {
511 render_test_fn(
512 &mut out,
513 fixture,
514 e2e_config,
515 function_name,
516 result_var,
517 args,
518 field_resolver,
519 enum_fields,
520 module_name,
521 );
522 }
523 let _ = writeln!(out);
524 }
525
526 out
527}
528
529#[allow(clippy::too_many_arguments)]
530fn render_test_fn(
531 out: &mut String,
532 fixture: &Fixture,
533 e2e_config: &E2eConfig,
534 _function_name: &str,
535 _result_var: &str,
536 _args: &[crate::config::ArgMapping],
537 field_resolver: &FieldResolver,
538 enum_fields: &HashSet<String>,
539 module_name: &str,
540) {
541 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
543 let lang = "zig";
544 let call_overrides = call_config.overrides.get(lang);
545 let function_name = call_overrides
546 .and_then(|o| o.function.as_ref())
547 .cloned()
548 .unwrap_or_else(|| call_config.function.clone());
549 let result_var = &call_config.result_var;
550 let args = &call_config.args;
551 let client_factory = call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
556 e2e_config
557 .call
558 .overrides
559 .get(lang)
560 .and_then(|o| o.client_factory.as_deref())
561 });
562
563 let call_result_is_bytes = call_config.result_is_bytes || call_config.overrides.values().any(|o| o.result_is_bytes);
580 let result_is_json_struct =
581 !call_result_is_bytes && (call_overrides.is_some_and(|o| o.result_is_json_struct) || client_factory.is_some());
582
583 let result_is_option = call_overrides.is_some_and(|o| o.result_is_option) || call_config.result_is_option;
588
589 let test_name = fixture.id.to_snake_case();
590 let description = &fixture.description;
591 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
592
593 let (setup_lines, args_str, setup_needs_gpa) = build_args_and_setup(&fixture.input, args, &fixture.id, module_name);
594 let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
600 let args_str = if extra_args.is_empty() {
601 args_str
602 } else if args_str.is_empty() {
603 extra_args.join(", ")
604 } else {
605 format!("{args_str}, {}", extra_args.join(", "))
606 };
607
608 let any_happy_emits_code = fixture
611 .assertions
612 .iter()
613 .any(|a| assertion_emits_code(a, field_resolver));
614 let any_non_error_emits_code = fixture
615 .assertions
616 .iter()
617 .filter(|a| a.assertion_type != "error")
618 .any(|a| assertion_emits_code(a, field_resolver));
619
620 let has_streaming_virtual_assertions = fixture.assertions.iter().any(|a| {
622 a.field
623 .as_ref()
624 .is_some_and(|f| !f.is_empty() && is_streaming_virtual_field(f))
625 });
626 let is_stream_fn = function_name.contains("stream");
627 let uses_streaming_virtual_path =
628 result_is_json_struct && has_streaming_virtual_assertions && is_stream_fn && client_factory.is_some();
629 let streaming_path_has_non_streaming = uses_streaming_virtual_path
631 && fixture.assertions.iter().any(|a| {
632 !a.field
633 .as_ref()
634 .is_some_and(|f| !f.is_empty() && is_streaming_virtual_field(f))
635 && !matches!(a.assertion_type.as_str(), "not_error" | "error")
636 && a.field
637 .as_ref()
638 .is_some_and(|f| !f.is_empty() && field_resolver.is_valid_for_result(f))
639 });
640
641 let _ = writeln!(out, "test \"{test_name}\" {{");
642 let _ = writeln!(out, " // {description}");
643
644 let needs_gpa = setup_needs_gpa
652 || streaming_path_has_non_streaming
653 || (!uses_streaming_virtual_path && result_is_json_struct && !expects_error && any_happy_emits_code)
654 || (!uses_streaming_virtual_path && result_is_json_struct && expects_error && any_non_error_emits_code);
655 if needs_gpa {
656 let _ = writeln!(out, " var gpa: std.heap.DebugAllocator(.{{}}) = .init;");
657 let _ = writeln!(out, " defer _ = gpa.deinit();");
658 let _ = writeln!(out, " const allocator = gpa.allocator();");
659 let _ = writeln!(out);
660 }
661
662 for line in &setup_lines {
663 let _ = writeln!(out, " {line}");
664 }
665
666 let call_prefix = if let Some(factory) = client_factory {
671 let fixture_id = &fixture.id;
672 let _ = writeln!(
673 out,
674 " const _mock_url = try std.fmt.allocPrintSentinel(std.heap.c_allocator, \"{{s}}/fixtures/{fixture_id}\", .{{if (std.c.getenv(\"MOCK_SERVER_URL\")) |v| std.mem.span(v) else \"http://localhost:8080\"}}, 0);"
675 );
676 let _ = writeln!(out, " defer std.heap.c_allocator.free(_mock_url);");
677 let _ = writeln!(
678 out,
679 " var _client = try {module_name}.{factory}(\"test-key\", _mock_url, null, null, null);"
680 );
681 let _ = writeln!(out, " defer _client.free();");
682 "_client".to_string()
683 } else {
684 module_name.to_string()
685 };
686
687 if expects_error {
688 if result_is_json_struct {
692 let _ = writeln!(
693 out,
694 " const _result_json = {call_prefix}.{function_name}({args_str}) catch {{"
695 );
696 } else {
697 let _ = writeln!(
698 out,
699 " const result = {call_prefix}.{function_name}({args_str}) catch {{"
700 );
701 }
702 let _ = writeln!(out, " try testing.expect(true); // Error occurred as expected");
703 let _ = writeln!(out, " return;");
704 let _ = writeln!(out, " }};");
705 let any_emits_code = fixture
709 .assertions
710 .iter()
711 .filter(|a| a.assertion_type != "error")
712 .any(|a| assertion_emits_code(a, field_resolver));
713 if result_is_json_struct && any_emits_code {
714 let _ = writeln!(out, " defer std.heap.c_allocator.free(_result_json);");
715 let _ = writeln!(
716 out,
717 " var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
718 );
719 let _ = writeln!(out, " defer _parsed.deinit();");
720 let _ = writeln!(out, " const {result_var} = &_parsed.value;");
721 let _ = writeln!(out, " // Perform success assertions if any");
722 for assertion in &fixture.assertions {
723 if assertion.assertion_type != "error" {
724 render_json_assertion(out, assertion, result_var, field_resolver);
725 }
726 }
727 } else if result_is_json_struct {
728 let _ = writeln!(out, " _ = _result_json;");
729 } else if any_emits_code {
730 let _ = writeln!(out, " // Perform success assertions if any");
731 for assertion in &fixture.assertions {
732 if assertion.assertion_type != "error" {
733 render_assertion(
734 out,
735 assertion,
736 result_var,
737 field_resolver,
738 enum_fields,
739 result_is_option,
740 );
741 }
742 }
743 } else {
744 let _ = writeln!(out, " _ = result;");
745 }
746 } else if fixture.assertions.is_empty() {
747 if result_is_json_struct {
749 let _ = writeln!(
750 out,
751 " const _result_json = try {call_prefix}.{function_name}({args_str});"
752 );
753 let _ = writeln!(out, " defer std.heap.c_allocator.free(_result_json);");
754 } else {
755 let _ = writeln!(out, " _ = try {call_prefix}.{function_name}({args_str});");
756 }
757 } else {
758 let any_emits_code = fixture
762 .assertions
763 .iter()
764 .any(|a| assertion_emits_code(a, field_resolver));
765 if call_result_is_bytes && client_factory.is_some() {
766 let _ = writeln!(
769 out,
770 " const _result_json = try {call_prefix}.{function_name}({args_str});"
771 );
772 let _ = writeln!(out, " defer std.heap.c_allocator.free(_result_json);");
773 let has_bytes_assertions = fixture
774 .assertions
775 .iter()
776 .any(|a| matches!(a.assertion_type.as_str(), "not_empty" | "is_empty"));
777 if has_bytes_assertions {
778 for assertion in &fixture.assertions {
779 match assertion.assertion_type.as_str() {
780 "not_empty" => {
781 let _ = writeln!(out, " try testing.expect(_result_json.len > 0);");
782 }
783 "is_empty" => {
784 let _ = writeln!(out, " try testing.expectEqual(@as(usize, 0), _result_json.len);");
785 }
786 "not_error" | "error" => {}
787 _ => {
788 let atype = &assertion.assertion_type;
789 let _ = writeln!(
790 out,
791 " // bytes result: assertion '{atype}' not implemented for zig bytes"
792 );
793 }
794 }
795 }
796 }
797 } else if result_is_json_struct {
798 if uses_streaming_virtual_path {
802 let _ = writeln!(
805 out,
806 " const _req_z = try std.heap.c_allocator.dupeZ(u8, {args_str});"
807 );
808 let _ = writeln!(out, " defer std.heap.c_allocator.free(_req_z);");
809 let _ = writeln!(
810 out,
811 " const _req_handle = {module_name}.c.literllm_chat_completion_request_from_json(_req_z.ptr);"
812 );
813 let _ = writeln!(
814 out,
815 " defer {module_name}.c.literllm_chat_completion_request_free(_req_handle);"
816 );
817 let _ = writeln!(
818 out,
819 " const _stream_handle = {module_name}.c.literllm_default_client_chat_stream_start(@as(*{module_name}.c.LITERLLMDefaultClient, @ptrCast(_client._handle)), _req_handle);"
820 );
821 let _ = writeln!(out, " if (_stream_handle == null) return error.StreamStartFailed;");
822 let _ = writeln!(
823 out,
824 " defer {module_name}.c.literllm_default_client_chat_stream_free(_stream_handle);"
825 );
826 if let Some(snip) = StreamingFieldResolver::collect_snippet("zig", "_stream_handle", "chunks") {
828 out.push_str(" ");
829 out.push_str(&snip);
830 out.push('\n');
831 }
832 if streaming_path_has_non_streaming {
835 let _ = writeln!(
836 out,
837 " const _result_json = if (chunks.items.len > 0) chunks.items[chunks.items.len - 1] else &[_]u8{{}};"
838 );
839 let _ = writeln!(
840 out,
841 " var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
842 );
843 let _ = writeln!(out, " defer _parsed.deinit();");
844 let _ = writeln!(out, " const {result_var} = &_parsed.value;");
845 }
846 for assertion in &fixture.assertions {
847 render_json_assertion(out, assertion, result_var, field_resolver);
848 }
849 } else {
850 let _ = writeln!(
852 out,
853 " const _result_json = try {call_prefix}.{function_name}({args_str});"
854 );
855 let _ = writeln!(out, " defer std.heap.c_allocator.free(_result_json);");
856 if any_emits_code {
857 let _ = writeln!(
858 out,
859 " var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
860 );
861 let _ = writeln!(out, " defer _parsed.deinit();");
862 let _ = writeln!(out, " const {result_var} = &_parsed.value;");
863 for assertion in &fixture.assertions {
864 render_json_assertion(out, assertion, result_var, field_resolver);
865 }
866 }
867 }
868 } else if any_emits_code {
869 let _ = writeln!(
870 out,
871 " const {result_var} = try {call_prefix}.{function_name}({args_str});"
872 );
873 for assertion in &fixture.assertions {
874 render_assertion(
875 out,
876 assertion,
877 result_var,
878 field_resolver,
879 enum_fields,
880 result_is_option,
881 );
882 }
883 } else {
884 let _ = writeln!(out, " _ = try {call_prefix}.{function_name}({args_str});");
885 }
886 }
887
888 let _ = writeln!(out, "}}");
889}
890
891const FORMAT_METADATA_VARIANTS: &[&str] = &[
909 "pdf",
910 "docx",
911 "excel",
912 "email",
913 "pptx",
914 "archive",
915 "image",
916 "xml",
917 "text",
918 "html",
919 "ocr",
920 "csv",
921 "bibtex",
922 "citation",
923 "fiction_book",
924 "dbf",
925 "jats",
926 "epub",
927 "pst",
928 "code",
929];
930
931fn json_path_expr(result_var: &str, field_path: &str) -> String {
932 let segments: Vec<&str> = field_path.split('.').collect();
933 let mut expr = result_var.to_string();
934 let mut prev_seg: Option<&str> = None;
935 for seg in &segments {
936 if prev_seg == Some("format") && FORMAT_METADATA_VARIANTS.contains(seg) {
941 prev_seg = Some(seg);
942 continue;
943 }
944 if let Some(key) = seg.strip_suffix("[]") {
948 expr = format!("{expr}.object.get(\"{key}\").?.array.items[0]");
949 } else if let Some(bracket_pos) = seg.find('[') {
950 if let Some(end_pos) = seg.find(']') {
951 if end_pos > bracket_pos + 1 && end_pos == seg.len() - 1 {
952 let key = &seg[..bracket_pos];
953 let idx = &seg[bracket_pos + 1..end_pos];
954 if idx.chars().all(|c| c.is_ascii_digit()) {
955 expr = format!("{expr}.object.get(\"{key}\").?.array.items[{idx}]");
956 prev_seg = Some(seg);
957 continue;
958 }
959 }
960 }
961 expr = format!("{expr}.object.get(\"{seg}\").?");
962 } else {
963 expr = format!("{expr}.object.get(\"{seg}\").?");
964 }
965 prev_seg = Some(seg);
966 }
967 expr
968}
969
970fn render_json_assertion(out: &mut String, assertion: &Assertion, result_var: &str, field_resolver: &FieldResolver) {
975 if let Some(f) = &assertion.field {
977 if !f.is_empty() && is_streaming_virtual_field(f) {
978 if let Some(expr) = StreamingFieldResolver::accessor(f, "zig", "chunks") {
979 match assertion.assertion_type.as_str() {
980 "count_min" => {
981 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
982 let _ = writeln!(out, " try testing.expect({expr}.len >= {n});");
983 }
984 }
985 "count_equals" => {
986 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
987 let _ = writeln!(out, " try testing.expectEqual(@as(usize, {n}), {expr}.len);");
988 }
989 }
990 "equals" => {
991 if let Some(serde_json::Value::String(s)) = &assertion.value {
992 let escaped = escape_zig(s);
993 let _ = writeln!(out, " try testing.expectEqualStrings(\"{escaped}\", {expr});");
994 } else if let Some(v) = &assertion.value {
995 let zig_val = json_to_zig(v);
996 let _ = writeln!(out, " try testing.expectEqual({zig_val}, {expr});");
997 }
998 }
999 "not_empty" => {
1000 let _ = writeln!(out, " try testing.expect({expr}.len > 0);");
1001 }
1002 "is_true" => {
1003 let _ = writeln!(out, " try testing.expect({expr});");
1004 }
1005 "is_false" => {
1006 let _ = writeln!(out, " try testing.expect(!{expr});");
1007 }
1008 _ => {
1009 let atype = &assertion.assertion_type;
1010 let _ = writeln!(
1011 out,
1012 " // streaming virtual field '{f}' assertion '{atype}' not implemented for zig"
1013 );
1014 }
1015 }
1016 }
1017 return;
1018 }
1019 }
1020
1021 if let Some(f) = &assertion.field {
1028 if f == "embeddings" && !field_resolver.has_explicit_field("embeddings") {
1029 match assertion.assertion_type.as_str() {
1030 "count_min" => {
1031 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1032 let _ = writeln!(out, " try testing.expect({result_var}.array.items.len >= {n});");
1033 }
1034 return;
1035 }
1036 "count_equals" => {
1037 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1038 let _ = writeln!(
1039 out,
1040 " try testing.expectEqual(@as(usize, {n}), {result_var}.array.items.len);"
1041 );
1042 }
1043 return;
1044 }
1045 "not_empty" => {
1046 let _ = writeln!(out, " try testing.expect({result_var}.array.items.len > 0);");
1047 return;
1048 }
1049 "is_empty" => {
1050 let _ = writeln!(
1051 out,
1052 " try testing.expectEqual(@as(usize, 0), {result_var}.array.items.len);"
1053 );
1054 return;
1055 }
1056 _ => {}
1057 }
1058 }
1059 }
1060
1061 if let Some(f) = &assertion.field {
1063 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1064 let _ = writeln!(out, " // skipped: field '{f}' not available on result type");
1065 return;
1066 }
1067 }
1068 if matches!(assertion.assertion_type.as_str(), "not_error" | "error") {
1070 return;
1071 }
1072
1073 let raw_field_path = assertion.field.as_deref().unwrap_or("").trim();
1074 let field_path = if raw_field_path.is_empty() {
1075 raw_field_path.to_string()
1076 } else {
1077 field_resolver.resolve(raw_field_path).to_string()
1078 };
1079 let field_path = field_path.trim();
1080
1081 let (field_path_for_expr, is_length_access) = if let Some(parent) = field_path.strip_suffix(".length") {
1083 (parent, true)
1084 } else {
1085 (field_path, false)
1086 };
1087
1088 let field_expr = if field_path_for_expr.is_empty() {
1089 result_var.to_string()
1090 } else {
1091 json_path_expr(result_var, field_path_for_expr)
1092 };
1093
1094 let zig_val = match &assertion.value {
1096 Some(serde_json::Value::String(s)) => format!("\"{}\"", escape_zig(s)),
1097 _ => String::new(),
1098 };
1099 let is_string_val = matches!(&assertion.value, Some(serde_json::Value::String(_)));
1100 let is_bool_val = matches!(&assertion.value, Some(serde_json::Value::Bool(_)));
1101 let bool_val = match &assertion.value {
1102 Some(serde_json::Value::Bool(b)) if *b => "true",
1103 _ => "false",
1104 };
1105 let is_null_val = matches!(&assertion.value, Some(serde_json::Value::Null));
1106 let n = assertion.value.as_ref().map(json_to_zig).unwrap_or_default();
1107 let has_n = assertion.value.as_ref().is_some_and(|v| v.is_number() || v.is_u64());
1108 let is_float_val = matches!(&assertion.value, Some(serde_json::Value::Number(n)) if !n.is_i64() && !n.is_u64());
1113 let values_list: Vec<String> = assertion
1114 .values
1115 .as_deref()
1116 .unwrap_or_default()
1117 .iter()
1118 .filter_map(|v| {
1119 if let serde_json::Value::String(s) = v {
1120 Some(format!("\"{}\"", escape_zig(s)))
1121 } else {
1122 None
1123 }
1124 })
1125 .collect();
1126
1127 let rendered = crate::template_env::render(
1128 "zig/json_assertion.jinja",
1129 minijinja::context! {
1130 assertion_type => assertion.assertion_type.as_str(),
1131 field_expr => field_expr,
1132 is_length_access => is_length_access,
1133 zig_val => zig_val,
1134 is_string_val => is_string_val,
1135 is_bool_val => is_bool_val,
1136 bool_val => bool_val,
1137 is_null_val => is_null_val,
1138 n => n,
1139 has_n => has_n,
1140 is_float_val => is_float_val,
1141 values_list => values_list,
1142 },
1143 );
1144 out.push_str(&rendered);
1145}
1146
1147fn assertion_emits_code(assertion: &Assertion, field_resolver: &FieldResolver) -> bool {
1150 if let Some(f) = &assertion.field {
1151 if !f.is_empty() && is_streaming_virtual_field(f) {
1152 } else if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1155 return false;
1156 }
1157 }
1158 matches!(
1159 assertion.assertion_type.as_str(),
1160 "equals"
1161 | "contains"
1162 | "contains_all"
1163 | "not_contains"
1164 | "not_empty"
1165 | "is_empty"
1166 | "starts_with"
1167 | "ends_with"
1168 | "min_length"
1169 | "max_length"
1170 | "count_min"
1171 | "count_equals"
1172 | "is_true"
1173 | "is_false"
1174 | "greater_than"
1175 | "less_than"
1176 | "greater_than_or_equal"
1177 | "less_than_or_equal"
1178 | "contains_any"
1179 )
1180}
1181
1182fn build_args_and_setup(
1187 input: &serde_json::Value,
1188 args: &[crate::config::ArgMapping],
1189 fixture_id: &str,
1190 _module_name: &str,
1191) -> (Vec<String>, String, bool) {
1192 if args.is_empty() {
1193 return (Vec::new(), String::new(), false);
1194 }
1195
1196 let mut setup_lines: Vec<String> = Vec::new();
1197 let mut parts: Vec<String> = Vec::new();
1198 let mut setup_needs_gpa = false;
1199
1200 for arg in args {
1201 if arg.arg_type == "mock_url" {
1202 let name = arg.name.clone();
1203 let id_upper = fixture_id.to_uppercase();
1204 setup_lines.push(format!(
1205 "const {name} = if (std.c.getenv(\"MOCK_SERVER_{id_upper}\")) |_pf| try std.fmt.allocPrint(allocator, \"{{s}}\", .{{std.mem.span(_pf)}}) else try std.fmt.allocPrint(allocator, \"{{s}}/fixtures/{fixture_id}\", .{{if (std.c.getenv(\"MOCK_SERVER_URL\")) |v| std.mem.span(v) else \"http://localhost:8080\"}});"
1206 ));
1207 setup_lines.push(format!("defer allocator.free({name});"));
1208 parts.push(name);
1209 setup_needs_gpa = true;
1210 continue;
1211 }
1212
1213 if arg.arg_type == "handle" {
1216 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1217 let json_str = match input.get(field) {
1218 Some(serde_json::Value::Null) | None => "null".to_string(),
1219 Some(v) => format!("\"{}\"", escape_zig(&serde_json::to_string(v).unwrap_or_default())),
1220 };
1221 parts.push(json_str);
1222 continue;
1223 }
1224
1225 if arg.name == "config" && arg.arg_type == "json_object" {
1232 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1233 let json_str = match input.get(field) {
1234 Some(serde_json::Value::Null) | None => "{}".to_string(),
1235 Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1236 };
1237 parts.push(format!("\"{}\"", escape_zig(&json_str)));
1238 continue;
1239 }
1240
1241 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1242 let val = if field.is_empty() || field == "input" {
1248 Some(input)
1249 } else {
1250 input.get(field)
1251 };
1252 match val {
1253 None | Some(serde_json::Value::Null) if arg.optional => {
1254 parts.push("null".to_string());
1257 }
1258 None | Some(serde_json::Value::Null) => {
1259 let default_val = match arg.arg_type.as_str() {
1260 "string" => "\"\"".to_string(),
1261 "int" | "integer" => "0".to_string(),
1262 "float" | "number" => "0.0".to_string(),
1263 "bool" | "boolean" => "false".to_string(),
1264 "json_object" => "\"{}\"".to_string(),
1265 _ => "null".to_string(),
1266 };
1267 parts.push(default_val);
1268 }
1269 Some(v) => {
1270 if arg.arg_type == "json_object" {
1275 let json_str = serde_json::to_string(v).unwrap_or_default();
1276 parts.push(format!("\"{}\"", escape_zig(&json_str)));
1277 } else if arg.arg_type == "bytes" {
1278 if let serde_json::Value::String(path) = v {
1283 let var_name = format!("{}_bytes", arg.name);
1284 let epath = escape_zig(path);
1285 setup_lines.push(format!(
1286 "const {var_name} = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, \"{epath}\", std.heap.c_allocator, .unlimited);"
1287 ));
1288 setup_lines.push(format!("defer std.heap.c_allocator.free({var_name});"));
1289 parts.push(var_name);
1290 } else {
1291 parts.push(json_to_zig(v));
1292 }
1293 } else {
1294 parts.push(json_to_zig(v));
1295 }
1296 }
1297 }
1298 }
1299
1300 (setup_lines, parts.join(", "), setup_needs_gpa)
1301}
1302
1303fn render_assertion(
1304 out: &mut String,
1305 assertion: &Assertion,
1306 result_var: &str,
1307 field_resolver: &FieldResolver,
1308 enum_fields: &HashSet<String>,
1309 result_is_option: bool,
1310) {
1311 let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1314 if bare_result_is_option {
1315 match assertion.assertion_type.as_str() {
1316 "is_empty" => {
1317 let _ = writeln!(out, " try testing.expect({result_var} == null);");
1318 return;
1319 }
1320 "not_empty" | "not_error" => {
1321 let _ = writeln!(out, " try testing.expect({result_var} != null);");
1322 return;
1323 }
1324 _ => {}
1325 }
1326 }
1327 if let Some(f) = &assertion.field {
1331 if f == "embeddings" && !field_resolver.is_valid_for_result(f) {
1332 match assertion.assertion_type.as_str() {
1333 "count_min" | "count_equals" | "not_empty" | "is_empty" => {
1334 let _ = writeln!(out, " {{");
1335 let _ = writeln!(
1336 out,
1337 " var _eparse = try std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {result_var}, .{{}});"
1338 );
1339 let _ = writeln!(out, " defer _eparse.deinit();");
1340 let _ = writeln!(out, " const _embeddings_len = _eparse.value.array.items.len;");
1341 match assertion.assertion_type.as_str() {
1342 "count_min" => {
1343 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1344 let _ = writeln!(out, " try testing.expect(_embeddings_len >= {n});");
1345 }
1346 }
1347 "count_equals" => {
1348 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1349 let _ = writeln!(
1350 out,
1351 " try testing.expectEqual(@as(usize, {n}), _embeddings_len);"
1352 );
1353 }
1354 }
1355 "not_empty" => {
1356 let _ = writeln!(out, " try testing.expect(_embeddings_len > 0);");
1357 }
1358 "is_empty" => {
1359 let _ = writeln!(out, " try testing.expectEqual(@as(usize, 0), _embeddings_len);");
1360 }
1361 _ => {}
1362 }
1363 let _ = writeln!(out, " }}");
1364 return;
1365 }
1366 _ => {}
1367 }
1368 }
1369 }
1370
1371 if let Some(f) = &assertion.field {
1373 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1374 let _ = writeln!(out, " // skipped: field '{{f}}' not available on result type");
1375 return;
1376 }
1377 }
1378
1379 let _field_is_enum = assertion
1381 .field
1382 .as_deref()
1383 .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1384
1385 let field_expr = match &assertion.field {
1386 Some(f) if !f.is_empty() => field_resolver.accessor(f, "zig", result_var),
1387 _ => result_var.to_string(),
1388 };
1389
1390 match assertion.assertion_type.as_str() {
1391 "equals" => {
1392 if let Some(expected) = &assertion.value {
1393 let zig_val = json_to_zig(expected);
1394 let _ = writeln!(out, " try testing.expectEqual({zig_val}, {field_expr});");
1395 }
1396 }
1397 "contains" => {
1398 if let Some(expected) = &assertion.value {
1399 let zig_val = json_to_zig(expected);
1400 let _ = writeln!(
1401 out,
1402 " try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) != null);"
1403 );
1404 }
1405 }
1406 "contains_all" => {
1407 if let Some(values) = &assertion.values {
1408 for val in values {
1409 let zig_val = json_to_zig(val);
1410 let _ = writeln!(
1411 out,
1412 " try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) != null);"
1413 );
1414 }
1415 }
1416 }
1417 "not_contains" => {
1418 if let Some(expected) = &assertion.value {
1419 let zig_val = json_to_zig(expected);
1420 let _ = writeln!(
1421 out,
1422 " try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) == null);"
1423 );
1424 }
1425 }
1426 "not_empty" => {
1427 let _ = writeln!(out, " try testing.expect({field_expr}.len > 0);");
1428 }
1429 "is_empty" => {
1430 let _ = writeln!(out, " try testing.expect({field_expr}.len == 0);");
1431 }
1432 "starts_with" => {
1433 if let Some(expected) = &assertion.value {
1434 let zig_val = json_to_zig(expected);
1435 let _ = writeln!(
1436 out,
1437 " try testing.expect(std.mem.startsWith(u8, {field_expr}, {zig_val}));"
1438 );
1439 }
1440 }
1441 "ends_with" => {
1442 if let Some(expected) = &assertion.value {
1443 let zig_val = json_to_zig(expected);
1444 let _ = writeln!(
1445 out,
1446 " try testing.expect(std.mem.endsWith(u8, {field_expr}, {zig_val}));"
1447 );
1448 }
1449 }
1450 "min_length" => {
1451 if let Some(val) = &assertion.value {
1452 if let Some(n) = val.as_u64() {
1453 let _ = writeln!(out, " try testing.expect({field_expr}.len >= {n});");
1454 }
1455 }
1456 }
1457 "max_length" => {
1458 if let Some(val) = &assertion.value {
1459 if let Some(n) = val.as_u64() {
1460 let _ = writeln!(out, " try testing.expect({field_expr}.len <= {n});");
1461 }
1462 }
1463 }
1464 "count_min" => {
1465 if let Some(val) = &assertion.value {
1466 if let Some(n) = val.as_u64() {
1467 let _ = writeln!(out, " try testing.expect({field_expr}.len >= {n});");
1468 }
1469 }
1470 }
1471 "count_equals" => {
1472 if let Some(val) = &assertion.value {
1473 if let Some(n) = val.as_u64() {
1474 let has_field = assertion.field.as_deref().is_some_and(|f| !f.is_empty());
1478 if has_field {
1479 let _ = writeln!(out, " try testing.expectEqual({n}, {field_expr}.len);");
1480 } else {
1481 let _ = writeln!(out, " {{");
1482 let _ = writeln!(
1483 out,
1484 " var _cparse = try std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {field_expr}, .{{}});"
1485 );
1486 let _ = writeln!(out, " defer _cparse.deinit();");
1487 let _ = writeln!(
1488 out,
1489 " try testing.expectEqual({n}, _cparse.value.array.items.len);"
1490 );
1491 let _ = writeln!(out, " }}");
1492 }
1493 }
1494 }
1495 }
1496 "is_true" => {
1497 let _ = writeln!(out, " try testing.expect({field_expr});");
1498 }
1499 "is_false" => {
1500 let _ = writeln!(out, " try testing.expect(!{field_expr});");
1501 }
1502 "not_error" => {
1503 }
1505 "error" => {
1506 }
1508 "greater_than" => {
1509 if let Some(val) = &assertion.value {
1510 let zig_val = json_to_zig(val);
1511 let _ = writeln!(out, " try testing.expect({field_expr} > {zig_val});");
1512 }
1513 }
1514 "less_than" => {
1515 if let Some(val) = &assertion.value {
1516 let zig_val = json_to_zig(val);
1517 let _ = writeln!(out, " try testing.expect({field_expr} < {zig_val});");
1518 }
1519 }
1520 "greater_than_or_equal" => {
1521 if let Some(val) = &assertion.value {
1522 let zig_val = json_to_zig(val);
1523 let _ = writeln!(out, " try testing.expect({field_expr} >= {zig_val});");
1524 }
1525 }
1526 "less_than_or_equal" => {
1527 if let Some(val) = &assertion.value {
1528 let zig_val = json_to_zig(val);
1529 let _ = writeln!(out, " try testing.expect({field_expr} <= {zig_val});");
1530 }
1531 }
1532 "contains_any" => {
1533 if let Some(values) = &assertion.values {
1535 let string_values: Vec<String> = values
1536 .iter()
1537 .filter_map(|v| {
1538 if let serde_json::Value::String(s) = v {
1539 Some(format!(
1540 "std.mem.indexOf(u8, {field_expr}, \"{}\") != null",
1541 escape_zig(s)
1542 ))
1543 } else {
1544 None
1545 }
1546 })
1547 .collect();
1548 if !string_values.is_empty() {
1549 let condition = string_values.join(" or\n ");
1550 let _ = writeln!(out, " try testing.expect(\n {condition}\n );");
1551 }
1552 }
1553 }
1554 "matches_regex" => {
1555 let _ = writeln!(out, " // regex match not yet implemented for Zig");
1556 }
1557 "method_result" => {
1558 let _ = writeln!(out, " // method_result assertions not yet implemented for Zig");
1559 }
1560 other => {
1561 panic!("Zig e2e generator: unsupported assertion type: {other}");
1562 }
1563 }
1564}
1565
1566fn json_to_zig(value: &serde_json::Value) -> String {
1568 match value {
1569 serde_json::Value::String(s) => format!("\"{}\"", escape_zig(s)),
1570 serde_json::Value::Bool(b) => b.to_string(),
1571 serde_json::Value::Number(n) => n.to_string(),
1572 serde_json::Value::Null => "null".to_string(),
1573 serde_json::Value::Array(arr) => {
1574 let items: Vec<String> = arr.iter().map(json_to_zig).collect();
1575 format!("&.{{{}}}", items.join(", "))
1576 }
1577 serde_json::Value::Object(_) => {
1578 let json_str = serde_json::to_string(value).unwrap_or_default();
1579 format!("\"{}\"", escape_zig(&json_str))
1580 }
1581 }
1582}