use super::assertions::render_json_assertion;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::Assertion;
use crate::snippets::types::{Language, Snippet, SnippetMetadata, SnippetStatus, SourceOrigin, ValidationLevel};
use crate::snippets::validators::SnippetValidator;
use crate::snippets::validators::zig::ZigValidator;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
const TOOLCHAIN_TEST_TIMEOUT_SECS: u64 = 120;
fn wrap_in_main(json_literal: &str, assertion_body: &str) -> String {
format!(
"const std = @import(\"std\");\nconst testing = std.testing;\n\npub fn main() !void {{\n \
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n defer arena.deinit();\n \
const alloc = arena.allocator();\n \
const parsed = try std.json.parseFromSlice(std.json.Value, alloc, \"{json_literal}\", .{{}});\n \
const result = parsed.value;\n{assertion_body}}}\n"
)
}
fn zig_snippet(code: String) -> Snippet {
Snippet {
id: None,
path: PathBuf::from("snippet.zig"),
language: Language::Zig,
title: None,
code,
start_line: 1,
block_index: 0,
annotation: None,
metadata: SnippetMetadata::default(),
source_origin: SourceOrigin {
path: PathBuf::from("snippet.zig"),
line: 1,
block_index: 0,
},
}
}
#[test]
fn nested_wire_optional_key_assertion_compiles_under_real_zig() {
if which::which("zig").is_err() {
return;
}
let wire_optional: HashSet<String> = ["children".to_string()].into_iter().collect();
let resolver = FieldResolver::new(
&HashMap::new(),
&HashSet::new(),
&HashSet::new(),
&HashSet::new(),
&HashSet::new(),
)
.with_wire_optional_fields(wire_optional);
let assertion = Assertion {
assertion_type: "equals".to_string(),
field: Some("data.children.count".to_string()),
value: Some(serde_json::Value::from(3)),
..Assertion::default()
};
let mut body = String::new();
render_json_assertion(&mut body, &assertion, "result", &resolver, false);
assert!(
body.contains("orelse"),
"the fixture must actually exercise the wire-optional guard. Rendered:\n{body}"
);
let code = wrap_in_main(r#"{\"data\":{\"children\":{\"count\":3}}}"#, &body);
let snippet = zig_snippet(code.clone());
let (status, output) = ZigValidator
.validate(&snippet, ValidationLevel::Compile, TOOLCHAIN_TEST_TIMEOUT_SECS)
.expect("validation runs");
assert_eq!(
status,
SnippetStatus::Pass,
"the generated wire-optional accessor chain must compile under real zig; generated \
code:\n{code}\ncompiler output:\n{output:?}"
);
}