1use crate::config::E2eConfig;
7use crate::escape::{escape_csharp, sanitize_filename, sanitize_ident};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::ResolvedCrateConfig;
12use alef_core::hash::{self, CommentStyle};
13use alef_core::template_versions as tv;
14use anyhow::Result;
15use heck::{ToLowerCamelCase, ToUpperCamelCase};
16use std::collections::HashMap;
17use std::fmt::Write as FmtWrite;
18use std::hash::{Hash, Hasher};
19use std::path::PathBuf;
20
21use super::E2eCodegen;
22use super::client;
23
24pub struct CSharpCodegen;
26
27impl E2eCodegen for CSharpCodegen {
28 fn generate(
29 &self,
30 groups: &[FixtureGroup],
31 e2e_config: &E2eConfig,
32 config: &ResolvedCrateConfig,
33 _type_defs: &[alef_core::ir::TypeDef],
34 _enums: &[alef_core::ir::EnumDef],
35 ) -> Result<Vec<GeneratedFile>> {
36 let lang = self.language_name();
37 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
38
39 let mut files = Vec::new();
40
41 let call = &e2e_config.call;
43 let overrides = call.overrides.get(lang);
44 let function_name = overrides
45 .and_then(|o| o.function.as_ref())
46 .cloned()
47 .unwrap_or_else(|| call.function.to_upper_camel_case());
48 let class_name = overrides
49 .and_then(|o| o.class.as_ref())
50 .cloned()
51 .unwrap_or_else(|| format!("{}Lib", config.name.to_upper_camel_case()));
52 let exception_class = format!("{}Exception", config.name.to_upper_camel_case());
54 let namespace = overrides
55 .and_then(|o| o.module.as_ref())
56 .cloned()
57 .or_else(|| config.csharp.as_ref().and_then(|cs| cs.namespace.clone()))
58 .unwrap_or_else(|| {
59 if call.module.is_empty() {
60 config.name.to_upper_camel_case()
61 } else {
62 call.module.to_upper_camel_case()
63 }
64 });
65 let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
66 let result_var = &call.result_var;
67 let is_async = call.r#async;
68
69 let cs_pkg = e2e_config.resolve_package("csharp");
71 let pkg_name = cs_pkg
72 .as_ref()
73 .and_then(|p| p.name.as_ref())
74 .cloned()
75 .unwrap_or_else(|| config.name.to_upper_camel_case());
76 let pkg_path = cs_pkg
78 .as_ref()
79 .and_then(|p| p.path.as_ref())
80 .cloned()
81 .unwrap_or_else(|| format!("../../packages/csharp/{pkg_name}/{pkg_name}.csproj"));
82 let pkg_version = cs_pkg
83 .as_ref()
84 .and_then(|p| p.version.as_ref())
85 .cloned()
86 .or_else(|| config.resolved_version())
87 .unwrap_or_else(|| "0.1.0".to_string());
88
89 let csproj_name = format!("{pkg_name}.E2eTests.csproj");
92 files.push(GeneratedFile {
93 path: output_base.join(&csproj_name),
94 content: render_csproj(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
95 generated_header: false,
96 });
97
98 let needs_mock_server = groups
106 .iter()
107 .flat_map(|g| g.fixtures.iter())
108 .any(|f| f.needs_mock_server());
109
110 files.push(GeneratedFile {
115 path: output_base.join("TestSetup.cs"),
116 content: render_test_setup(needs_mock_server, &e2e_config.test_documents_dir, &namespace),
117 generated_header: true,
118 });
119
120 let tests_base = output_base.join("tests");
122 let field_resolver = FieldResolver::new(
123 &e2e_config.fields,
124 &e2e_config.fields_optional,
125 &e2e_config.result_fields,
126 &e2e_config.fields_array,
127 &std::collections::HashSet::new(),
128 );
129
130 static EMPTY_ENUM_FIELDS: std::sync::LazyLock<HashMap<String, String>> = std::sync::LazyLock::new(HashMap::new);
132 let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&EMPTY_ENUM_FIELDS);
133
134 let mut effective_nested_types = default_csharp_nested_types();
136 if let Some(overrides_map) = overrides.map(|o| &o.nested_types) {
137 effective_nested_types.extend(overrides_map.clone());
138 }
139
140 for group in groups {
141 let active: Vec<&Fixture> = group
142 .fixtures
143 .iter()
144 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
145 .collect();
146
147 if active.is_empty() {
148 continue;
149 }
150
151 let test_class = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
152 let filename = format!("{test_class}.cs");
153 let content = render_test_file(
154 &group.category,
155 &active,
156 &namespace,
157 &class_name,
158 &function_name,
159 &exception_class,
160 result_var,
161 &test_class,
162 &e2e_config.call.args,
163 &field_resolver,
164 result_is_simple,
165 is_async,
166 e2e_config,
167 enum_fields,
168 &effective_nested_types,
169 &config.adapters,
170 );
171 files.push(GeneratedFile {
172 path: tests_base.join(filename),
173 content,
174 generated_header: true,
175 });
176 }
177
178 Ok(files)
179 }
180
181 fn language_name(&self) -> &'static str {
182 "csharp"
183 }
184}
185
186fn render_csproj(pkg_name: &str, pkg_path: &str, pkg_version: &str, dep_mode: crate::config::DependencyMode) -> String {
191 let pkg_ref = match dep_mode {
192 crate::config::DependencyMode::Registry => {
193 format!(" <PackageReference Include=\"{pkg_name}\" Version=\"{pkg_version}\" />")
194 }
195 crate::config::DependencyMode::Local => {
196 format!(" <ProjectReference Include=\"{pkg_path}\" />")
197 }
198 };
199 crate::template_env::render(
200 "csharp/csproj.jinja",
201 minijinja::context! {
202 pkg_ref => pkg_ref,
203 microsoft_net_test_sdk_version => tv::nuget::MICROSOFT_NET_TEST_SDK,
204 xunit_version => tv::nuget::XUNIT,
205 xunit_runner_version => tv::nuget::XUNIT_RUNNER_VISUALSTUDIO,
206 },
207 )
208}
209
210fn render_test_setup(needs_mock_server: bool, test_documents_dir: &str, namespace: &str) -> String {
211 let mut out = String::new();
212 out.push_str(&hash::header(CommentStyle::DoubleSlash));
213 out.push_str("using System;\n");
214 out.push_str("using System.IO;\n");
215 if needs_mock_server {
216 out.push_str("using System.Diagnostics;\n");
217 }
218 out.push_str("using System.Runtime.CompilerServices;\n\n");
219 let _ = writeln!(out, "namespace {namespace};\n");
220 out.push_str("internal static class TestSetup\n");
221 out.push_str("{\n");
222 if needs_mock_server {
223 out.push_str(" private static Process? _mockServer;\n\n");
224 }
225 out.push_str(" [ModuleInitializer]\n");
226 out.push_str(" internal static void Init()\n");
227 out.push_str(" {\n");
228 let _ = writeln!(
229 out,
230 " // Walk up from the assembly directory until we find the repo root."
231 );
232 let _ = writeln!(
233 out,
234 " // Prefer a sibling {test_documents_dir}/ directory (chdir into it so that"
235 );
236 out.push_str(" // fixture paths like \"docx/fake.docx\" resolve relative to it). If that\n");
237 out.push_str(" // is absent (web-crawler-style repos with no document fixtures), fall\n");
238 out.push_str(" // back to a sibling alef.toml or fixtures/ marker as the repo root.\n");
239 out.push_str(" var dir = new DirectoryInfo(AppContext.BaseDirectory);\n");
240 out.push_str(" DirectoryInfo? repoRoot = null;\n");
241 out.push_str(" while (dir != null)\n");
242 out.push_str(" {\n");
243 let _ = writeln!(
244 out,
245 " var documentsCandidate = Path.Combine(dir.FullName, \"{test_documents_dir}\");"
246 );
247 out.push_str(" if (Directory.Exists(documentsCandidate))\n");
248 out.push_str(" {\n");
249 out.push_str(" repoRoot = dir;\n");
250 out.push_str(" Directory.SetCurrentDirectory(documentsCandidate);\n");
251 out.push_str(" break;\n");
252 out.push_str(" }\n");
253 out.push_str(" if (File.Exists(Path.Combine(dir.FullName, \"alef.toml\"))\n");
254 out.push_str(" || Directory.Exists(Path.Combine(dir.FullName, \"fixtures\")))\n");
255 out.push_str(" {\n");
256 out.push_str(" repoRoot = dir;\n");
257 out.push_str(" break;\n");
258 out.push_str(" }\n");
259 out.push_str(" dir = dir.Parent;\n");
260 out.push_str(" }\n");
261 if needs_mock_server {
262 out.push('\n');
263 out.push_str(" // Spawn the mock-server binary before any test loads, mirroring the\n");
264 out.push_str(" // Ruby spec_helper / Python conftest pattern. Honors a pre-set\n");
265 out.push_str(" // MOCK_SERVER_URL (e.g. set by `task` or CI) by skipping the spawn.\n");
266 out.push_str(" // Without this, every fixture-bound test failed with\n");
267 out.push_str(" // `<Lib>Exception : builder error` because reqwest rejected the\n");
268 out.push_str(" // relative URL produced by `\"\" + \"/fixtures/<id>\"`.\n");
269 out.push_str(" var preset = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\");\n");
270 out.push_str(" if (!string.IsNullOrEmpty(preset))\n");
271 out.push_str(" {\n");
272 out.push_str(" return;\n");
273 out.push_str(" }\n");
274 out.push_str(" if (repoRoot == null)\n");
275 out.push_str(" {\n");
276 let _ = writeln!(
277 out,
278 " throw new InvalidOperationException(\"TestSetup: could not locate repo root ({test_documents_dir}/, alef.toml, or fixtures/ not found in any ancestor of \" + AppContext.BaseDirectory + \")\");"
279 );
280 out.push_str(" }\n");
281 out.push_str(" var bin = Path.Combine(\n");
282 out.push_str(" repoRoot.FullName,\n");
283 out.push_str(" \"e2e\", \"rust\", \"target\", \"release\", \"mock-server\");\n");
284 out.push_str(" if (OperatingSystem.IsWindows())\n");
285 out.push_str(" {\n");
286 out.push_str(" bin += \".exe\";\n");
287 out.push_str(" }\n");
288 out.push_str(" var fixturesDir = Path.Combine(repoRoot.FullName, \"fixtures\");\n");
289 out.push_str(" if (!File.Exists(bin))\n");
290 out.push_str(" {\n");
291 out.push_str(" throw new InvalidOperationException(\n");
292 out.push_str(" $\"TestSetup: mock-server binary not found at {bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release\");\n");
293 out.push_str(" }\n");
294 out.push_str(" var psi = new ProcessStartInfo\n");
295 out.push_str(" {\n");
296 out.push_str(" FileName = bin,\n");
297 out.push_str(" Arguments = $\"\\\"{fixturesDir}\\\"\",\n");
298 out.push_str(" RedirectStandardInput = true,\n");
299 out.push_str(" RedirectStandardOutput = true,\n");
300 out.push_str(" RedirectStandardError = true,\n");
301 out.push_str(" UseShellExecute = false,\n");
302 out.push_str(" };\n");
303 out.push_str(" _mockServer = Process.Start(psi)\n");
304 out.push_str(
305 " ?? throw new InvalidOperationException(\"TestSetup: failed to start mock-server\");\n",
306 );
307 out.push_str(" // The mock-server prints MOCK_SERVER_URL=<url>, then optionally\n");
308 out.push_str(" // MOCK_SERVERS={...} for host-root fixtures. Read up to 16 lines.\n");
309 out.push_str(" string? url = null;\n");
310 out.push_str(" for (int i = 0; i < 16; i++)\n");
311 out.push_str(" {\n");
312 out.push_str(" var line = _mockServer.StandardOutput.ReadLine();\n");
313 out.push_str(" if (line == null)\n");
314 out.push_str(" {\n");
315 out.push_str(" break;\n");
316 out.push_str(" }\n");
317 out.push_str(" const string urlPrefix = \"MOCK_SERVER_URL=\";\n");
318 out.push_str(" const string serversPrefix = \"MOCK_SERVERS=\";\n");
319 out.push_str(" if (line.StartsWith(urlPrefix, StringComparison.Ordinal))\n");
320 out.push_str(" {\n");
321 out.push_str(" url = line.Substring(urlPrefix.Length).Trim();\n");
322 out.push_str(" }\n");
323 out.push_str(" else if (line.StartsWith(serversPrefix, StringComparison.Ordinal))\n");
324 out.push_str(" {\n");
325 out.push_str(" var jsonVal = line.Substring(serversPrefix.Length).Trim();\n");
326 out.push_str(" Environment.SetEnvironmentVariable(\"MOCK_SERVERS\", jsonVal);\n");
327 out.push_str(" // Parse JSON map and set per-fixture env vars (MOCK_SERVER_<FIXTURE_ID>).\n");
328 out.push_str(" var matches = System.Text.RegularExpressions.Regex.Matches(\n");
329 out.push_str(" jsonVal, \"\\\"([^\\\"]+)\\\":\\\"([^\\\"]+)\\\"\");\n");
330 out.push_str(" foreach (System.Text.RegularExpressions.Match m in matches)\n");
331 out.push_str(" {\n");
332 out.push_str(" Environment.SetEnvironmentVariable(\n");
333 out.push_str(" \"MOCK_SERVER_\" + m.Groups[1].Value.ToUpperInvariant(),\n");
334 out.push_str(" m.Groups[2].Value);\n");
335 out.push_str(" }\n");
336 out.push_str(" break;\n");
337 out.push_str(" }\n");
338 out.push_str(" else if (url != null)\n");
339 out.push_str(" {\n");
340 out.push_str(" break;\n");
341 out.push_str(" }\n");
342 out.push_str(" }\n");
343 out.push_str(" if (string.IsNullOrEmpty(url))\n");
344 out.push_str(" {\n");
345 out.push_str(" try { _mockServer.Kill(true); } catch { }\n");
346 out.push_str(" throw new InvalidOperationException(\"TestSetup: mock-server did not emit MOCK_SERVER_URL\");\n");
347 out.push_str(" }\n");
348 out.push_str(" Environment.SetEnvironmentVariable(\"MOCK_SERVER_URL\", url);\n");
349 out.push_str(" // TCP-readiness probe: ensure axum::serve is accepting before tests start.\n");
350 out.push_str(" // The mock-server binds the TcpListener synchronously then prints the URL\n");
351 out.push_str(" // before tokio::spawn(axum::serve(...)) is polled, so under xUnit\n");
352 out.push_str(" // class-parallel default tests can race startup. Poll-connect (max 5s,\n");
353 out.push_str(" // 50ms backoff) until success.\n");
354 out.push_str(" var healthUri = new System.Uri(url);\n");
355 out.push_str(" var deadline = System.Diagnostics.Stopwatch.StartNew();\n");
356 out.push_str(" while (deadline.ElapsedMilliseconds < 5000)\n");
357 out.push_str(" {\n");
358 out.push_str(" try\n");
359 out.push_str(" {\n");
360 out.push_str(" using var probe = new System.Net.Sockets.TcpClient();\n");
361 out.push_str(" var task = probe.ConnectAsync(healthUri.Host, healthUri.Port);\n");
362 out.push_str(" if (task.Wait(100) && probe.Connected) { break; }\n");
363 out.push_str(" }\n");
364 out.push_str(" catch (System.Exception) { }\n");
365 out.push_str(" System.Threading.Thread.Sleep(50);\n");
366 out.push_str(" }\n");
367 out.push_str(" // Drain stdout/stderr so the child does not block on a full pipe.\n");
368 out.push_str(" var server = _mockServer;\n");
369 out.push_str(" var stdoutThread = new System.Threading.Thread(() =>\n");
370 out.push_str(" {\n");
371 out.push_str(" try { server.StandardOutput.ReadToEnd(); } catch { }\n");
372 out.push_str(" }) { IsBackground = true };\n");
373 out.push_str(" stdoutThread.Start();\n");
374 out.push_str(" var stderrThread = new System.Threading.Thread(() =>\n");
375 out.push_str(" {\n");
376 out.push_str(" try { server.StandardError.ReadToEnd(); } catch { }\n");
377 out.push_str(" }) { IsBackground = true };\n");
378 out.push_str(" stderrThread.Start();\n");
379 out.push_str(" // Tear the child down on assembly unload / process exit by closing\n");
380 out.push_str(" // its stdin (the mock-server treats stdin EOF as a shutdown signal).\n");
381 out.push_str(" AppDomain.CurrentDomain.ProcessExit += (_, _) =>\n");
382 out.push_str(" {\n");
383 out.push_str(" try { _mockServer.StandardInput.Close(); } catch { }\n");
384 out.push_str(" try { if (!_mockServer.WaitForExit(2000)) { _mockServer.Kill(true); } } catch { }\n");
385 out.push_str(" };\n");
386 }
387 out.push_str(" }\n");
388 out.push_str("}\n");
389 out
390}
391
392#[allow(clippy::too_many_arguments)]
393fn render_test_file(
394 category: &str,
395 fixtures: &[&Fixture],
396 namespace: &str,
397 class_name: &str,
398 function_name: &str,
399 exception_class: &str,
400 result_var: &str,
401 test_class: &str,
402 args: &[crate::config::ArgMapping],
403 field_resolver: &FieldResolver,
404 result_is_simple: bool,
405 is_async: bool,
406 e2e_config: &E2eConfig,
407 enum_fields: &HashMap<String, String>,
408 nested_types: &HashMap<String, String>,
409 adapters: &[alef_core::config::extras::AdapterConfig],
410) -> String {
411 let mut using_imports = String::new();
413 using_imports.push_str("using System;\n");
414 using_imports.push_str("using System.Collections.Generic;\n");
415 using_imports.push_str("using System.Linq;\n");
416 using_imports.push_str("using System.Net.Http;\n");
417 using_imports.push_str("using System.Text;\n");
418 using_imports.push_str("using System.Text.Json;\n");
419 using_imports.push_str("using System.Text.Json.Serialization;\n");
420 using_imports.push_str("using System.Threading.Tasks;\n");
421 using_imports.push_str("using Xunit;\n");
422 using_imports.push_str(&format!("using {namespace};\n"));
423 using_imports.push_str(&format!("using static {namespace}.{class_name};\n"));
424
425 let config_options_field = " private static readonly JsonSerializerOptions ConfigOptions = new() { Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault };";
427
428 let mut visitor_class_decls: Vec<String> = Vec::new();
432
433 let mut fixtures_body = String::new();
435 for (i, fixture) in fixtures.iter().enumerate() {
436 render_test_method(
437 &mut fixtures_body,
438 &mut visitor_class_decls,
439 fixture,
440 class_name,
441 function_name,
442 exception_class,
443 result_var,
444 args,
445 field_resolver,
446 result_is_simple,
447 is_async,
448 e2e_config,
449 enum_fields,
450 nested_types,
451 adapters,
452 );
453 if i + 1 < fixtures.len() {
454 fixtures_body.push('\n');
455 }
456 }
457
458 let mut visitor_classes_str = String::new();
460 for (i, decl) in visitor_class_decls.iter().enumerate() {
461 if i > 0 {
462 visitor_classes_str.push('\n');
463 }
464 visitor_classes_str.push('\n');
465 for line in decl.lines() {
467 visitor_classes_str.push_str(" ");
468 visitor_classes_str.push_str(line);
469 visitor_classes_str.push('\n');
470 }
471 }
472
473 let ctx = minijinja::context! {
474 header => hash::header(CommentStyle::DoubleSlash),
475 using_imports => using_imports,
476 category => category,
477 namespace => namespace,
478 test_class => test_class,
479 config_options_field => config_options_field,
480 fixtures_body => fixtures_body,
481 visitor_class_decls => visitor_classes_str,
482 };
483
484 crate::template_env::render("csharp/test_file.jinja", ctx)
485}
486
487struct CSharpTestClientRenderer;
496
497fn to_csharp_http_method(method: &str) -> String {
499 let lower = method.to_ascii_lowercase();
500 let mut chars = lower.chars();
501 match chars.next() {
502 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
503 None => String::new(),
504 }
505}
506
507const CSHARP_RESTRICTED_REQUEST_HEADERS: &[&str] = &[
511 "content-length",
512 "host",
513 "connection",
514 "expect",
515 "transfer-encoding",
516 "upgrade",
517 "content-type",
520 "content-encoding",
522 "content-language",
523 "content-location",
524 "content-md5",
525 "content-range",
526 "content-disposition",
527];
528
529fn is_csharp_content_header(name: &str) -> bool {
533 matches!(
534 name.to_ascii_lowercase().as_str(),
535 "content-type"
536 | "content-length"
537 | "content-encoding"
538 | "content-language"
539 | "content-location"
540 | "content-md5"
541 | "content-range"
542 | "content-disposition"
543 | "expires"
544 | "last-modified"
545 | "allow"
546 )
547}
548
549impl client::TestClientRenderer for CSharpTestClientRenderer {
550 fn language_name(&self) -> &'static str {
551 "csharp"
552 }
553
554 fn sanitize_test_name(&self, id: &str) -> String {
556 id.to_upper_camel_case()
557 }
558
559 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
562 let escaped_reason = skip_reason.map(escape_csharp);
563 let rendered = crate::template_env::render(
564 "csharp/http_test_open.jinja",
565 minijinja::context! {
566 fn_name => fn_name,
567 description => description,
568 skip_reason => escaped_reason,
569 },
570 );
571 out.push_str(&rendered);
572 }
573
574 fn render_test_close(&self, out: &mut String) {
576 let rendered = crate::template_env::render("csharp/http_test_close.jinja", minijinja::context! {});
577 out.push_str(&rendered);
578 }
579
580 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
585 let method = to_csharp_http_method(ctx.method);
586 let path = escape_csharp(ctx.path);
587
588 out.push_str(" var baseUrl = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? \"http://localhost:8080\";\n");
589 out.push_str(
592 " using var handler = new System.Net.Http.HttpClientHandler { AllowAutoRedirect = false };\n",
593 );
594 out.push_str(" using var client = new System.Net.Http.HttpClient(handler);\n");
595 out.push_str(&format!(" var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.{method}, $\"{{baseUrl}}{path}\");\n"));
596
597 if let Some(body) = ctx.body {
599 let content_type = ctx.content_type.unwrap_or("application/json");
600 let json_str = serde_json::to_string(body).unwrap_or_default();
601 let escaped = escape_csharp(&json_str);
602 out.push_str(&format!(" request.Content = new System.Net.Http.StringContent(\"{escaped}\", System.Text.Encoding.UTF8, \"{content_type}\");\n"));
603 }
604
605 for (name, value) in ctx.headers {
607 if CSHARP_RESTRICTED_REQUEST_HEADERS.contains(&name.to_lowercase().as_str()) {
608 continue;
609 }
610 let escaped_name = escape_csharp(name);
611 let escaped_value = escape_csharp(value);
612 out.push_str(&format!(
613 " request.Headers.Add(\"{escaped_name}\", \"{escaped_value}\");\n"
614 ));
615 }
616
617 if !ctx.cookies.is_empty() {
619 let mut pairs: Vec<String> = ctx.cookies.iter().map(|(k, v)| format!("{k}={v}")).collect();
620 pairs.sort();
621 let cookie_header = escape_csharp(&pairs.join("; "));
622 out.push_str(&format!(
623 " request.Headers.Add(\"Cookie\", \"{cookie_header}\");\n"
624 ));
625 }
626
627 out.push_str(" var response = await client.SendAsync(request);\n");
628 }
629
630 fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
632 out.push_str(&format!(" Assert.Equal({status}, (int)response.StatusCode);\n"));
633 }
634
635 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
640 let target = if is_csharp_content_header(name) {
641 "response.Content.Headers"
642 } else {
643 "response.Headers"
644 };
645 let escaped_name = escape_csharp(name);
646 match expected {
647 "<<present>>" => {
648 out.push_str(&format!(" Assert.True({target}.Contains(\"{escaped_name}\"), \"expected header {escaped_name} to be present\");\n"));
649 }
650 "<<absent>>" => {
651 out.push_str(&format!(" Assert.False({target}.Contains(\"{escaped_name}\"), \"expected header {escaped_name} to be absent\");\n"));
652 }
653 "<<uuid>>" => {
654 out.push_str(&format!(" Assert.True({target}.TryGetValues(\"{escaped_name}\", out var _uuidHdr) && System.Text.RegularExpressions.Regex.IsMatch(string.Join(\", \", _uuidHdr), @\"^[0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{12}}$\"), \"header {escaped_name} is not a UUID\");\n"));
656 }
657 literal => {
658 let var_name = format!("hdr{}", sanitize_ident(name));
661 let escaped_value = escape_csharp(literal);
662 out.push_str(&format!(" Assert.True({target}.TryGetValues(\"{escaped_name}\", out var {var_name}) && {var_name}.Any(v => v.Contains(\"{escaped_value}\")), \"header {escaped_name} mismatch\");\n"));
663 }
664 }
665 }
666
667 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
671 match expected {
672 serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
673 let json_str = serde_json::to_string(expected).unwrap_or_default();
674 let escaped = escape_csharp(&json_str);
675 out.push_str(" var bodyText = await response.Content.ReadAsStringAsync();\n");
676 out.push_str(" var body = JsonDocument.Parse(bodyText).RootElement;\n");
677 out.push_str(&format!(
678 " var expectedBody = JsonDocument.Parse(\"{escaped}\").RootElement;\n"
679 ));
680 out.push_str(" Assert.Equal(expectedBody.GetRawText(), body.GetRawText());\n");
681 }
682 serde_json::Value::String(s) => {
683 let escaped = escape_csharp(s);
684 out.push_str(" var bodyText = await response.Content.ReadAsStringAsync();\n");
685 out.push_str(&format!(" Assert.Equal(\"{escaped}\", bodyText.Trim());\n"));
686 }
687 other => {
688 let escaped = escape_csharp(&other.to_string());
689 out.push_str(" var bodyText = await response.Content.ReadAsStringAsync();\n");
690 out.push_str(&format!(" Assert.Equal(\"{escaped}\", bodyText.Trim());\n"));
691 }
692 }
693 }
694
695 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
700 if let Some(obj) = expected.as_object() {
701 out.push_str(" var partialBodyText = await response.Content.ReadAsStringAsync();\n");
702 out.push_str(" var partialBody = JsonDocument.Parse(partialBodyText).RootElement;\n");
703 for (key, val) in obj {
704 let escaped_key = escape_csharp(key);
705 let json_str = serde_json::to_string(val).unwrap_or_default();
706 let escaped_val = escape_csharp(&json_str);
707 let var_name = format!("expected{}", key.to_upper_camel_case());
708 out.push_str(&format!(
709 " var {var_name} = JsonDocument.Parse(\"{escaped_val}\").RootElement;\n"
710 ));
711 out.push_str(&format!(" Assert.True(partialBody.TryGetProperty(\"{escaped_key}\", out var _partialProp{var_name}) && _partialProp{var_name}.GetRawText() == {var_name}.GetRawText(), \"partial body field '{escaped_key}' mismatch\");\n"));
712 }
713 }
714 }
715
716 fn render_assert_validation_errors(
719 &self,
720 out: &mut String,
721 _response_var: &str,
722 errors: &[ValidationErrorExpectation],
723 ) {
724 out.push_str(" var validationBodyText = await response.Content.ReadAsStringAsync();\n");
725 for err in errors {
726 let escaped_msg = escape_csharp(&err.msg);
727 out.push_str(&format!(
728 " Assert.Contains(\"{escaped_msg}\", validationBodyText);\n"
729 ));
730 }
731 }
732}
733
734fn render_http_test_method(out: &mut String, fixture: &Fixture, _http: &HttpFixture) {
737 client::http_call::render_http_test(out, &CSharpTestClientRenderer, fixture);
738}
739
740#[allow(clippy::too_many_arguments)]
741fn render_test_method(
742 out: &mut String,
743 visitor_class_decls: &mut Vec<String>,
744 fixture: &Fixture,
745 class_name: &str,
746 _function_name: &str,
747 exception_class: &str,
748 _result_var: &str,
749 _args: &[crate::config::ArgMapping],
750 _field_resolver: &FieldResolver,
751 result_is_simple: bool,
752 _is_async: bool,
753 e2e_config: &E2eConfig,
754 enum_fields: &HashMap<String, String>,
755 nested_types: &HashMap<String, String>,
756 adapters: &[alef_core::config::extras::AdapterConfig],
757) {
758 let method_name = fixture.id.to_upper_camel_case();
759 let description = &fixture.description;
760
761 if let Some(http) = &fixture.http {
763 render_http_test_method(out, fixture, http);
764 return;
765 }
766
767 if fixture.mock_response.is_none() && !fixture_has_csharp_callable(fixture, e2e_config) {
770 let skip_reason =
771 "non-HTTP fixture: C# binding does not expose a callable for the configured `[e2e.call]` function";
772 let ctx = minijinja::context! {
773 is_skipped => true,
774 skip_reason => skip_reason,
775 description => description,
776 method_name => method_name,
777 };
778 let rendered = crate::template_env::render("csharp/test_method.jinja", ctx);
779 out.push_str(&rendered);
780 return;
781 }
782
783 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
784
785 let call_config = e2e_config.resolve_call_for_fixture(
789 fixture.call.as_deref(),
790 &fixture.id,
791 &fixture.resolved_category(),
792 &fixture.tags,
793 &fixture.input,
794 );
795 let call_field_resolver = FieldResolver::new(
801 e2e_config.effective_fields(call_config),
802 e2e_config.effective_fields_optional(call_config),
803 e2e_config.effective_result_fields(call_config),
804 e2e_config.effective_fields_array(call_config),
805 &std::collections::HashSet::new(),
806 );
807 let field_resolver = &call_field_resolver;
808 let lang = "csharp";
809 let cs_overrides = call_config.overrides.get(lang);
810
811 let raw_function_name = cs_overrides
816 .and_then(|o| o.function.as_ref())
817 .cloned()
818 .unwrap_or_else(|| call_config.function.clone());
819 if raw_function_name == "chat_stream" {
820 render_chat_stream_test_method(
821 out,
822 fixture,
823 class_name,
824 call_config,
825 cs_overrides,
826 e2e_config,
827 enum_fields,
828 nested_types,
829 exception_class,
830 adapters,
831 );
832 return;
833 }
834
835 let effective_function_name = cs_overrides.and_then(|o| o.function.as_ref()).cloned().unwrap_or_else(|| {
836 let mut name = call_config.function.to_upper_camel_case();
837 if call_config.r#async && !name.ends_with("Async") {
838 name.push_str("Async");
839 }
840 name
841 });
842 let effective_result_var = &call_config.result_var;
843 let effective_is_async = call_config.r#async;
844 let function_name = effective_function_name.as_str();
845 let result_var = effective_result_var.as_str();
846 let is_async = effective_is_async;
847 let args = call_config.args.as_slice();
848
849 let per_call_result_is_simple = call_config.result_is_simple || cs_overrides.is_some_and(|o| o.result_is_simple);
853 let per_call_result_is_bytes = call_config.result_is_bytes || cs_overrides.is_some_and(|o| o.result_is_bytes);
858 let effective_result_is_simple = result_is_simple || per_call_result_is_simple || per_call_result_is_bytes;
859 let effective_result_is_bytes = per_call_result_is_bytes;
860 let returns_void = call_config.returns_void;
861 let extra_args_slice: &[String] = cs_overrides.map_or(&[], |o| o.extra_args.as_slice());
862 let top_level_options_type = e2e_config
864 .call
865 .overrides
866 .get("csharp")
867 .and_then(|o| o.options_type.as_deref());
868 let effective_options_type = cs_overrides
869 .and_then(|o| o.options_type.as_deref())
870 .or(top_level_options_type);
871
872 let top_level_options_via = e2e_config
879 .call
880 .overrides
881 .get("csharp")
882 .and_then(|o| o.options_via.as_deref());
883 let effective_options_via = cs_overrides
884 .and_then(|o| o.options_via.as_deref())
885 .or(top_level_options_via);
886
887 let adapter_request_type_owned: Option<String> = adapters
888 .iter()
889 .find(|a| a.name == call_config.function.as_str())
890 .and_then(|a| a.request_type.as_deref())
891 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
892 let (mut setup_lines, args_str) = build_args_and_setup(
893 &fixture.input,
894 args,
895 class_name,
896 effective_options_type,
897 effective_options_via,
898 enum_fields,
899 nested_types,
900 fixture,
901 adapter_request_type_owned.as_deref(),
902 );
903
904 let mut visitor_arg = String::new();
906 let has_visitor = fixture.visitor.is_some();
907 if let Some(visitor_spec) = &fixture.visitor {
908 visitor_arg = build_csharp_visitor(&mut setup_lines, visitor_class_decls, &fixture.id, visitor_spec);
909 }
910
911 let final_args = if has_visitor && !visitor_arg.is_empty() {
915 let opts_type = effective_options_type.unwrap_or("ConversionOptions");
916 if args_str.contains("JsonSerializer.Deserialize") {
917 setup_lines.push(format!("var options = {args_str};"));
919 setup_lines.push(format!("options.Visitor = {visitor_arg};"));
920 "options".to_string()
921 } else if args_str.ends_with(", null") {
922 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
924 let trimmed = args_str[..args_str.len() - 6].to_string(); format!("{trimmed}, options")
926 } else if args_str.contains(", null,") {
927 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
929 args_str.replace(", null,", ", options,")
930 } else if args_str.is_empty() {
931 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
933 "options".to_string()
934 } else {
935 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
937 format!("{args_str}, options")
938 }
939 } else if extra_args_slice.is_empty() {
940 args_str
941 } else if args_str.is_empty() {
942 extra_args_slice.join(", ")
943 } else {
944 format!("{args_str}, {}", extra_args_slice.join(", "))
945 };
946
947 let effective_function_name = function_name.to_string();
950
951 let return_type = if is_async { "async Task" } else { "void" };
952 let await_kw = if is_async { "await " } else { "" };
953
954 let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
957 e2e_config
958 .call
959 .overrides
960 .get("csharp")
961 .and_then(|o| o.client_factory.as_deref())
962 });
963 let call_target = if client_factory.is_some() {
964 "client".to_string()
965 } else {
966 class_name.to_string()
967 };
968
969 let mut client_factory_setup = String::new();
976 if let Some(factory) = client_factory {
977 let factory_name = factory.to_upper_camel_case();
978 let fixture_id = &fixture.id;
979 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
980 let api_key_var_opt = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
981 let is_live_smoke = !has_mock && api_key_var_opt.is_some();
982 if let Some(api_key_var) = api_key_var_opt.filter(|_| has_mock) {
983 client_factory_setup.push_str(&format!(
984 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
985 ));
986 client_factory_setup.push_str(&format!(
987 " var baseUrl = string.IsNullOrEmpty(apiKey)\n ? (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\"\n : null;\n"
988 ));
989 client_factory_setup.push_str(&format!(
990 " Console.WriteLine($\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({api_key_var} is set)\" : \"using mock server ({api_key_var} not set)\"));\n"
991 ));
992 client_factory_setup.push_str(&format!(
993 " var client = {class_name}.{factory_name}(string.IsNullOrEmpty(apiKey) ? \"test-key\" : apiKey, baseUrl, null, null, null);\n"
994 ));
995 } else if let Some(api_key_var) = api_key_var_opt.filter(|_| is_live_smoke) {
996 client_factory_setup.push_str(&format!(
997 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
998 ));
999 client_factory_setup.push_str(" if (string.IsNullOrEmpty(apiKey)) { return; }\n");
1000 client_factory_setup.push_str(&format!(
1001 " var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
1002 ));
1003 } else if fixture.has_host_root_route() {
1004 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1005 client_factory_setup.push_str(&format!(
1006 " var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
1007 ));
1008 client_factory_setup.push_str(&format!(" var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1009 client_factory_setup.push_str(&format!(
1010 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1011 ));
1012 } else {
1013 client_factory_setup.push_str(&format!(" var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1014 client_factory_setup.push_str(&format!(
1015 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1016 ));
1017 }
1018 }
1019
1020 let call_expr = format!("{}({})", effective_function_name, final_args);
1022
1023 let mut effective_enum_fields: std::collections::HashSet<String> = e2e_config.fields_enum.clone();
1031 for k in enum_fields.keys() {
1032 effective_enum_fields.insert(k.clone());
1033 }
1034 if let Some(o) = cs_overrides {
1035 for k in o.enum_fields.keys() {
1036 effective_enum_fields.insert(k.clone());
1037 }
1038 }
1039
1040 let mut assertions_body = String::new();
1042 if !expects_error && !returns_void {
1043 for assertion in &fixture.assertions {
1044 render_assertion(
1045 &mut assertions_body,
1046 assertion,
1047 result_var,
1048 class_name,
1049 exception_class,
1050 field_resolver,
1051 effective_result_is_simple,
1052 call_config.result_is_vec || cs_overrides.is_some_and(|o| o.result_is_vec),
1053 call_config.result_is_array,
1054 effective_result_is_bytes,
1055 &effective_enum_fields,
1056 );
1057 }
1058 }
1059
1060 let ctx = minijinja::context! {
1061 is_skipped => false,
1062 expects_error => expects_error,
1063 description => description,
1064 return_type => return_type,
1065 method_name => method_name,
1066 async_kw => await_kw,
1067 call_target => call_target,
1068 setup_lines => setup_lines.clone(),
1069 call_expr => call_expr,
1070 exception_class => exception_class,
1071 client_factory_setup => client_factory_setup,
1072 has_usable_assertion => !expects_error && !returns_void,
1073 result_var => result_var,
1074 assertions_body => assertions_body,
1075 };
1076
1077 let rendered = crate::template_env::render("csharp/test_method.jinja", ctx);
1078 for line in rendered.lines() {
1080 out.push_str(" ");
1081 out.push_str(line);
1082 out.push('\n');
1083 }
1084}
1085
1086#[allow(clippy::too_many_arguments)]
1094fn render_chat_stream_test_method(
1095 out: &mut String,
1096 fixture: &Fixture,
1097 class_name: &str,
1098 call_config: &crate::config::CallConfig,
1099 cs_overrides: Option<&crate::config::CallOverride>,
1100 e2e_config: &E2eConfig,
1101 enum_fields: &HashMap<String, String>,
1102 nested_types: &HashMap<String, String>,
1103 exception_class: &str,
1104 adapters: &[alef_core::config::extras::AdapterConfig],
1105) {
1106 let method_name = fixture.id.to_upper_camel_case();
1107 let description = &fixture.description;
1108 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1109
1110 let effective_function_name = cs_overrides.and_then(|o| o.function.as_ref()).cloned().unwrap_or_else(|| {
1111 let mut name = call_config.function.to_upper_camel_case();
1112 if call_config.r#async && !name.ends_with("Async") {
1113 name.push_str("Async");
1114 }
1115 name
1116 });
1117 let function_name = effective_function_name.as_str();
1118 let args = call_config.args.as_slice();
1119
1120 let top_level_options_type = e2e_config
1121 .call
1122 .overrides
1123 .get("csharp")
1124 .and_then(|o| o.options_type.as_deref());
1125 let effective_options_type = cs_overrides
1126 .and_then(|o| o.options_type.as_deref())
1127 .or(top_level_options_type);
1128 let top_level_options_via = e2e_config
1129 .call
1130 .overrides
1131 .get("csharp")
1132 .and_then(|o| o.options_via.as_deref());
1133 let effective_options_via = cs_overrides
1134 .and_then(|o| o.options_via.as_deref())
1135 .or(top_level_options_via);
1136
1137 let adapter_request_type_cs: Option<String> = adapters
1138 .iter()
1139 .find(|a| a.name == call_config.function.as_str())
1140 .and_then(|a| a.request_type.as_deref())
1141 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
1142 let (setup_lines, args_str) = build_args_and_setup(
1143 &fixture.input,
1144 args,
1145 class_name,
1146 effective_options_type,
1147 effective_options_via,
1148 enum_fields,
1149 nested_types,
1150 fixture,
1151 adapter_request_type_cs.as_deref(),
1152 );
1153
1154 let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
1155 e2e_config
1156 .call
1157 .overrides
1158 .get("csharp")
1159 .and_then(|o| o.client_factory.as_deref())
1160 });
1161 let mut client_factory_setup = String::new();
1162 if let Some(factory) = client_factory {
1163 let factory_name = factory.to_upper_camel_case();
1164 let fixture_id = &fixture.id;
1165 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1166 let api_key_var_opt = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1167 let is_live_smoke = !has_mock && api_key_var_opt.is_some();
1168 if let Some(api_key_var) = api_key_var_opt.filter(|_| has_mock) {
1169 client_factory_setup.push_str(&format!(
1170 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1171 ));
1172 client_factory_setup.push_str(&format!(
1173 " var baseUrl = string.IsNullOrEmpty(apiKey)\n ? (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\"\n : null;\n"
1174 ));
1175 client_factory_setup.push_str(&format!(
1176 " Console.WriteLine($\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({api_key_var} is set)\" : \"using mock server ({api_key_var} not set)\"));\n"
1177 ));
1178 client_factory_setup.push_str(&format!(
1179 " var client = {class_name}.{factory_name}(string.IsNullOrEmpty(apiKey) ? \"test-key\" : apiKey, baseUrl, null, null, null);\n"
1180 ));
1181 } else if let Some(api_key_var) = api_key_var_opt.filter(|_| is_live_smoke) {
1182 client_factory_setup.push_str(&format!(
1183 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1184 ));
1185 client_factory_setup.push_str(" if (string.IsNullOrEmpty(apiKey)) { return; }\n");
1186 client_factory_setup.push_str(&format!(
1187 " var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
1188 ));
1189 } else if fixture.has_host_root_route() {
1190 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1191 client_factory_setup.push_str(&format!(
1192 " var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
1193 ));
1194 client_factory_setup.push_str(&format!(" var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1195 client_factory_setup.push_str(&format!(
1196 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1197 ));
1198 } else {
1199 client_factory_setup.push_str(&format!(
1200 " var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"
1201 ));
1202 client_factory_setup.push_str(&format!(
1203 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1204 ));
1205 }
1206 }
1207
1208 let call_target = if client_factory.is_some() { "client" } else { class_name };
1209 let call_expr = format!("{call_target}.{function_name}({args_str})");
1210
1211 let mut needs_finish_reason = false;
1213 let mut needs_tool_calls_json = false;
1214 let mut needs_tool_calls_0_function_name = false;
1215 let mut needs_total_tokens = false;
1216 for a in &fixture.assertions {
1217 if let Some(f) = a.field.as_deref() {
1218 match f {
1219 "finish_reason" => needs_finish_reason = true,
1220 "tool_calls" => needs_tool_calls_json = true,
1221 "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
1222 "usage.total_tokens" => needs_total_tokens = true,
1223 _ => {}
1224 }
1225 }
1226 }
1227
1228 let mut body = String::new();
1229 let _ = writeln!(body, " [Fact]");
1230 let _ = writeln!(body, " public async Task Test_{method_name}()");
1231 let _ = writeln!(body, " {{");
1232 let _ = writeln!(body, " // {description}");
1233 if !client_factory_setup.is_empty() {
1234 body.push_str(&client_factory_setup);
1235 }
1236 for line in &setup_lines {
1237 let _ = writeln!(body, " {line}");
1238 }
1239
1240 if expects_error {
1241 let _ = writeln!(
1244 body,
1245 " await Assert.ThrowsAnyAsync<{exception_class}>(async () => {{"
1246 );
1247 let _ = writeln!(body, " await foreach (var _chunk in {call_expr}) {{ }}");
1248 body.push_str(" });\n");
1249 body.push_str(" }\n");
1250 for line in body.lines() {
1251 out.push_str(" ");
1252 out.push_str(line);
1253 out.push('\n');
1254 }
1255 return;
1256 }
1257
1258 body.push_str(" var chunks = new List<ChatCompletionChunk>();\n");
1259 body.push_str(" var streamContent = new System.Text.StringBuilder();\n");
1260 body.push_str(" var streamComplete = false;\n");
1261 if needs_finish_reason {
1262 body.push_str(" string? lastFinishReason = null;\n");
1263 }
1264 if needs_tool_calls_json {
1265 body.push_str(" string? toolCallsJson = null;\n");
1266 }
1267 if needs_tool_calls_0_function_name {
1268 body.push_str(" string? toolCalls0FunctionName = null;\n");
1269 }
1270 if needs_total_tokens {
1271 body.push_str(" long? totalTokens = null;\n");
1272 }
1273 let _ = writeln!(body, " await foreach (var chunk in {call_expr})");
1274 body.push_str(" {\n");
1275 body.push_str(" chunks.Add(chunk);\n");
1276 body.push_str(
1277 " var choice = chunk.Choices != null && chunk.Choices.Count > 0 ? chunk.Choices[0] : null;\n",
1278 );
1279 body.push_str(" if (choice != null)\n");
1280 body.push_str(" {\n");
1281 body.push_str(" var delta = choice.Delta;\n");
1282 body.push_str(" if (delta != null && !string.IsNullOrEmpty(delta.Content))\n");
1283 body.push_str(" {\n");
1284 body.push_str(" streamContent.Append(delta.Content);\n");
1285 body.push_str(" }\n");
1286 if needs_finish_reason {
1287 body.push_str(" if (choice.FinishReason != null)\n");
1295 body.push_str(" {\n");
1296 body.push_str(
1297 " lastFinishReason = JsonNamingPolicy.SnakeCaseLower.ConvertName(choice.FinishReason.ToString()!);\n",
1298 );
1299 body.push_str(" }\n");
1300 }
1301 if needs_tool_calls_json || needs_tool_calls_0_function_name {
1302 body.push_str(" var tcs = delta?.ToolCalls;\n");
1303 body.push_str(" if (tcs != null && tcs.Count > 0)\n");
1304 body.push_str(" {\n");
1305 if needs_tool_calls_json {
1306 body.push_str(
1307 " toolCallsJson ??= JsonSerializer.Serialize(tcs.Select(tc => new { function = new { name = tc.Function?.Name } }));\n",
1308 );
1309 }
1310 if needs_tool_calls_0_function_name {
1311 body.push_str(" toolCalls0FunctionName ??= tcs[0].Function?.Name;\n");
1312 }
1313 body.push_str(" }\n");
1314 }
1315 body.push_str(" }\n");
1316 if needs_total_tokens {
1317 body.push_str(" if (chunk.Usage != null)\n");
1318 body.push_str(" {\n");
1319 body.push_str(" totalTokens = chunk.Usage.TotalTokens;\n");
1320 body.push_str(" }\n");
1321 }
1322 body.push_str(" }\n");
1323 body.push_str(" streamComplete = true;\n");
1324
1325 let mut had_explicit_complete = false;
1327 for assertion in &fixture.assertions {
1328 if assertion.field.as_deref() == Some("stream_complete") {
1329 had_explicit_complete = true;
1330 }
1331 emit_chat_stream_assertion(&mut body, assertion);
1332 }
1333 if !had_explicit_complete {
1334 body.push_str(" Assert.True(streamComplete);\n");
1335 }
1336
1337 body.push_str(" }\n");
1338
1339 for line in body.lines() {
1340 out.push_str(" ");
1341 out.push_str(line);
1342 out.push('\n');
1343 }
1344}
1345
1346fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion) {
1350 let atype = assertion.assertion_type.as_str();
1351 if atype == "not_error" || atype == "error" {
1352 return;
1353 }
1354 let field = assertion.field.as_deref().unwrap_or("");
1355
1356 enum Kind {
1357 Chunks,
1358 Bool,
1359 Str,
1360 IntTokens,
1361 Json,
1362 Unsupported,
1363 }
1364
1365 let (expr, kind) = match field {
1366 "chunks" => ("chunks", Kind::Chunks),
1367 "stream_content" => ("streamContent.ToString()", Kind::Str),
1368 "stream_complete" => ("streamComplete", Kind::Bool),
1369 "no_chunks_after_done" => ("streamComplete", Kind::Bool),
1370 "finish_reason" => ("lastFinishReason", Kind::Str),
1371 "tool_calls" => ("toolCallsJson", Kind::Json),
1372 "tool_calls[0].function.name" => ("toolCalls0FunctionName", Kind::Str),
1373 "usage.total_tokens" => ("totalTokens", Kind::IntTokens),
1374 _ => ("", Kind::Unsupported),
1375 };
1376
1377 if matches!(kind, Kind::Unsupported) {
1378 let _ = writeln!(
1379 out,
1380 " // skipped: streaming assertion on unsupported field '{field}'"
1381 );
1382 return;
1383 }
1384
1385 match (atype, &kind) {
1386 ("count_min", Kind::Chunks) => {
1387 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1388 let _ = writeln!(
1389 out,
1390 " Assert.True(chunks.Count >= {n}, \"expected at least {n} chunks\");"
1391 );
1392 }
1393 }
1394 ("count_equals", Kind::Chunks) => {
1395 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1396 let _ = writeln!(out, " Assert.Equal({n}, chunks.Count);");
1397 }
1398 }
1399 ("equals", Kind::Str) => {
1400 if let Some(val) = &assertion.value {
1401 let cs_val = json_to_csharp(val);
1402 let _ = writeln!(out, " Assert.Equal({cs_val}, {expr});");
1403 }
1404 }
1405 ("contains", Kind::Str) => {
1406 if let Some(val) = &assertion.value {
1407 let cs_val = json_to_csharp(val);
1408 let _ = writeln!(out, " Assert.Contains({cs_val}, {expr} ?? string.Empty);");
1409 }
1410 }
1411 ("not_empty", Kind::Str) => {
1412 let _ = writeln!(out, " Assert.False(string.IsNullOrEmpty({expr}));");
1413 }
1414 ("not_empty", Kind::Json) => {
1415 let _ = writeln!(out, " Assert.NotNull({expr});");
1416 }
1417 ("is_empty", Kind::Str) => {
1418 let _ = writeln!(out, " Assert.True(string.IsNullOrEmpty({expr}));");
1419 }
1420 ("is_true", Kind::Bool) => {
1421 let _ = writeln!(out, " Assert.True({expr});");
1422 }
1423 ("is_false", Kind::Bool) => {
1424 let _ = writeln!(out, " Assert.False({expr});");
1425 }
1426 ("greater_than_or_equal", Kind::IntTokens) => {
1427 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1428 let _ = writeln!(out, " Assert.True({expr} >= {n}, \"expected >= {n}\");");
1429 }
1430 }
1431 ("equals", Kind::IntTokens) => {
1432 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1433 let _ = writeln!(out, " Assert.Equal((long?){n}, {expr});");
1434 }
1435 }
1436 _ => {
1437 let _ = writeln!(
1438 out,
1439 " // skipped: streaming assertion '{atype}' on field '{field}' not supported"
1440 );
1441 }
1442 }
1443}
1444
1445#[allow(clippy::too_many_arguments)]
1449fn build_args_and_setup(
1450 input: &serde_json::Value,
1451 args: &[crate::config::ArgMapping],
1452 class_name: &str,
1453 options_type: Option<&str>,
1454 options_via: Option<&str>,
1455 enum_fields: &HashMap<String, String>,
1456 nested_types: &HashMap<String, String>,
1457 fixture: &crate::fixture::Fixture,
1458 adapter_request_type: Option<&str>,
1459) -> (Vec<String>, String) {
1460 let fixture_id = &fixture.id;
1461 if args.is_empty() {
1462 return (Vec::new(), String::new());
1463 }
1464
1465 let mut setup_lines: Vec<String> = Vec::new();
1466 let mut parts: Vec<String> = Vec::new();
1467
1468 for arg in args {
1469 if arg.arg_type == "bytes" {
1470 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1472 let val = input.get(field);
1473 match val {
1474 None | Some(serde_json::Value::Null) if arg.optional => {
1475 parts.push("null".to_string());
1476 }
1477 None | Some(serde_json::Value::Null) => {
1478 parts.push("System.Array.Empty<byte>()".to_string());
1479 }
1480 Some(v) => {
1481 if let Some(s) = v.as_str() {
1486 let bytes_code = classify_bytes_value_csharp(s);
1487 parts.push(bytes_code);
1488 } else {
1489 let cs_str = json_to_csharp(v);
1491 parts.push(format!("System.Text.Encoding.UTF8.GetBytes({cs_str})"));
1492 }
1493 }
1494 }
1495 continue;
1496 }
1497
1498 if arg.arg_type == "mock_url" {
1499 if fixture.has_host_root_route() {
1500 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1501 setup_lines.push(format!(
1502 "var _pfUrl_{name} = Environment.GetEnvironmentVariable(\"{env_key}\");",
1503 name = arg.name,
1504 ));
1505 setup_lines.push(format!(
1506 "var {} = !string.IsNullOrEmpty(_pfUrl_{name}) ? _pfUrl_{name} : Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1507 arg.name,
1508 name = arg.name,
1509 ));
1510 } else {
1511 setup_lines.push(format!(
1512 "var {} = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1513 arg.name,
1514 ));
1515 }
1516 if let Some(req_type) = adapter_request_type {
1517 let req_var = format!("{}Req", arg.name);
1518 setup_lines.push(format!(
1519 "var {req_var} = new {class_name}.{req_type} {{ Url = {} }};",
1520 arg.name
1521 ));
1522 parts.push(req_var);
1523 } else {
1524 parts.push(arg.name.clone());
1525 }
1526 continue;
1527 }
1528
1529 if arg.arg_type == "handle" {
1530 let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
1532 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1533 let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1534 if config_value.is_null()
1535 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1536 {
1537 setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
1538 } else {
1539 let sorted = sort_discriminator_first(config_value.clone());
1543 let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1544 let name = &arg.name;
1545 setup_lines.push(format!(
1546 "var {name}Config = JsonSerializer.Deserialize<CrawlConfig>(\"{}\", ConfigOptions)!;",
1547 escape_csharp(&json_str),
1548 ));
1549 setup_lines.push(format!(
1550 "var {} = {class_name}.{constructor_name}({name}Config);",
1551 arg.name,
1552 name = name,
1553 ));
1554 }
1555 parts.push(arg.name.clone());
1556 continue;
1557 }
1558
1559 let val: Option<&serde_json::Value> = if arg.field == "input" {
1562 Some(input)
1563 } else {
1564 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1565 input.get(field)
1566 };
1567 match val {
1568 None | Some(serde_json::Value::Null) if arg.optional => {
1569 parts.push("null".to_string());
1572 continue;
1573 }
1574 None | Some(serde_json::Value::Null) => {
1575 let default_val = match arg.arg_type.as_str() {
1579 "string" => "\"\"".to_string(),
1580 "int" | "integer" => "0".to_string(),
1581 "float" | "number" => "0.0d".to_string(),
1582 "bool" | "boolean" => "false".to_string(),
1583 "json_object" => {
1584 if let Some(opts_type) = options_type {
1585 format!("new {opts_type}()")
1586 } else {
1587 "null".to_string()
1588 }
1589 }
1590 _ => "null".to_string(),
1591 };
1592 parts.push(default_val);
1593 }
1594 Some(v) => {
1595 if arg.arg_type == "json_object" {
1596 if options_via == Some("from_json")
1602 && let Some(opts_type) = options_type
1603 {
1604 let sorted = sort_discriminator_first(v.clone());
1605 let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1606 let escaped = escape_csharp(&json_str);
1607 parts.push(format!("{opts_type}.FromJson(\"{escaped}\")",));
1613 continue;
1614 }
1615 if let Some(arr) = v.as_array() {
1617 parts.push(json_array_to_csharp_list(arr, arg.element_type.as_deref()));
1618 continue;
1619 }
1620 if let Some(opts_type) = options_type {
1622 if let Some(obj) = v.as_object() {
1623 parts.push(csharp_object_initializer(obj, opts_type, enum_fields, nested_types));
1624 continue;
1625 }
1626 }
1627 }
1628 parts.push(json_to_csharp(v));
1629 }
1630 }
1631 }
1632
1633 (setup_lines, parts.join(", "))
1634}
1635
1636fn json_array_to_csharp_list(arr: &[serde_json::Value], element_type: Option<&str>) -> String {
1644 match element_type {
1645 Some("BatchBytesItem") => {
1646 let items: Vec<String> = arr
1647 .iter()
1648 .filter_map(|v| v.as_object())
1649 .map(|obj| {
1650 let content = obj.get("content").and_then(|v| v.as_array());
1651 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1652 let content_code = if let Some(arr) = content {
1653 let bytes: Vec<String> = arr
1654 .iter()
1655 .filter_map(|v| v.as_u64().map(|n| format!("(byte){}", n)))
1656 .collect();
1657 format!("new byte[] {{ {} }}", bytes.join(", "))
1658 } else {
1659 "new byte[] { }".to_string()
1660 };
1661 format!(
1662 "new BatchBytesItem {{ Content = {}, MimeType = \"{}\" }}",
1663 content_code, mime_type
1664 )
1665 })
1666 .collect();
1667 format!("new List<BatchBytesItem>() {{ {} }}", items.join(", "))
1668 }
1669 Some("BatchFileItem") => {
1670 let items: Vec<String> = arr
1671 .iter()
1672 .filter_map(|v| v.as_object())
1673 .map(|obj| {
1674 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1675 format!("new BatchFileItem {{ Path = \"{}\" }}", path)
1676 })
1677 .collect();
1678 format!("new List<BatchFileItem>() {{ {} }}", items.join(", "))
1679 }
1680 Some("f32") => {
1681 let items: Vec<String> = arr.iter().map(|v| format!("(float){}", json_to_csharp(v))).collect();
1682 format!("new List<float>() {{ {} }}", items.join(", "))
1683 }
1684 Some("(String, String)") => {
1685 let items: Vec<String> = arr
1686 .iter()
1687 .map(|v| {
1688 let strs: Vec<String> = v
1689 .as_array()
1690 .map_or_else(Vec::new, |a| a.iter().map(json_to_csharp).collect());
1691 format!("new List<string>() {{ {} }}", strs.join(", "))
1692 })
1693 .collect();
1694 format!("new List<List<string>>() {{ {} }}", items.join(", "))
1695 }
1696 Some(et)
1697 if et != "f32"
1698 && et != "(String, String)"
1699 && et != "string"
1700 && et != "BatchBytesItem"
1701 && et != "BatchFileItem" =>
1702 {
1703 let items: Vec<String> = arr
1705 .iter()
1706 .map(|v| {
1707 let json_str = serde_json::to_string(v).unwrap_or_default();
1708 let escaped = escape_csharp(&json_str);
1709 format!("JsonSerializer.Deserialize<{et}>(\"{escaped}\", ConfigOptions)!")
1710 })
1711 .collect();
1712 format!("new List<{et}>() {{ {} }}", items.join(", "))
1713 }
1714 _ => {
1715 let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
1716 format!("new List<string>() {{ {} }}", items.join(", "))
1717 }
1718 }
1719}
1720
1721fn parse_discriminated_union_access(field: &str) -> Option<(String, String, String)> {
1725 let parts: Vec<&str> = field.split('.').collect();
1726 if parts.len() >= 3 && parts.len() <= 4 {
1727 if parts[0] == "metadata" && parts[1] == "format" {
1729 let variant_name = parts[2];
1730 let known_variants = [
1732 "pdf",
1733 "docx",
1734 "excel",
1735 "email",
1736 "pptx",
1737 "archive",
1738 "image",
1739 "xml",
1740 "text",
1741 "html",
1742 "ocr",
1743 "csv",
1744 "bibtex",
1745 "citation",
1746 "fiction_book",
1747 "dbf",
1748 "jats",
1749 "epub",
1750 "pst",
1751 "code",
1752 ];
1753 if known_variants.contains(&variant_name) {
1754 let variant_pascal = variant_name.to_upper_camel_case();
1755 if parts.len() == 4 {
1756 let inner_field = parts[3];
1757 return Some((
1758 format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1759 variant_pascal,
1760 inner_field.to_string(),
1761 ));
1762 } else if parts.len() == 3 {
1763 return Some((
1765 format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1766 variant_pascal,
1767 String::new(),
1768 ));
1769 }
1770 }
1771 }
1772 }
1773 None
1774}
1775
1776fn render_discriminated_union_assertion(
1780 out: &mut String,
1781 assertion: &Assertion,
1782 variant_var: &str,
1783 inner_field: &str,
1784 _result_is_vec: bool,
1785) {
1786 if inner_field.is_empty() {
1787 return; }
1789
1790 let field_pascal = inner_field.to_upper_camel_case();
1791 let field_expr = format!("{variant_var}.Value.{field_pascal}");
1792
1793 match assertion.assertion_type.as_str() {
1794 "equals" => {
1795 if let Some(expected) = &assertion.value {
1796 let cs_val = json_to_csharp(expected);
1797 if expected.is_string() {
1798 let _ = writeln!(out, " Assert.Equal({cs_val}, {field_expr}!.Trim());");
1799 } else if expected.as_bool() == Some(true) {
1800 let _ = writeln!(out, " Assert.True({field_expr});");
1801 } else if expected.as_bool() == Some(false) {
1802 let _ = writeln!(out, " Assert.False({field_expr});");
1803 } else if expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0) {
1804 let _ = writeln!(out, " Assert.True({field_expr} == {cs_val});");
1805 } else {
1806 let _ = writeln!(out, " Assert.Equal({cs_val}, {field_expr});");
1807 }
1808 }
1809 }
1810 "greater_than_or_equal" => {
1811 if let Some(val) = &assertion.value {
1812 let cs_val = json_to_csharp(val);
1813 let _ = writeln!(
1814 out,
1815 " Assert.True({field_expr} >= {cs_val}, \"expected >= {cs_val}\");"
1816 );
1817 }
1818 }
1819 "contains_all" => {
1820 if let Some(values) = &assertion.values {
1821 let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1822 for val in values {
1823 let lower_val = val.as_str().map(|s| s.to_lowercase());
1824 let cs_val = lower_val
1825 .as_deref()
1826 .map(|s| format!("\"{}\"", escape_csharp(s)))
1827 .unwrap_or_else(|| json_to_csharp(val));
1828 let _ = writeln!(out, " Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1829 }
1830 }
1831 }
1832 "contains" => {
1833 if let Some(expected) = &assertion.value {
1834 let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1835 let lower_expected = expected.as_str().map(|s| s.to_lowercase());
1836 let cs_val = lower_expected
1837 .as_deref()
1838 .map(|s| format!("\"{}\"", escape_csharp(s)))
1839 .unwrap_or_else(|| json_to_csharp(expected));
1840 let _ = writeln!(out, " Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1841 }
1842 }
1843 "not_empty" => {
1844 let _ = writeln!(out, " Assert.NotEmpty({field_expr});");
1845 }
1846 "is_empty" => {
1847 let _ = writeln!(out, " Assert.Empty({field_expr});");
1848 }
1849 _ => {
1850 let _ = writeln!(
1851 out,
1852 " // skipped: assertion type '{}' not yet supported for discriminated union fields",
1853 assertion.assertion_type
1854 );
1855 }
1856 }
1857}
1858
1859#[allow(clippy::too_many_arguments)]
1860fn render_assertion(
1861 out: &mut String,
1862 assertion: &Assertion,
1863 result_var: &str,
1864 class_name: &str,
1865 exception_class: &str,
1866 field_resolver: &FieldResolver,
1867 result_is_simple: bool,
1868 result_is_vec: bool,
1869 result_is_array: bool,
1870 result_is_bytes: bool,
1871 fields_enum: &std::collections::HashSet<String>,
1872) {
1873 if result_is_bytes {
1877 match assertion.assertion_type.as_str() {
1878 "not_empty" => {
1879 let _ = writeln!(out, " Assert.NotEmpty({result_var});");
1880 return;
1881 }
1882 "is_empty" => {
1883 let _ = writeln!(out, " Assert.Empty({result_var});");
1884 return;
1885 }
1886 "count_equals" | "length_equals" => {
1887 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1888 let _ = writeln!(out, " Assert.Equal({n}, {result_var}.Length);");
1889 }
1890 return;
1891 }
1892 "count_min" | "length_min" => {
1893 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1894 let _ = writeln!(out, " Assert.True({result_var}.Length >= {n});");
1895 }
1896 return;
1897 }
1898 "not_error" => {
1899 let _ = writeln!(out, " Assert.NotNull({result_var});");
1900 return;
1901 }
1902 _ => {
1903 let _ = writeln!(
1907 out,
1908 " // skipped: assertion type '{}' not supported on byte[] result",
1909 assertion.assertion_type
1910 );
1911 return;
1912 }
1913 }
1914 }
1915 if let Some(f) = &assertion.field {
1918 match f.as_str() {
1919 "chunks_have_content" => {
1920 let synthetic_pred =
1921 format!("({result_var}.Chunks ?? new()).All(c => !string.IsNullOrEmpty(c.Content))");
1922 let synthetic_pred_type = match assertion.assertion_type.as_str() {
1923 "is_true" => "is_true",
1924 "is_false" => "is_false",
1925 _ => {
1926 out.push_str(&format!(
1927 " // skipped: unsupported assertion type on synthetic field '{f}'\n"
1928 ));
1929 return;
1930 }
1931 };
1932 let rendered = crate::template_env::render(
1933 "csharp/assertion.jinja",
1934 minijinja::context! {
1935 assertion_type => "synthetic_assertion",
1936 synthetic_pred => synthetic_pred,
1937 synthetic_pred_type => synthetic_pred_type,
1938 },
1939 );
1940 out.push_str(&rendered);
1941 return;
1942 }
1943 "chunks_have_embeddings" => {
1944 let synthetic_pred =
1945 format!("({result_var}.Chunks ?? new()).All(c => c.Embedding != null && c.Embedding.Count > 0)");
1946 let synthetic_pred_type = match assertion.assertion_type.as_str() {
1947 "is_true" => "is_true",
1948 "is_false" => "is_false",
1949 _ => {
1950 out.push_str(&format!(
1951 " // skipped: unsupported assertion type on synthetic field '{f}'\n"
1952 ));
1953 return;
1954 }
1955 };
1956 let rendered = crate::template_env::render(
1957 "csharp/assertion.jinja",
1958 minijinja::context! {
1959 assertion_type => "synthetic_assertion",
1960 synthetic_pred => synthetic_pred,
1961 synthetic_pred_type => synthetic_pred_type,
1962 },
1963 );
1964 out.push_str(&rendered);
1965 return;
1966 }
1967 "embeddings" => {
1971 match assertion.assertion_type.as_str() {
1972 "count_equals" => {
1973 if let Some(val) = &assertion.value {
1974 if let Some(n) = val.as_u64() {
1975 let rendered = crate::template_env::render(
1976 "csharp/assertion.jinja",
1977 minijinja::context! {
1978 assertion_type => "synthetic_embeddings_count_equals",
1979 synthetic_pred => format!("{result_var}.Count"),
1980 n => n,
1981 },
1982 );
1983 out.push_str(&rendered);
1984 }
1985 }
1986 }
1987 "count_min" => {
1988 if let Some(val) = &assertion.value {
1989 if let Some(n) = val.as_u64() {
1990 let rendered = crate::template_env::render(
1991 "csharp/assertion.jinja",
1992 minijinja::context! {
1993 assertion_type => "synthetic_embeddings_count_min",
1994 synthetic_pred => format!("{result_var}.Count"),
1995 n => n,
1996 },
1997 );
1998 out.push_str(&rendered);
1999 }
2000 }
2001 }
2002 "not_empty" => {
2003 let rendered = crate::template_env::render(
2004 "csharp/assertion.jinja",
2005 minijinja::context! {
2006 assertion_type => "synthetic_embeddings_not_empty",
2007 synthetic_pred => result_var.to_string(),
2008 },
2009 );
2010 out.push_str(&rendered);
2011 }
2012 "is_empty" => {
2013 let rendered = crate::template_env::render(
2014 "csharp/assertion.jinja",
2015 minijinja::context! {
2016 assertion_type => "synthetic_embeddings_is_empty",
2017 synthetic_pred => result_var.to_string(),
2018 },
2019 );
2020 out.push_str(&rendered);
2021 }
2022 _ => {
2023 out.push_str(
2024 " // skipped: unsupported assertion type on synthetic field 'embeddings'\n",
2025 );
2026 }
2027 }
2028 return;
2029 }
2030 "embedding_dimensions" => {
2031 let expr = format!("({result_var}.Count > 0 ? {result_var}[0].Count : 0)");
2032 match assertion.assertion_type.as_str() {
2033 "equals" => {
2034 if let Some(val) = &assertion.value {
2035 if let Some(n) = val.as_u64() {
2036 let rendered = crate::template_env::render(
2037 "csharp/assertion.jinja",
2038 minijinja::context! {
2039 assertion_type => "synthetic_embedding_dimensions_equals",
2040 synthetic_pred => expr,
2041 n => n,
2042 },
2043 );
2044 out.push_str(&rendered);
2045 }
2046 }
2047 }
2048 "greater_than" => {
2049 if let Some(val) = &assertion.value {
2050 if let Some(n) = val.as_u64() {
2051 let rendered = crate::template_env::render(
2052 "csharp/assertion.jinja",
2053 minijinja::context! {
2054 assertion_type => "synthetic_embedding_dimensions_greater_than",
2055 synthetic_pred => expr,
2056 n => n,
2057 },
2058 );
2059 out.push_str(&rendered);
2060 }
2061 }
2062 }
2063 _ => {
2064 out.push_str(" // skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n");
2065 }
2066 }
2067 return;
2068 }
2069 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
2070 let synthetic_pred = match f.as_str() {
2071 "embeddings_valid" => {
2072 format!("{result_var}.All(e => e.Count > 0)")
2073 }
2074 "embeddings_finite" => {
2075 format!("{result_var}.All(e => e.All(v => !float.IsInfinity(v) && !float.IsNaN(v)))")
2076 }
2077 "embeddings_non_zero" => {
2078 format!("{result_var}.All(e => e.Any(v => v != 0.0f))")
2079 }
2080 "embeddings_normalized" => {
2081 format!(
2082 "{result_var}.All(e => {{ var n = e.Sum(v => (double)v * v); return Math.Abs(n - 1.0) < 1e-3; }})"
2083 )
2084 }
2085 _ => unreachable!(),
2086 };
2087 let synthetic_pred_type = match assertion.assertion_type.as_str() {
2088 "is_true" => "is_true",
2089 "is_false" => "is_false",
2090 _ => {
2091 out.push_str(&format!(
2092 " // skipped: unsupported assertion type on synthetic field '{f}'\n"
2093 ));
2094 return;
2095 }
2096 };
2097 let rendered = crate::template_env::render(
2098 "csharp/assertion.jinja",
2099 minijinja::context! {
2100 assertion_type => "synthetic_assertion",
2101 synthetic_pred => synthetic_pred,
2102 synthetic_pred_type => synthetic_pred_type,
2103 },
2104 );
2105 out.push_str(&rendered);
2106 return;
2107 }
2108 "keywords" | "keywords_count" => {
2111 let skipped_reason = format!("field '{f}' not available on C# ExtractionResult");
2112 let rendered = crate::template_env::render(
2113 "csharp/assertion.jinja",
2114 minijinja::context! {
2115 skipped_reason => skipped_reason,
2116 },
2117 );
2118 out.push_str(&rendered);
2119 return;
2120 }
2121 _ => {}
2122 }
2123 }
2124
2125 if let Some(f) = &assertion.field {
2127 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
2128 let skipped_reason = format!("field '{f}' not available on result type");
2129 let rendered = crate::template_env::render(
2130 "csharp/assertion.jinja",
2131 minijinja::context! {
2132 skipped_reason => skipped_reason,
2133 },
2134 );
2135 out.push_str(&rendered);
2136 return;
2137 }
2138 }
2139
2140 let is_count_assertion = matches!(
2143 assertion.assertion_type.as_str(),
2144 "count_equals" | "count_min" | "count_max"
2145 );
2146 let is_no_field = assertion.field.is_none() || assertion.field.as_ref().is_some_and(|f| f.is_empty());
2147 let use_list_directly = result_is_vec && is_count_assertion && is_no_field;
2148
2149 let effective_result_var: String = if result_is_vec && !use_list_directly {
2150 format!("{result_var}[0]")
2151 } else {
2152 result_var.to_string()
2153 };
2154
2155 let is_discriminated_union = assertion
2157 .field
2158 .as_ref()
2159 .is_some_and(|f| parse_discriminated_union_access(f).is_some());
2160
2161 if is_discriminated_union {
2163 if let Some((_, variant_name, inner_field)) = assertion
2164 .field
2165 .as_ref()
2166 .and_then(|f| parse_discriminated_union_access(f))
2167 {
2168 let mut hasher = std::collections::hash_map::DefaultHasher::new();
2170 inner_field.hash(&mut hasher);
2171 let var_hash = format!("{:x}", hasher.finish());
2172 let variant_var = format!("variant_{}", &var_hash[..8]);
2173 let _ = writeln!(
2174 out,
2175 " if ({effective_result_var}.Metadata.Format is FormatMetadata.{} {})",
2176 variant_name, &variant_var
2177 );
2178 let _ = writeln!(out, " {{");
2179 render_discriminated_union_assertion(out, assertion, &variant_var, &inner_field, result_is_vec);
2180 let _ = writeln!(out, " }}");
2181 let _ = writeln!(out, " else");
2182 let _ = writeln!(out, " {{");
2183 let _ = writeln!(
2184 out,
2185 " Assert.Fail(\"Expected {} format metadata\");",
2186 variant_name.to_lowercase()
2187 );
2188 let _ = writeln!(out, " }}");
2189 return;
2190 }
2191 }
2192
2193 let field_expr = if result_is_simple {
2194 effective_result_var.clone()
2195 } else {
2196 match &assertion.field {
2197 Some(f) if !f.is_empty() => field_resolver.accessor(f, "csharp", &effective_result_var),
2198 _ => effective_result_var.clone(),
2199 }
2200 };
2201
2202 let field_needs_json_serialize = if result_is_simple {
2206 result_is_array
2209 } else {
2210 match &assertion.field {
2211 Some(f) if !f.is_empty() => field_resolver.is_array(f),
2212 _ => !result_is_simple,
2214 }
2215 };
2216 let field_as_str = if field_needs_json_serialize {
2218 format!("JsonSerializer.Serialize({field_expr})")
2219 } else {
2220 format!("{field_expr}.ToString()")
2221 };
2222
2223 let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
2227 let resolved = field_resolver.resolve(f);
2228 fields_enum.contains(f) || fields_enum.contains(resolved)
2229 });
2230
2231 match assertion.assertion_type.as_str() {
2232 "equals" => {
2233 if let Some(expected) = &assertion.value {
2234 if field_is_enum && expected.is_string() {
2241 let s_lower = expected.as_str().map(|s| s.to_lowercase()).unwrap_or_default();
2242 let _ = writeln!(
2243 out,
2244 " Assert.Equal(\"{}\", {field_expr} == null ? null : JsonNamingPolicy.SnakeCaseLower.ConvertName({field_expr}.ToString()!));",
2245 escape_csharp(&s_lower)
2246 );
2247 return;
2248 }
2249 let cs_val = json_to_csharp(expected);
2250 let is_string_val = expected.is_string();
2251 let is_bool_true = expected.as_bool() == Some(true);
2252 let is_bool_false = expected.as_bool() == Some(false);
2253 let is_integer_val = expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0);
2254
2255 let rendered = crate::template_env::render(
2256 "csharp/assertion.jinja",
2257 minijinja::context! {
2258 assertion_type => "equals",
2259 field_expr => field_expr.clone(),
2260 cs_val => cs_val,
2261 is_string_val => is_string_val,
2262 is_bool_true => is_bool_true,
2263 is_bool_false => is_bool_false,
2264 is_integer_val => is_integer_val,
2265 },
2266 );
2267 out.push_str(&rendered);
2268 }
2269 }
2270 "contains" => {
2271 if let Some(expected) = &assertion.value {
2272 let lower_expected = expected.as_str().map(|s| s.to_lowercase());
2279 let cs_val = lower_expected
2280 .as_deref()
2281 .map(|s| format!("\"{}\"", escape_csharp(s)))
2282 .unwrap_or_else(|| json_to_csharp(expected));
2283
2284 let rendered = crate::template_env::render(
2285 "csharp/assertion.jinja",
2286 minijinja::context! {
2287 assertion_type => "contains",
2288 field_as_str => field_as_str.clone(),
2289 cs_val => cs_val,
2290 },
2291 );
2292 out.push_str(&rendered);
2293 }
2294 }
2295 "contains_all" => {
2296 if let Some(values) = &assertion.values {
2297 let values_cs_lower: Vec<String> = values
2298 .iter()
2299 .map(|val| {
2300 let lower_val = val.as_str().map(|s| s.to_lowercase());
2301 lower_val
2302 .as_deref()
2303 .map(|s| format!("\"{}\"", escape_csharp(s)))
2304 .unwrap_or_else(|| json_to_csharp(val))
2305 })
2306 .collect();
2307
2308 let rendered = crate::template_env::render(
2309 "csharp/assertion.jinja",
2310 minijinja::context! {
2311 assertion_type => "contains_all",
2312 field_as_str => field_as_str.clone(),
2313 values_cs_lower => values_cs_lower,
2314 },
2315 );
2316 out.push_str(&rendered);
2317 }
2318 }
2319 "not_contains" => {
2320 if let Some(expected) = &assertion.value {
2321 let cs_val = json_to_csharp(expected);
2322
2323 let rendered = crate::template_env::render(
2324 "csharp/assertion.jinja",
2325 minijinja::context! {
2326 assertion_type => "not_contains",
2327 field_as_str => field_as_str.clone(),
2328 cs_val => cs_val,
2329 },
2330 );
2331 out.push_str(&rendered);
2332 }
2333 }
2334 "not_empty" => {
2335 let rendered = crate::template_env::render(
2336 "csharp/assertion.jinja",
2337 minijinja::context! {
2338 assertion_type => "not_empty",
2339 field_expr => field_expr.clone(),
2340 field_needs_json_serialize => field_needs_json_serialize,
2341 },
2342 );
2343 out.push_str(&rendered);
2344 }
2345 "is_empty" => {
2346 let rendered = crate::template_env::render(
2347 "csharp/assertion.jinja",
2348 minijinja::context! {
2349 assertion_type => "is_empty",
2350 field_expr => field_expr.clone(),
2351 field_needs_json_serialize => field_needs_json_serialize,
2352 },
2353 );
2354 out.push_str(&rendered);
2355 }
2356 "contains_any" => {
2357 if let Some(values) = &assertion.values {
2358 let checks: Vec<String> = values
2359 .iter()
2360 .map(|v| {
2361 let cs_val = json_to_csharp(v);
2362 format!("{field_as_str}.Contains({cs_val})")
2363 })
2364 .collect();
2365 let contains_any_expr = checks.join(" || ");
2366
2367 let rendered = crate::template_env::render(
2368 "csharp/assertion.jinja",
2369 minijinja::context! {
2370 assertion_type => "contains_any",
2371 contains_any_expr => contains_any_expr,
2372 },
2373 );
2374 out.push_str(&rendered);
2375 }
2376 }
2377 "greater_than" => {
2378 if let Some(val) = &assertion.value {
2379 let cs_val = json_to_csharp(val);
2380
2381 let rendered = crate::template_env::render(
2382 "csharp/assertion.jinja",
2383 minijinja::context! {
2384 assertion_type => "greater_than",
2385 field_expr => field_expr.clone(),
2386 cs_val => cs_val,
2387 },
2388 );
2389 out.push_str(&rendered);
2390 }
2391 }
2392 "less_than" => {
2393 if let Some(val) = &assertion.value {
2394 let cs_val = json_to_csharp(val);
2395
2396 let rendered = crate::template_env::render(
2397 "csharp/assertion.jinja",
2398 minijinja::context! {
2399 assertion_type => "less_than",
2400 field_expr => field_expr.clone(),
2401 cs_val => cs_val,
2402 },
2403 );
2404 out.push_str(&rendered);
2405 }
2406 }
2407 "greater_than_or_equal" => {
2408 if let Some(val) = &assertion.value {
2409 let cs_val = json_to_csharp(val);
2410
2411 let rendered = crate::template_env::render(
2412 "csharp/assertion.jinja",
2413 minijinja::context! {
2414 assertion_type => "greater_than_or_equal",
2415 field_expr => field_expr.clone(),
2416 cs_val => cs_val,
2417 },
2418 );
2419 out.push_str(&rendered);
2420 }
2421 }
2422 "less_than_or_equal" => {
2423 if let Some(val) = &assertion.value {
2424 let cs_val = json_to_csharp(val);
2425
2426 let rendered = crate::template_env::render(
2427 "csharp/assertion.jinja",
2428 minijinja::context! {
2429 assertion_type => "less_than_or_equal",
2430 field_expr => field_expr.clone(),
2431 cs_val => cs_val,
2432 },
2433 );
2434 out.push_str(&rendered);
2435 }
2436 }
2437 "starts_with" => {
2438 if let Some(expected) = &assertion.value {
2439 let cs_val = json_to_csharp(expected);
2440
2441 let rendered = crate::template_env::render(
2442 "csharp/assertion.jinja",
2443 minijinja::context! {
2444 assertion_type => "starts_with",
2445 field_expr => field_expr.clone(),
2446 cs_val => cs_val,
2447 },
2448 );
2449 out.push_str(&rendered);
2450 }
2451 }
2452 "ends_with" => {
2453 if let Some(expected) = &assertion.value {
2454 let cs_val = json_to_csharp(expected);
2455
2456 let rendered = crate::template_env::render(
2457 "csharp/assertion.jinja",
2458 minijinja::context! {
2459 assertion_type => "ends_with",
2460 field_expr => field_expr.clone(),
2461 cs_val => cs_val,
2462 },
2463 );
2464 out.push_str(&rendered);
2465 }
2466 }
2467 "min_length" => {
2468 if let Some(val) = &assertion.value {
2469 if let Some(n) = val.as_u64() {
2470 let rendered = crate::template_env::render(
2471 "csharp/assertion.jinja",
2472 minijinja::context! {
2473 assertion_type => "min_length",
2474 field_expr => field_expr.clone(),
2475 n => n,
2476 },
2477 );
2478 out.push_str(&rendered);
2479 }
2480 }
2481 }
2482 "max_length" => {
2483 if let Some(val) = &assertion.value {
2484 if let Some(n) = val.as_u64() {
2485 let rendered = crate::template_env::render(
2486 "csharp/assertion.jinja",
2487 minijinja::context! {
2488 assertion_type => "max_length",
2489 field_expr => field_expr.clone(),
2490 n => n,
2491 },
2492 );
2493 out.push_str(&rendered);
2494 }
2495 }
2496 }
2497 "count_min" => {
2498 if let Some(val) = &assertion.value {
2499 if let Some(n) = val.as_u64() {
2500 let rendered = crate::template_env::render(
2501 "csharp/assertion.jinja",
2502 minijinja::context! {
2503 assertion_type => "count_min",
2504 field_expr => field_expr.clone(),
2505 n => n,
2506 },
2507 );
2508 out.push_str(&rendered);
2509 }
2510 }
2511 }
2512 "count_equals" => {
2513 if let Some(val) = &assertion.value {
2514 if let Some(n) = val.as_u64() {
2515 let rendered = crate::template_env::render(
2516 "csharp/assertion.jinja",
2517 minijinja::context! {
2518 assertion_type => "count_equals",
2519 field_expr => field_expr.clone(),
2520 n => n,
2521 },
2522 );
2523 out.push_str(&rendered);
2524 }
2525 }
2526 }
2527 "is_true" => {
2528 let rendered = crate::template_env::render(
2529 "csharp/assertion.jinja",
2530 minijinja::context! {
2531 assertion_type => "is_true",
2532 field_expr => field_expr.clone(),
2533 },
2534 );
2535 out.push_str(&rendered);
2536 }
2537 "is_false" => {
2538 let rendered = crate::template_env::render(
2539 "csharp/assertion.jinja",
2540 minijinja::context! {
2541 assertion_type => "is_false",
2542 field_expr => field_expr.clone(),
2543 },
2544 );
2545 out.push_str(&rendered);
2546 }
2547 "not_error" => {
2548 let rendered = crate::template_env::render(
2550 "csharp/assertion.jinja",
2551 minijinja::context! {
2552 assertion_type => "not_error",
2553 },
2554 );
2555 out.push_str(&rendered);
2556 }
2557 "error" => {
2558 let rendered = crate::template_env::render(
2560 "csharp/assertion.jinja",
2561 minijinja::context! {
2562 assertion_type => "error",
2563 },
2564 );
2565 out.push_str(&rendered);
2566 }
2567 "method_result" => {
2568 if let Some(method_name) = &assertion.method {
2569 let call_expr = build_csharp_method_call(result_var, method_name, assertion.args.as_ref(), class_name);
2570 let check = assertion.check.as_deref().unwrap_or("is_true");
2571
2572 match check {
2573 "equals" => {
2574 if let Some(val) = &assertion.value {
2575 let is_check_bool_true = val.as_bool() == Some(true);
2576 let is_check_bool_false = val.as_bool() == Some(false);
2577 let cs_check_val = json_to_csharp(val);
2578
2579 let rendered = crate::template_env::render(
2580 "csharp/assertion.jinja",
2581 minijinja::context! {
2582 assertion_type => "method_result",
2583 check => "equals",
2584 call_expr => call_expr.clone(),
2585 is_check_bool_true => is_check_bool_true,
2586 is_check_bool_false => is_check_bool_false,
2587 cs_check_val => cs_check_val,
2588 },
2589 );
2590 out.push_str(&rendered);
2591 }
2592 }
2593 "is_true" => {
2594 let rendered = crate::template_env::render(
2595 "csharp/assertion.jinja",
2596 minijinja::context! {
2597 assertion_type => "method_result",
2598 check => "is_true",
2599 call_expr => call_expr.clone(),
2600 },
2601 );
2602 out.push_str(&rendered);
2603 }
2604 "is_false" => {
2605 let rendered = crate::template_env::render(
2606 "csharp/assertion.jinja",
2607 minijinja::context! {
2608 assertion_type => "method_result",
2609 check => "is_false",
2610 call_expr => call_expr.clone(),
2611 },
2612 );
2613 out.push_str(&rendered);
2614 }
2615 "greater_than_or_equal" => {
2616 if let Some(val) = &assertion.value {
2617 let check_n = val.as_u64().unwrap_or(0);
2618
2619 let rendered = crate::template_env::render(
2620 "csharp/assertion.jinja",
2621 minijinja::context! {
2622 assertion_type => "method_result",
2623 check => "greater_than_or_equal",
2624 call_expr => call_expr.clone(),
2625 check_n => check_n,
2626 },
2627 );
2628 out.push_str(&rendered);
2629 }
2630 }
2631 "count_min" => {
2632 if let Some(val) = &assertion.value {
2633 let check_n = val.as_u64().unwrap_or(0);
2634
2635 let rendered = crate::template_env::render(
2636 "csharp/assertion.jinja",
2637 minijinja::context! {
2638 assertion_type => "method_result",
2639 check => "count_min",
2640 call_expr => call_expr.clone(),
2641 check_n => check_n,
2642 },
2643 );
2644 out.push_str(&rendered);
2645 }
2646 }
2647 "is_error" => {
2648 let rendered = crate::template_env::render(
2649 "csharp/assertion.jinja",
2650 minijinja::context! {
2651 assertion_type => "method_result",
2652 check => "is_error",
2653 call_expr => call_expr.clone(),
2654 exception_class => exception_class,
2655 },
2656 );
2657 out.push_str(&rendered);
2658 }
2659 "contains" => {
2660 if let Some(val) = &assertion.value {
2661 let cs_check_val = json_to_csharp(val);
2662
2663 let rendered = crate::template_env::render(
2664 "csharp/assertion.jinja",
2665 minijinja::context! {
2666 assertion_type => "method_result",
2667 check => "contains",
2668 call_expr => call_expr.clone(),
2669 cs_check_val => cs_check_val,
2670 },
2671 );
2672 out.push_str(&rendered);
2673 }
2674 }
2675 other_check => {
2676 panic!("C# e2e generator: unsupported method_result check type: {other_check}");
2677 }
2678 }
2679 } else {
2680 panic!("C# e2e generator: method_result assertion missing 'method' field");
2681 }
2682 }
2683 "matches_regex" => {
2684 if let Some(expected) = &assertion.value {
2685 let cs_val = json_to_csharp(expected);
2686
2687 let rendered = crate::template_env::render(
2688 "csharp/assertion.jinja",
2689 minijinja::context! {
2690 assertion_type => "matches_regex",
2691 field_expr => field_expr.clone(),
2692 cs_val => cs_val,
2693 },
2694 );
2695 out.push_str(&rendered);
2696 }
2697 }
2698 other => {
2699 panic!("C# e2e generator: unsupported assertion type: {other}");
2700 }
2701 }
2702}
2703
2704fn sort_discriminator_first(value: serde_json::Value) -> serde_json::Value {
2711 match value {
2712 serde_json::Value::Object(map) => {
2713 let mut sorted = serde_json::Map::with_capacity(map.len());
2714 if let Some(type_val) = map.get("type") {
2716 sorted.insert("type".to_string(), sort_discriminator_first(type_val.clone()));
2717 }
2718 for (k, v) in map {
2719 if k != "type" {
2720 sorted.insert(k, sort_discriminator_first(v));
2721 }
2722 }
2723 serde_json::Value::Object(sorted)
2724 }
2725 serde_json::Value::Array(arr) => {
2726 serde_json::Value::Array(arr.into_iter().map(sort_discriminator_first).collect())
2727 }
2728 other => other,
2729 }
2730}
2731
2732fn json_to_csharp(value: &serde_json::Value) -> String {
2734 match value {
2735 serde_json::Value::String(s) => format!("\"{}\"", escape_csharp(s)),
2736 serde_json::Value::Bool(true) => "true".to_string(),
2737 serde_json::Value::Bool(false) => "false".to_string(),
2738 serde_json::Value::Number(n) => {
2739 if n.is_f64() {
2740 format!("{}d", n)
2741 } else {
2742 n.to_string()
2743 }
2744 }
2745 serde_json::Value::Null => "null".to_string(),
2746 serde_json::Value::Array(arr) => {
2747 let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2748 format!("new[] {{ {} }}", items.join(", "))
2749 }
2750 serde_json::Value::Object(_) => {
2751 let json_str = serde_json::to_string(value).unwrap_or_default();
2752 format!("\"{}\"", escape_csharp(&json_str))
2753 }
2754 }
2755}
2756
2757fn default_csharp_nested_types() -> HashMap<String, String> {
2764 [
2765 ("chunking", "ChunkingConfig"),
2766 ("ocr", "OcrConfig"),
2767 ("images", "ImageExtractionConfig"),
2768 ("html_output", "HtmlOutputConfig"),
2769 ("language_detection", "LanguageDetectionConfig"),
2770 ("postprocessor", "PostProcessorConfig"),
2771 ("acceleration", "AccelerationConfig"),
2772 ("email", "EmailConfig"),
2773 ("pages", "PageConfig"),
2774 ("pdf_options", "PdfConfig"),
2775 ("layout", "LayoutDetectionConfig"),
2776 ("tree_sitter", "TreeSitterConfig"),
2777 ("structured_extraction", "StructuredExtractionConfig"),
2778 ("content_filter", "ContentFilterConfig"),
2779 ("token_reduction", "TokenReductionOptions"),
2780 ("security_limits", "SecurityLimits"),
2781 ("format", "FormatMetadata"),
2782 ("model", "EmbeddingModelType"),
2783 ]
2784 .iter()
2785 .map(|(k, v)| (k.to_string(), v.to_string()))
2786 .collect()
2787}
2788
2789fn csharp_object_initializer(
2797 obj: &serde_json::Map<String, serde_json::Value>,
2798 type_name: &str,
2799 enum_fields: &HashMap<String, String>,
2800 nested_types: &HashMap<String, String>,
2801) -> String {
2802 if obj.is_empty() {
2803 return format!("new {type_name}()");
2804 }
2805
2806 static IMPLICIT_ENUM_FIELDS: &[(&str, &str)] = &[("output_format", "OutputFormat")];
2809
2810 let props: Vec<String> = obj
2811 .iter()
2812 .map(|(key, val)| {
2813 let pascal_key = key.to_upper_camel_case();
2814 let implicit_enum_type = IMPLICIT_ENUM_FIELDS
2815 .iter()
2816 .find(|(k, _)| *k == key.as_str())
2817 .map(|(_, t)| *t);
2818 let camel_key = key.to_lower_camel_case();
2822 let cs_val = if let Some(enum_type) = enum_fields
2823 .get(key.as_str())
2824 .or_else(|| enum_fields.get(camel_key.as_str()))
2825 .map(String::as_str)
2826 .or(implicit_enum_type)
2827 {
2828 if val.is_null() {
2830 "null".to_string()
2831 } else {
2832 let member = val
2833 .as_str()
2834 .map(|s| s.to_upper_camel_case())
2835 .unwrap_or_else(|| "null".to_string());
2836 format!("{enum_type}.{member}")
2837 }
2838 } else if let Some(nested_type) = nested_types
2839 .get(key.as_str())
2840 .or_else(|| nested_types.get(camel_key.as_str()))
2841 {
2842 let normalized = normalize_csharp_enum_values(val, enum_fields);
2844 let json_str = serde_json::to_string(&normalized).unwrap_or_default();
2845 format!(
2846 "JsonSerializer.Deserialize<{nested_type}>(\"{}\", ConfigOptions)!",
2847 escape_csharp(&json_str)
2848 )
2849 } else if let Some(arr) = val.as_array() {
2850 let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2852 format!("new List<string> {{ {} }}", items.join(", "))
2853 } else {
2854 json_to_csharp(val)
2855 };
2856 format!("{pascal_key} = {cs_val}")
2857 })
2858 .collect();
2859 format!("new {} {{ {} }}", type_name, props.join(", "))
2860}
2861
2862fn normalize_csharp_enum_values(value: &serde_json::Value, enum_fields: &HashMap<String, String>) -> serde_json::Value {
2867 match value {
2868 serde_json::Value::Object(map) => {
2869 let mut result = map.clone();
2870 for (key, val) in result.iter_mut() {
2871 let camel_key = key.to_lower_camel_case();
2874 if enum_fields.contains_key(key) || enum_fields.contains_key(camel_key.as_str()) {
2875 if let Some(s) = val.as_str() {
2877 *val = serde_json::Value::String(s.to_lowercase());
2878 }
2879 }
2880 }
2881 serde_json::Value::Object(result)
2882 }
2883 other => other.clone(),
2884 }
2885}
2886
2887fn build_csharp_visitor(
2898 setup_lines: &mut Vec<String>,
2899 class_decls: &mut Vec<String>,
2900 fixture_id: &str,
2901 visitor_spec: &crate::fixture::VisitorSpec,
2902) -> String {
2903 use heck::ToUpperCamelCase;
2904 let class_name = format!("{}Visitor", fixture_id.to_upper_camel_case());
2905 let var_name = format!("_visitor_{}", fixture_id.replace('-', "_"));
2906
2907 setup_lines.push(format!("var {var_name} = new {class_name}();"));
2908
2909 let mut decl = String::new();
2911 decl.push_str(&format!(" private sealed class {class_name} : IHtmlVisitor\n"));
2912 decl.push_str(" {\n");
2913
2914 let all_methods = [
2916 "visit_element_start",
2917 "visit_element_end",
2918 "visit_text",
2919 "visit_link",
2920 "visit_image",
2921 "visit_heading",
2922 "visit_code_block",
2923 "visit_code_inline",
2924 "visit_list_item",
2925 "visit_list_start",
2926 "visit_list_end",
2927 "visit_table_start",
2928 "visit_table_row",
2929 "visit_table_end",
2930 "visit_blockquote",
2931 "visit_strong",
2932 "visit_emphasis",
2933 "visit_strikethrough",
2934 "visit_underline",
2935 "visit_subscript",
2936 "visit_superscript",
2937 "visit_mark",
2938 "visit_line_break",
2939 "visit_horizontal_rule",
2940 "visit_custom_element",
2941 "visit_definition_list_start",
2942 "visit_definition_term",
2943 "visit_definition_description",
2944 "visit_definition_list_end",
2945 "visit_form",
2946 "visit_input",
2947 "visit_button",
2948 "visit_audio",
2949 "visit_video",
2950 "visit_iframe",
2951 "visit_details",
2952 "visit_summary",
2953 "visit_figure_start",
2954 "visit_figcaption",
2955 "visit_figure_end",
2956 ];
2957
2958 for method_name in &all_methods {
2960 if let Some(action) = visitor_spec.callbacks.get(*method_name) {
2961 emit_csharp_visitor_method(&mut decl, method_name, action);
2962 } else {
2963 emit_csharp_visitor_method(&mut decl, method_name, &CallbackAction::Continue);
2965 }
2966 }
2967
2968 decl.push_str(" }\n");
2969 class_decls.push(decl);
2970
2971 var_name
2972}
2973
2974fn emit_csharp_visitor_method(decl: &mut String, method_name: &str, action: &CallbackAction) {
2976 let camel_method = method_to_camel(method_name);
2977 let params = match method_name {
2978 "visit_link" => "NodeContext ctx, string href, string text, string title",
2979 "visit_image" => "NodeContext ctx, string src, string alt, string title",
2980 "visit_heading" => "NodeContext ctx, uint level, string text, string id",
2981 "visit_code_block" => "NodeContext ctx, string lang, string code",
2982 "visit_code_inline"
2983 | "visit_strong"
2984 | "visit_emphasis"
2985 | "visit_strikethrough"
2986 | "visit_underline"
2987 | "visit_subscript"
2988 | "visit_superscript"
2989 | "visit_mark"
2990 | "visit_button"
2991 | "visit_summary"
2992 | "visit_figcaption"
2993 | "visit_definition_term"
2994 | "visit_definition_description" => "NodeContext ctx, string text",
2995 "visit_text" => "NodeContext ctx, string text",
2996 "visit_list_item" => "NodeContext ctx, bool ordered, string marker, string text",
2997 "visit_blockquote" => "NodeContext ctx, string content, ulong depth",
2998 "visit_table_row" => "NodeContext ctx, List<string> cells, bool isHeader",
2999 "visit_custom_element" => "NodeContext ctx, string tagName, string html",
3000 "visit_form" => "NodeContext ctx, string actionUrl, string method",
3001 "visit_input" => "NodeContext ctx, string inputType, string name, string value",
3002 "visit_audio" | "visit_video" | "visit_iframe" => "NodeContext ctx, string src",
3003 "visit_details" => "NodeContext ctx, bool isOpen",
3004 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
3005 "NodeContext ctx, string output"
3006 }
3007 "visit_list_start" => "NodeContext ctx, bool ordered",
3008 "visit_list_end" => "NodeContext ctx, bool ordered, string output",
3009 "visit_element_start"
3010 | "visit_table_start"
3011 | "visit_definition_list_start"
3012 | "visit_figure_start"
3013 | "visit_line_break"
3014 | "visit_horizontal_rule" => "NodeContext ctx",
3015 _ => "NodeContext ctx",
3016 };
3017
3018 let (action_type, action_value) = match action {
3019 CallbackAction::Skip => ("skip", String::new()),
3020 CallbackAction::Continue => ("continue", String::new()),
3021 CallbackAction::PreserveHtml => ("preserve_html", String::new()),
3022 CallbackAction::Custom { output } => ("custom", escape_csharp(output)),
3023 CallbackAction::CustomTemplate { template, .. } => {
3024 let camel = snake_case_template_to_camel(template);
3025 ("custom_template", escape_csharp(&camel))
3026 }
3027 };
3028
3029 let rendered = crate::template_env::render(
3030 "csharp/visitor_method.jinja",
3031 minijinja::context! {
3032 camel_method => camel_method,
3033 params => params,
3034 action_type => action_type,
3035 action_value => action_value,
3036 },
3037 );
3038 let _ = write!(decl, "{}", rendered);
3039}
3040
3041fn method_to_camel(snake: &str) -> String {
3043 use heck::ToUpperCamelCase;
3044 snake.to_upper_camel_case()
3045}
3046
3047fn snake_case_template_to_camel(template: &str) -> String {
3050 use heck::ToLowerCamelCase;
3051 let mut out = String::with_capacity(template.len());
3052 let mut chars = template.chars().peekable();
3053 while let Some(c) = chars.next() {
3054 if c == '{' {
3055 let mut name = String::new();
3056 while let Some(&nc) = chars.peek() {
3057 if nc == '}' {
3058 chars.next();
3059 break;
3060 }
3061 name.push(nc);
3062 chars.next();
3063 }
3064 out.push('{');
3065 out.push_str(&name.to_lower_camel_case());
3066 out.push('}');
3067 } else {
3068 out.push(c);
3069 }
3070 }
3071 out
3072}
3073
3074fn build_csharp_method_call(
3079 result_var: &str,
3080 method_name: &str,
3081 args: Option<&serde_json::Value>,
3082 class_name: &str,
3083) -> String {
3084 match method_name {
3085 "root_child_count" => format!("{result_var}.RootNode.ChildCount"),
3086 "root_node_type" => format!("{result_var}.RootNode.Kind"),
3087 "named_children_count" => format!("{result_var}.RootNode.NamedChildCount"),
3088 "has_error_nodes" => format!("{class_name}.TreeHasErrorNodes({result_var})"),
3089 "error_count" | "tree_error_count" => format!("{class_name}.TreeErrorCount({result_var})"),
3090 "tree_to_sexp" => format!("{class_name}.TreeToSexp({result_var})"),
3091 "contains_node_type" => {
3092 let node_type = args
3093 .and_then(|a| a.get("node_type"))
3094 .and_then(|v| v.as_str())
3095 .unwrap_or("");
3096 format!("{class_name}.TreeContainsNodeType({result_var}, \"{node_type}\")")
3097 }
3098 "find_nodes_by_type" => {
3099 let node_type = args
3100 .and_then(|a| a.get("node_type"))
3101 .and_then(|v| v.as_str())
3102 .unwrap_or("");
3103 format!("{class_name}.FindNodesByType({result_var}, \"{node_type}\")")
3104 }
3105 "run_query" => {
3106 let query_source = args
3107 .and_then(|a| a.get("query_source"))
3108 .and_then(|v| v.as_str())
3109 .unwrap_or("");
3110 let language = args
3111 .and_then(|a| a.get("language"))
3112 .and_then(|v| v.as_str())
3113 .unwrap_or("");
3114 format!("{class_name}.RunQuery({result_var}, \"{language}\", \"{query_source}\", source)")
3115 }
3116 _ => {
3117 use heck::ToUpperCamelCase;
3118 let pascal = method_name.to_upper_camel_case();
3119 format!("{result_var}.{pascal}()")
3120 }
3121 }
3122}
3123
3124fn fixture_has_csharp_callable(fixture: &Fixture, e2e_config: &E2eConfig) -> bool {
3125 if fixture.is_http_test() {
3127 return false;
3128 }
3129 let call_config = e2e_config.resolve_call_for_fixture(
3131 fixture.call.as_deref(),
3132 &fixture.id,
3133 &fixture.resolved_category(),
3134 &fixture.tags,
3135 &fixture.input,
3136 );
3137 let cs_override = call_config
3138 .overrides
3139 .get("csharp")
3140 .or_else(|| e2e_config.call.overrides.get("csharp"));
3141 if cs_override.and_then(|o| o.client_factory.as_deref()).is_some() {
3143 return true;
3144 }
3145 cs_override.and_then(|o| o.function.as_deref()).is_some() || !call_config.function.is_empty()
3148}
3149
3150fn classify_bytes_value_csharp(s: &str) -> String {
3153 if let Some(first) = s.chars().next() {
3156 if first.is_ascii_alphanumeric() || first == '_' {
3157 if let Some(slash_pos) = s.find('/') {
3158 if slash_pos > 0 {
3159 let after_slash = &s[slash_pos + 1..];
3160 if after_slash.contains('.') && !after_slash.is_empty() {
3161 return format!("System.IO.File.ReadAllBytes(\"{}\")", s);
3163 }
3164 }
3165 }
3166 }
3167 }
3168
3169 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
3172 return format!("System.Text.Encoding.UTF8.GetBytes(\"{}\")", escape_csharp(s));
3174 }
3175
3176 format!("System.Convert.FromBase64String(\"{}\")", s)
3180}
3181
3182#[cfg(test)]
3183mod tests {
3184 use crate::config::{CallConfig, E2eConfig, SelectWhen};
3185 use crate::fixture::Fixture;
3186 use std::collections::HashMap;
3187
3188 fn make_fixture_with_input(id: &str, input: serde_json::Value) -> Fixture {
3189 Fixture {
3190 id: id.to_string(),
3191 category: None,
3192 description: "test fixture".to_string(),
3193 tags: vec![],
3194 skip: None,
3195 env: None,
3196 call: None,
3197 input,
3198 mock_response: None,
3199 source: String::new(),
3200 http: None,
3201 assertions: vec![],
3202 visitor: None,
3203 }
3204 }
3205
3206 #[test]
3209 fn test_csharp_select_when_routes_to_batch_scrape() {
3210 let mut calls = HashMap::new();
3211 calls.insert(
3212 "batch_scrape".to_string(),
3213 CallConfig {
3214 function: "BatchScrape".to_string(),
3215 module: "KreuzBrowser".to_string(),
3216 select_when: Some(SelectWhen {
3217 input_has: Some("batch_urls".to_string()),
3218 ..Default::default()
3219 }),
3220 ..CallConfig::default()
3221 },
3222 );
3223
3224 let e2e_config = E2eConfig {
3225 call: CallConfig {
3226 function: "Scrape".to_string(),
3227 module: "KreuzBrowser".to_string(),
3228 ..CallConfig::default()
3229 },
3230 calls,
3231 ..E2eConfig::default()
3232 };
3233
3234 let fixture = make_fixture_with_input("batch_empty_urls", serde_json::json!({ "batch_urls": [] }));
3236
3237 let resolved_call = e2e_config.resolve_call_for_fixture(
3238 fixture.call.as_deref(),
3239 &fixture.id,
3240 &fixture.resolved_category(),
3241 &fixture.tags,
3242 &fixture.input,
3243 );
3244 assert_eq!(resolved_call.function, "BatchScrape");
3245
3246 let fixture_no_batch =
3248 make_fixture_with_input("simple_scrape", serde_json::json!({ "url": "https://example.com" }));
3249 let resolved_default = e2e_config.resolve_call_for_fixture(
3250 fixture_no_batch.call.as_deref(),
3251 &fixture_no_batch.id,
3252 &fixture_no_batch.resolved_category(),
3253 &fixture_no_batch.tags,
3254 &fixture_no_batch.input,
3255 );
3256 assert_eq!(resolved_default.function, "Scrape");
3257 }
3258}