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 is_streaming = call_config.streaming.unwrap_or(false);
836 let effective_function_name = {
837 let mut name = cs_overrides
838 .and_then(|o| o.function.as_ref())
839 .cloned()
840 .unwrap_or_else(|| call_config.function.to_upper_camel_case());
841 if call_config.r#async && !is_streaming && !name.ends_with("Async") {
842 name.push_str("Async");
843 }
844 name
845 };
846 let effective_result_var = &call_config.result_var;
847 let effective_is_async = call_config.r#async;
848 let function_name = effective_function_name.as_str();
849 let result_var = effective_result_var.as_str();
850 let is_async = effective_is_async;
851 let args = call_config.args.as_slice();
852
853 let per_call_result_is_simple = call_config.result_is_simple || cs_overrides.is_some_and(|o| o.result_is_simple);
857 let per_call_result_is_bytes = call_config.result_is_bytes || cs_overrides.is_some_and(|o| o.result_is_bytes);
862 let effective_result_is_simple = result_is_simple || per_call_result_is_simple || per_call_result_is_bytes;
863 let effective_result_is_bytes = per_call_result_is_bytes;
864 let returns_void = call_config.returns_void;
865 let extra_args_slice: &[String] = cs_overrides.map_or(&[], |o| o.extra_args.as_slice());
866 let top_level_options_type = e2e_config
868 .call
869 .overrides
870 .get("csharp")
871 .and_then(|o| o.options_type.as_deref());
872 let effective_options_type = cs_overrides
873 .and_then(|o| o.options_type.as_deref())
874 .or(top_level_options_type);
875
876 let top_level_options_via = e2e_config
883 .call
884 .overrides
885 .get("csharp")
886 .and_then(|o| o.options_via.as_deref());
887 let effective_options_via = cs_overrides
888 .and_then(|o| o.options_via.as_deref())
889 .or(top_level_options_via);
890
891 let adapter_request_type_owned: Option<String> = adapters
892 .iter()
893 .find(|a| a.name == call_config.function.as_str())
894 .and_then(|a| a.request_type.as_deref())
895 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
896 let (mut setup_lines, args_str) = build_args_and_setup(
897 &fixture.input,
898 args,
899 class_name,
900 effective_options_type,
901 effective_options_via,
902 enum_fields,
903 nested_types,
904 fixture,
905 adapter_request_type_owned.as_deref(),
906 );
907
908 let mut visitor_arg = String::new();
910 let has_visitor = fixture.visitor.is_some();
911 if let Some(visitor_spec) = &fixture.visitor {
912 visitor_arg = build_csharp_visitor(&mut setup_lines, visitor_class_decls, &fixture.id, visitor_spec);
913 }
914
915 let final_args = if has_visitor && !visitor_arg.is_empty() {
919 let opts_type = effective_options_type.unwrap_or("ConversionOptions");
920 if args_str.contains("JsonSerializer.Deserialize") {
921 setup_lines.push(format!("var options = {args_str};"));
923 setup_lines.push(format!("options.Visitor = {visitor_arg};"));
924 "options".to_string()
925 } else if args_str.ends_with(", null") {
926 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
928 let trimmed = args_str[..args_str.len() - 6].to_string(); format!("{trimmed}, options")
930 } else if args_str.contains(", null,") {
931 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
933 args_str.replace(", null,", ", options,")
934 } else if args_str.is_empty() {
935 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
937 "options".to_string()
938 } else {
939 setup_lines.push(format!("var options = new {opts_type} {{ Visitor = {visitor_arg} }};"));
941 format!("{args_str}, options")
942 }
943 } else if extra_args_slice.is_empty() {
944 args_str
945 } else if args_str.is_empty() {
946 extra_args_slice.join(", ")
947 } else {
948 format!("{args_str}, {}", extra_args_slice.join(", "))
949 };
950
951 let effective_function_name = function_name.to_string();
954
955 let return_type = if is_async { "async Task" } else { "void" };
956 let await_kw = if is_async { "await " } else { "" };
957
958 let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
961 e2e_config
962 .call
963 .overrides
964 .get("csharp")
965 .and_then(|o| o.client_factory.as_deref())
966 });
967 let call_target = if client_factory.is_some() {
968 "client".to_string()
969 } else {
970 class_name.to_string()
971 };
972
973 let mut client_factory_setup = String::new();
980 if let Some(factory) = client_factory {
981 let factory_name = factory.to_upper_camel_case();
982 let fixture_id = &fixture.id;
983 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
984 let api_key_var_opt = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
985 let is_live_smoke = !has_mock && api_key_var_opt.is_some();
986 if let Some(api_key_var) = api_key_var_opt.filter(|_| has_mock) {
987 client_factory_setup.push_str(&format!(
988 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
989 ));
990 client_factory_setup.push_str(&format!(
991 " var baseUrl = string.IsNullOrEmpty(apiKey)\n ? (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\"\n : null;\n"
992 ));
993 client_factory_setup.push_str(&format!(
994 " Console.WriteLine($\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({api_key_var} is set)\" : \"using mock server ({api_key_var} not set)\"));\n"
995 ));
996 client_factory_setup.push_str(&format!(
997 " var client = {class_name}.{factory_name}(string.IsNullOrEmpty(apiKey) ? \"test-key\" : apiKey, baseUrl, null, null, null);\n"
998 ));
999 } else if let Some(api_key_var) = api_key_var_opt.filter(|_| is_live_smoke) {
1000 client_factory_setup.push_str(&format!(
1001 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1002 ));
1003 client_factory_setup.push_str(" if (string.IsNullOrEmpty(apiKey)) { return; }\n");
1004 client_factory_setup.push_str(&format!(
1005 " var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
1006 ));
1007 } else if fixture.has_host_root_route() {
1008 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1009 client_factory_setup.push_str(&format!(
1010 " var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
1011 ));
1012 client_factory_setup.push_str(&format!(" var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1013 client_factory_setup.push_str(&format!(
1014 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1015 ));
1016 } else {
1017 client_factory_setup.push_str(&format!(" var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1018 client_factory_setup.push_str(&format!(
1019 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1020 ));
1021 }
1022 }
1023
1024 let call_expr = format!("{}({})", effective_function_name, final_args);
1026
1027 let mut effective_enum_fields: std::collections::HashSet<String> = e2e_config.fields_enum.clone();
1035 for k in enum_fields.keys() {
1036 effective_enum_fields.insert(k.clone());
1037 }
1038 if let Some(o) = cs_overrides {
1039 for k in o.enum_fields.keys() {
1040 effective_enum_fields.insert(k.clone());
1041 }
1042 }
1043
1044 let mut assertions_body = String::new();
1046 if !expects_error && !returns_void {
1047 for assertion in &fixture.assertions {
1048 render_assertion(
1049 &mut assertions_body,
1050 assertion,
1051 result_var,
1052 class_name,
1053 exception_class,
1054 field_resolver,
1055 effective_result_is_simple,
1056 call_config.result_is_vec || cs_overrides.is_some_and(|o| o.result_is_vec),
1057 call_config.result_is_array,
1058 effective_result_is_bytes,
1059 &effective_enum_fields,
1060 );
1061 }
1062 }
1063
1064 let ctx = minijinja::context! {
1065 is_skipped => false,
1066 expects_error => expects_error,
1067 description => description,
1068 return_type => return_type,
1069 method_name => method_name,
1070 async_kw => await_kw,
1071 call_target => call_target,
1072 setup_lines => setup_lines.clone(),
1073 call_expr => call_expr,
1074 exception_class => exception_class,
1075 client_factory_setup => client_factory_setup,
1076 has_usable_assertion => !expects_error && !returns_void,
1077 result_var => result_var,
1078 assertions_body => assertions_body,
1079 };
1080
1081 let rendered = crate::template_env::render("csharp/test_method.jinja", ctx);
1082 for line in rendered.lines() {
1084 out.push_str(" ");
1085 out.push_str(line);
1086 out.push('\n');
1087 }
1088}
1089
1090#[allow(clippy::too_many_arguments)]
1098fn render_chat_stream_test_method(
1099 out: &mut String,
1100 fixture: &Fixture,
1101 class_name: &str,
1102 call_config: &crate::config::CallConfig,
1103 cs_overrides: Option<&crate::config::CallOverride>,
1104 e2e_config: &E2eConfig,
1105 enum_fields: &HashMap<String, String>,
1106 nested_types: &HashMap<String, String>,
1107 exception_class: &str,
1108 adapters: &[alef_core::config::extras::AdapterConfig],
1109) {
1110 let method_name = fixture.id.to_upper_camel_case();
1111 let description = &fixture.description;
1112 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1113
1114 let effective_function_name = cs_overrides
1117 .and_then(|o| o.function.as_ref())
1118 .cloned()
1119 .unwrap_or_else(|| call_config.function.to_upper_camel_case());
1120 let function_name = effective_function_name.as_str();
1121 let args = call_config.args.as_slice();
1122
1123 let top_level_options_type = e2e_config
1124 .call
1125 .overrides
1126 .get("csharp")
1127 .and_then(|o| o.options_type.as_deref());
1128 let effective_options_type = cs_overrides
1129 .and_then(|o| o.options_type.as_deref())
1130 .or(top_level_options_type);
1131 let top_level_options_via = e2e_config
1132 .call
1133 .overrides
1134 .get("csharp")
1135 .and_then(|o| o.options_via.as_deref());
1136 let effective_options_via = cs_overrides
1137 .and_then(|o| o.options_via.as_deref())
1138 .or(top_level_options_via);
1139
1140 let adapter_request_type_cs: Option<String> = adapters
1141 .iter()
1142 .find(|a| a.name == call_config.function.as_str())
1143 .and_then(|a| a.request_type.as_deref())
1144 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
1145 let (setup_lines, args_str) = build_args_and_setup(
1146 &fixture.input,
1147 args,
1148 class_name,
1149 effective_options_type,
1150 effective_options_via,
1151 enum_fields,
1152 nested_types,
1153 fixture,
1154 adapter_request_type_cs.as_deref(),
1155 );
1156
1157 let client_factory = cs_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
1158 e2e_config
1159 .call
1160 .overrides
1161 .get("csharp")
1162 .and_then(|o| o.client_factory.as_deref())
1163 });
1164 let mut client_factory_setup = String::new();
1165 if let Some(factory) = client_factory {
1166 let factory_name = factory.to_upper_camel_case();
1167 let fixture_id = &fixture.id;
1168 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1169 let api_key_var_opt = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1170 let is_live_smoke = !has_mock && api_key_var_opt.is_some();
1171 if let Some(api_key_var) = api_key_var_opt.filter(|_| has_mock) {
1172 client_factory_setup.push_str(&format!(
1173 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1174 ));
1175 client_factory_setup.push_str(&format!(
1176 " var baseUrl = string.IsNullOrEmpty(apiKey)\n ? (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\"\n : null;\n"
1177 ));
1178 client_factory_setup.push_str(&format!(
1179 " Console.WriteLine($\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({api_key_var} is set)\" : \"using mock server ({api_key_var} not set)\"));\n"
1180 ));
1181 client_factory_setup.push_str(&format!(
1182 " var client = {class_name}.{factory_name}(string.IsNullOrEmpty(apiKey) ? \"test-key\" : apiKey, baseUrl, null, null, null);\n"
1183 ));
1184 } else if let Some(api_key_var) = api_key_var_opt.filter(|_| is_live_smoke) {
1185 client_factory_setup.push_str(&format!(
1186 " var apiKey = System.Environment.GetEnvironmentVariable(\"{api_key_var}\");\n"
1187 ));
1188 client_factory_setup.push_str(" if (string.IsNullOrEmpty(apiKey)) { return; }\n");
1189 client_factory_setup.push_str(&format!(
1190 " var client = {class_name}.{factory_name}(apiKey, null, null, null, null);\n"
1191 ));
1192 } else if fixture.has_host_root_route() {
1193 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1194 client_factory_setup.push_str(&format!(
1195 " var _perFixtureUrl = System.Environment.GetEnvironmentVariable(\"{env_key}\");\n"
1196 ));
1197 client_factory_setup.push_str(&format!(" var baseUrl = !string.IsNullOrEmpty(_perFixtureUrl) ? _perFixtureUrl : (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"));
1198 client_factory_setup.push_str(&format!(
1199 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1200 ));
1201 } else {
1202 client_factory_setup.push_str(&format!(
1203 " var baseUrl = (System.Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") ?? string.Empty) + \"/fixtures/{fixture_id}\";\n"
1204 ));
1205 client_factory_setup.push_str(&format!(
1206 " var client = {class_name}.{factory_name}(\"test-key\", baseUrl, null, null, null);\n"
1207 ));
1208 }
1209 }
1210
1211 let call_target = if client_factory.is_some() { "client" } else { class_name };
1212 let call_expr = format!("{call_target}.{function_name}({args_str})");
1213
1214 let mut needs_finish_reason = false;
1216 let mut needs_tool_calls_json = false;
1217 let mut needs_tool_calls_0_function_name = false;
1218 let mut needs_total_tokens = false;
1219 for a in &fixture.assertions {
1220 if let Some(f) = a.field.as_deref() {
1221 match f {
1222 "finish_reason" => needs_finish_reason = true,
1223 "tool_calls" => needs_tool_calls_json = true,
1224 "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
1225 "usage.total_tokens" => needs_total_tokens = true,
1226 _ => {}
1227 }
1228 }
1229 }
1230
1231 let mut body = String::new();
1232 let _ = writeln!(body, " [Fact]");
1233 let _ = writeln!(body, " public async Task Test_{method_name}()");
1234 let _ = writeln!(body, " {{");
1235 let _ = writeln!(body, " // {description}");
1236 if !client_factory_setup.is_empty() {
1237 body.push_str(&client_factory_setup);
1238 }
1239 for line in &setup_lines {
1240 let _ = writeln!(body, " {line}");
1241 }
1242
1243 if expects_error {
1244 let _ = writeln!(
1247 body,
1248 " await Assert.ThrowsAnyAsync<{exception_class}>(async () => {{"
1249 );
1250 let _ = writeln!(body, " await foreach (var _chunk in {call_expr}) {{ }}");
1251 body.push_str(" });\n");
1252 body.push_str(" }\n");
1253 for line in body.lines() {
1254 out.push_str(" ");
1255 out.push_str(line);
1256 out.push('\n');
1257 }
1258 return;
1259 }
1260
1261 body.push_str(" var chunks = new List<ChatCompletionChunk>();\n");
1262 body.push_str(" var streamContent = new System.Text.StringBuilder();\n");
1263 body.push_str(" var streamComplete = false;\n");
1264 if needs_finish_reason {
1265 body.push_str(" string? lastFinishReason = null;\n");
1266 }
1267 if needs_tool_calls_json {
1268 body.push_str(" string? toolCallsJson = null;\n");
1269 }
1270 if needs_tool_calls_0_function_name {
1271 body.push_str(" string? toolCalls0FunctionName = null;\n");
1272 }
1273 if needs_total_tokens {
1274 body.push_str(" long? totalTokens = null;\n");
1275 }
1276 let _ = writeln!(body, " await foreach (var chunk in {call_expr})");
1277 body.push_str(" {\n");
1278 body.push_str(" chunks.Add(chunk);\n");
1279 body.push_str(
1280 " var choice = chunk.Choices != null && chunk.Choices.Count > 0 ? chunk.Choices[0] : null;\n",
1281 );
1282 body.push_str(" if (choice != null)\n");
1283 body.push_str(" {\n");
1284 body.push_str(" var delta = choice.Delta;\n");
1285 body.push_str(" if (delta != null && !string.IsNullOrEmpty(delta.Content))\n");
1286 body.push_str(" {\n");
1287 body.push_str(" streamContent.Append(delta.Content);\n");
1288 body.push_str(" }\n");
1289 if needs_finish_reason {
1290 body.push_str(" if (choice.FinishReason != null)\n");
1298 body.push_str(" {\n");
1299 body.push_str(
1300 " lastFinishReason = JsonNamingPolicy.SnakeCaseLower.ConvertName(choice.FinishReason.ToString()!);\n",
1301 );
1302 body.push_str(" }\n");
1303 }
1304 if needs_tool_calls_json || needs_tool_calls_0_function_name {
1305 body.push_str(" var tcs = delta?.ToolCalls;\n");
1306 body.push_str(" if (tcs != null && tcs.Count > 0)\n");
1307 body.push_str(" {\n");
1308 if needs_tool_calls_json {
1309 body.push_str(
1310 " toolCallsJson ??= JsonSerializer.Serialize(tcs.Select(tc => new { function = new { name = tc.Function?.Name } }));\n",
1311 );
1312 }
1313 if needs_tool_calls_0_function_name {
1314 body.push_str(" toolCalls0FunctionName ??= tcs[0].Function?.Name;\n");
1315 }
1316 body.push_str(" }\n");
1317 }
1318 body.push_str(" }\n");
1319 if needs_total_tokens {
1320 body.push_str(" if (chunk.Usage != null)\n");
1321 body.push_str(" {\n");
1322 body.push_str(" totalTokens = chunk.Usage.TotalTokens;\n");
1323 body.push_str(" }\n");
1324 }
1325 body.push_str(" }\n");
1326 body.push_str(" streamComplete = true;\n");
1327
1328 let mut had_explicit_complete = false;
1330 for assertion in &fixture.assertions {
1331 if assertion.field.as_deref() == Some("stream_complete") {
1332 had_explicit_complete = true;
1333 }
1334 emit_chat_stream_assertion(&mut body, assertion);
1335 }
1336 if !had_explicit_complete {
1337 body.push_str(" Assert.True(streamComplete);\n");
1338 }
1339
1340 body.push_str(" }\n");
1341
1342 for line in body.lines() {
1343 out.push_str(" ");
1344 out.push_str(line);
1345 out.push('\n');
1346 }
1347}
1348
1349fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion) {
1353 let atype = assertion.assertion_type.as_str();
1354 if atype == "not_error" || atype == "error" {
1355 return;
1356 }
1357 let field = assertion.field.as_deref().unwrap_or("");
1358
1359 enum Kind {
1360 Chunks,
1361 Bool,
1362 Str,
1363 IntTokens,
1364 Json,
1365 Unsupported,
1366 }
1367
1368 let (expr, kind) = match field {
1369 "chunks" => ("chunks", Kind::Chunks),
1370 "stream_content" => ("streamContent.ToString()", Kind::Str),
1371 "stream_complete" => ("streamComplete", Kind::Bool),
1372 "no_chunks_after_done" => ("streamComplete", Kind::Bool),
1373 "finish_reason" => ("lastFinishReason", Kind::Str),
1374 "tool_calls" => ("toolCallsJson", Kind::Json),
1375 "tool_calls[0].function.name" => ("toolCalls0FunctionName", Kind::Str),
1376 "usage.total_tokens" => ("totalTokens", Kind::IntTokens),
1377 _ => ("", Kind::Unsupported),
1378 };
1379
1380 if matches!(kind, Kind::Unsupported) {
1381 let _ = writeln!(
1382 out,
1383 " // skipped: streaming assertion on unsupported field '{field}'"
1384 );
1385 return;
1386 }
1387
1388 match (atype, &kind) {
1389 ("count_min", Kind::Chunks) => {
1390 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1391 let _ = writeln!(
1392 out,
1393 " Assert.True(chunks.Count >= {n}, \"expected at least {n} chunks\");"
1394 );
1395 }
1396 }
1397 ("count_equals", Kind::Chunks) => {
1398 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1399 let _ = writeln!(out, " Assert.Equal({n}, chunks.Count);");
1400 }
1401 }
1402 ("equals", Kind::Str) => {
1403 if let Some(val) = &assertion.value {
1404 let cs_val = json_to_csharp(val);
1405 let _ = writeln!(out, " Assert.Equal({cs_val}, {expr});");
1406 }
1407 }
1408 ("contains", Kind::Str) => {
1409 if let Some(val) = &assertion.value {
1410 let cs_val = json_to_csharp(val);
1411 let _ = writeln!(out, " Assert.Contains({cs_val}, {expr} ?? string.Empty);");
1412 }
1413 }
1414 ("not_empty", Kind::Str) => {
1415 let _ = writeln!(out, " Assert.False(string.IsNullOrEmpty({expr}));");
1416 }
1417 ("not_empty", Kind::Json) => {
1418 let _ = writeln!(out, " Assert.NotNull({expr});");
1419 }
1420 ("is_empty", Kind::Str) => {
1421 let _ = writeln!(out, " Assert.True(string.IsNullOrEmpty({expr}));");
1422 }
1423 ("is_true", Kind::Bool) => {
1424 let _ = writeln!(out, " Assert.True({expr});");
1425 }
1426 ("is_false", Kind::Bool) => {
1427 let _ = writeln!(out, " Assert.False({expr});");
1428 }
1429 ("greater_than_or_equal", Kind::IntTokens) => {
1430 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1431 let _ = writeln!(out, " Assert.True({expr} >= {n}, \"expected >= {n}\");");
1432 }
1433 }
1434 ("equals", Kind::IntTokens) => {
1435 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1436 let _ = writeln!(out, " Assert.Equal((long?){n}, {expr});");
1437 }
1438 }
1439 _ => {
1440 let _ = writeln!(
1441 out,
1442 " // skipped: streaming assertion '{atype}' on field '{field}' not supported"
1443 );
1444 }
1445 }
1446}
1447
1448#[allow(clippy::too_many_arguments)]
1452fn build_args_and_setup(
1453 input: &serde_json::Value,
1454 args: &[crate::config::ArgMapping],
1455 class_name: &str,
1456 options_type: Option<&str>,
1457 options_via: Option<&str>,
1458 enum_fields: &HashMap<String, String>,
1459 nested_types: &HashMap<String, String>,
1460 fixture: &crate::fixture::Fixture,
1461 adapter_request_type: Option<&str>,
1462) -> (Vec<String>, String) {
1463 let fixture_id = &fixture.id;
1464 if args.is_empty() {
1465 return (Vec::new(), String::new());
1466 }
1467
1468 let mut setup_lines: Vec<String> = Vec::new();
1469 let mut parts: Vec<String> = Vec::new();
1470
1471 for arg in args {
1472 if arg.arg_type == "bytes" {
1473 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1475 let val = input.get(field);
1476 match val {
1477 None | Some(serde_json::Value::Null) if arg.optional => {
1478 parts.push("null".to_string());
1479 }
1480 None | Some(serde_json::Value::Null) => {
1481 parts.push("System.Array.Empty<byte>()".to_string());
1482 }
1483 Some(v) => {
1484 if let Some(s) = v.as_str() {
1489 let bytes_code = classify_bytes_value_csharp(s);
1490 parts.push(bytes_code);
1491 } else {
1492 let cs_str = json_to_csharp(v);
1494 parts.push(format!("System.Text.Encoding.UTF8.GetBytes({cs_str})"));
1495 }
1496 }
1497 }
1498 continue;
1499 }
1500
1501 if arg.arg_type == "mock_url" {
1502 if fixture.has_host_root_route() {
1503 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1504 setup_lines.push(format!(
1505 "var _pfUrl_{name} = Environment.GetEnvironmentVariable(\"{env_key}\");",
1506 name = arg.name,
1507 ));
1508 setup_lines.push(format!(
1509 "var {} = !string.IsNullOrEmpty(_pfUrl_{name}) ? _pfUrl_{name} : Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1510 arg.name,
1511 name = arg.name,
1512 ));
1513 } else {
1514 setup_lines.push(format!(
1515 "var {} = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
1516 arg.name,
1517 ));
1518 }
1519 if let Some(req_type) = adapter_request_type {
1520 let req_var = format!("{}Req", arg.name);
1521 setup_lines.push(format!(
1522 "var {req_var} = new {class_name}.{req_type} {{ Url = {} }};",
1523 arg.name
1524 ));
1525 parts.push(req_var);
1526 } else {
1527 parts.push(arg.name.clone());
1528 }
1529 continue;
1530 }
1531
1532 if arg.arg_type == "mock_url_list" {
1533 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1540 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1541 let val = input.get(field).unwrap_or(&serde_json::Value::Null);
1542 let paths: Vec<String> = if let Some(arr) = val.as_array() {
1543 arr.iter()
1544 .filter_map(|v| v.as_str().map(|s| format!("\"{}\"", escape_csharp(s))))
1545 .collect()
1546 } else {
1547 Vec::new()
1548 };
1549 let paths_literal = paths.join(", ");
1550 let name = &arg.name;
1551 setup_lines.push(format!(
1552 "var _pfBase_{name} = Environment.GetEnvironmentVariable(\"{env_key}\");"
1553 ));
1554 setup_lines.push(format!(
1555 "var _base_{name} = !string.IsNullOrEmpty(_pfBase_{name}) ? _pfBase_{name} : Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";"
1556 ));
1557 setup_lines.push(format!(
1558 "var {name} = new System.Collections.Generic.List<string>(new[] {{ {paths_literal} }}.Select(p => p.StartsWith(\"http\") ? p : _base_{name} + p));"
1559 ));
1560 parts.push(name.clone());
1561 continue;
1562 }
1563
1564 if arg.arg_type == "handle" {
1565 let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
1567 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1568 let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1569 if config_value.is_null()
1570 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1571 {
1572 setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
1573 } else {
1574 let sorted = sort_discriminator_first(config_value.clone());
1578 let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1579 let name = &arg.name;
1580 setup_lines.push(format!(
1581 "var {name}Config = JsonSerializer.Deserialize<CrawlConfig>(\"{}\", ConfigOptions)!;",
1582 escape_csharp(&json_str),
1583 ));
1584 setup_lines.push(format!(
1585 "var {} = {class_name}.{constructor_name}({name}Config);",
1586 arg.name,
1587 name = name,
1588 ));
1589 }
1590 parts.push(arg.name.clone());
1591 continue;
1592 }
1593
1594 let val: Option<&serde_json::Value> = if arg.field == "input" {
1597 Some(input)
1598 } else {
1599 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1600 input.get(field)
1601 };
1602 match val {
1603 None | Some(serde_json::Value::Null) if arg.optional => {
1604 parts.push("null".to_string());
1607 continue;
1608 }
1609 None | Some(serde_json::Value::Null) => {
1610 let default_val = match arg.arg_type.as_str() {
1614 "string" => "\"\"".to_string(),
1615 "int" | "integer" => "0".to_string(),
1616 "float" | "number" => "0.0d".to_string(),
1617 "bool" | "boolean" => "false".to_string(),
1618 "json_object" => {
1619 if let Some(opts_type) = options_type {
1620 format!("new {opts_type}()")
1621 } else {
1622 "null".to_string()
1623 }
1624 }
1625 _ => "null".to_string(),
1626 };
1627 parts.push(default_val);
1628 }
1629 Some(v) => {
1630 if arg.arg_type == "json_object" {
1631 if options_via == Some("from_json")
1637 && let Some(opts_type) = options_type
1638 {
1639 let sorted = sort_discriminator_first(v.clone());
1640 let json_str = serde_json::to_string(&sorted).unwrap_or_default();
1641 let escaped = escape_csharp(&json_str);
1642 parts.push(format!("{opts_type}.FromJson(\"{escaped}\")",));
1648 continue;
1649 }
1650 if let Some(arr) = v.as_array() {
1652 parts.push(json_array_to_csharp_list(arr, arg.element_type.as_deref()));
1653 continue;
1654 }
1655 if let Some(opts_type) = options_type {
1657 if let Some(obj) = v.as_object() {
1658 parts.push(csharp_object_initializer(obj, opts_type, enum_fields, nested_types));
1659 continue;
1660 }
1661 }
1662 }
1663 parts.push(json_to_csharp(v));
1664 }
1665 }
1666 }
1667
1668 (setup_lines, parts.join(", "))
1669}
1670
1671fn json_array_to_csharp_list(arr: &[serde_json::Value], element_type: Option<&str>) -> String {
1679 match element_type {
1680 Some("BatchBytesItem") => {
1681 let items: Vec<String> = arr
1682 .iter()
1683 .filter_map(|v| v.as_object())
1684 .map(|obj| {
1685 let content = obj.get("content").and_then(|v| v.as_array());
1686 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1687 let content_code = if let Some(arr) = content {
1688 let bytes: Vec<String> = arr
1689 .iter()
1690 .filter_map(|v| v.as_u64().map(|n| format!("(byte){}", n)))
1691 .collect();
1692 format!("new byte[] {{ {} }}", bytes.join(", "))
1693 } else {
1694 "new byte[] { }".to_string()
1695 };
1696 format!(
1697 "new BatchBytesItem {{ Content = {}, MimeType = \"{}\" }}",
1698 content_code, mime_type
1699 )
1700 })
1701 .collect();
1702 format!("new List<BatchBytesItem>() {{ {} }}", items.join(", "))
1703 }
1704 Some("BatchFileItem") => {
1705 let items: Vec<String> = arr
1706 .iter()
1707 .filter_map(|v| v.as_object())
1708 .map(|obj| {
1709 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1710 format!("new BatchFileItem {{ Path = \"{}\" }}", path)
1711 })
1712 .collect();
1713 format!("new List<BatchFileItem>() {{ {} }}", items.join(", "))
1714 }
1715 Some("f32") => {
1716 let items: Vec<String> = arr.iter().map(|v| format!("(float){}", json_to_csharp(v))).collect();
1717 format!("new List<float>() {{ {} }}", items.join(", "))
1718 }
1719 Some("(String, String)") => {
1720 let items: Vec<String> = arr
1721 .iter()
1722 .map(|v| {
1723 let strs: Vec<String> = v
1724 .as_array()
1725 .map_or_else(Vec::new, |a| a.iter().map(json_to_csharp).collect());
1726 format!("new List<string>() {{ {} }}", strs.join(", "))
1727 })
1728 .collect();
1729 format!("new List<List<string>>() {{ {} }}", items.join(", "))
1730 }
1731 Some(et)
1732 if et != "f32"
1733 && et != "(String, String)"
1734 && et != "string"
1735 && et != "BatchBytesItem"
1736 && et != "BatchFileItem" =>
1737 {
1738 let items: Vec<String> = arr
1740 .iter()
1741 .map(|v| {
1742 let json_str = serde_json::to_string(v).unwrap_or_default();
1743 let escaped = escape_csharp(&json_str);
1744 format!("JsonSerializer.Deserialize<{et}>(\"{escaped}\", ConfigOptions)!")
1745 })
1746 .collect();
1747 format!("new List<{et}>() {{ {} }}", items.join(", "))
1748 }
1749 _ => {
1750 let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
1751 format!("new List<string>() {{ {} }}", items.join(", "))
1752 }
1753 }
1754}
1755
1756fn parse_discriminated_union_access(field: &str) -> Option<(String, String, String)> {
1760 let parts: Vec<&str> = field.split('.').collect();
1761 if parts.len() >= 3 && parts.len() <= 4 {
1762 if parts[0] == "metadata" && parts[1] == "format" {
1764 let variant_name = parts[2];
1765 let known_variants = [
1767 "pdf",
1768 "docx",
1769 "excel",
1770 "email",
1771 "pptx",
1772 "archive",
1773 "image",
1774 "xml",
1775 "text",
1776 "html",
1777 "ocr",
1778 "csv",
1779 "bibtex",
1780 "citation",
1781 "fiction_book",
1782 "dbf",
1783 "jats",
1784 "epub",
1785 "pst",
1786 "code",
1787 ];
1788 if known_variants.contains(&variant_name) {
1789 let variant_pascal = variant_name.to_upper_camel_case();
1790 if parts.len() == 4 {
1791 let inner_field = parts[3];
1792 return Some((
1793 format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1794 variant_pascal,
1795 inner_field.to_string(),
1796 ));
1797 } else if parts.len() == 3 {
1798 return Some((
1800 format!("result.Metadata.Format! as FormatMetadata.{}", variant_pascal),
1801 variant_pascal,
1802 String::new(),
1803 ));
1804 }
1805 }
1806 }
1807 }
1808 None
1809}
1810
1811fn render_discriminated_union_assertion(
1815 out: &mut String,
1816 assertion: &Assertion,
1817 variant_var: &str,
1818 inner_field: &str,
1819 _result_is_vec: bool,
1820) {
1821 if inner_field.is_empty() {
1822 return; }
1824
1825 let field_pascal = inner_field.to_upper_camel_case();
1826 let field_expr = format!("{variant_var}.Value.{field_pascal}");
1827
1828 match assertion.assertion_type.as_str() {
1829 "equals" => {
1830 if let Some(expected) = &assertion.value {
1831 let cs_val = json_to_csharp(expected);
1832 if expected.is_string() {
1833 let _ = writeln!(out, " Assert.Equal({cs_val}, {field_expr}!.Trim());");
1834 } else if expected.as_bool() == Some(true) {
1835 let _ = writeln!(out, " Assert.True({field_expr});");
1836 } else if expected.as_bool() == Some(false) {
1837 let _ = writeln!(out, " Assert.False({field_expr});");
1838 } else if expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0) {
1839 let _ = writeln!(out, " Assert.True({field_expr} == {cs_val});");
1840 } else {
1841 let _ = writeln!(out, " Assert.Equal({cs_val}, {field_expr});");
1842 }
1843 }
1844 }
1845 "greater_than_or_equal" => {
1846 if let Some(val) = &assertion.value {
1847 let cs_val = json_to_csharp(val);
1848 let _ = writeln!(
1849 out,
1850 " Assert.True({field_expr} >= {cs_val}, \"expected >= {cs_val}\");"
1851 );
1852 }
1853 }
1854 "contains_all" => {
1855 if let Some(values) = &assertion.values {
1856 let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1857 for val in values {
1858 let lower_val = val.as_str().map(|s| s.to_lowercase());
1859 let cs_val = lower_val
1860 .as_deref()
1861 .map(|s| format!("\"{}\"", escape_csharp(s)))
1862 .unwrap_or_else(|| json_to_csharp(val));
1863 let _ = writeln!(out, " Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1864 }
1865 }
1866 }
1867 "contains" => {
1868 if let Some(expected) = &assertion.value {
1869 let field_as_str = format!("JsonSerializer.Serialize({field_expr})");
1870 let lower_expected = expected.as_str().map(|s| s.to_lowercase());
1871 let cs_val = lower_expected
1872 .as_deref()
1873 .map(|s| format!("\"{}\"", escape_csharp(s)))
1874 .unwrap_or_else(|| json_to_csharp(expected));
1875 let _ = writeln!(out, " Assert.Contains({cs_val}, {field_as_str}.ToLower());");
1876 }
1877 }
1878 "not_empty" => {
1879 let _ = writeln!(out, " Assert.NotEmpty({field_expr});");
1880 }
1881 "is_empty" => {
1882 let _ = writeln!(out, " Assert.Empty({field_expr});");
1883 }
1884 _ => {
1885 let _ = writeln!(
1886 out,
1887 " // skipped: assertion type '{}' not yet supported for discriminated union fields",
1888 assertion.assertion_type
1889 );
1890 }
1891 }
1892}
1893
1894#[allow(clippy::too_many_arguments)]
1895fn render_assertion(
1896 out: &mut String,
1897 assertion: &Assertion,
1898 result_var: &str,
1899 class_name: &str,
1900 exception_class: &str,
1901 field_resolver: &FieldResolver,
1902 result_is_simple: bool,
1903 result_is_vec: bool,
1904 result_is_array: bool,
1905 result_is_bytes: bool,
1906 fields_enum: &std::collections::HashSet<String>,
1907) {
1908 if result_is_bytes {
1912 match assertion.assertion_type.as_str() {
1913 "not_empty" => {
1914 let _ = writeln!(out, " Assert.NotEmpty({result_var});");
1915 return;
1916 }
1917 "is_empty" => {
1918 let _ = writeln!(out, " Assert.Empty({result_var});");
1919 return;
1920 }
1921 "count_equals" | "length_equals" => {
1922 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1923 let _ = writeln!(out, " Assert.Equal({n}, {result_var}.Length);");
1924 }
1925 return;
1926 }
1927 "count_min" | "length_min" => {
1928 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1929 let _ = writeln!(out, " Assert.True({result_var}.Length >= {n});");
1930 }
1931 return;
1932 }
1933 "not_error" => {
1934 let _ = writeln!(out, " Assert.NotNull({result_var});");
1935 return;
1936 }
1937 _ => {
1938 let _ = writeln!(
1942 out,
1943 " // skipped: assertion type '{}' not supported on byte[] result",
1944 assertion.assertion_type
1945 );
1946 return;
1947 }
1948 }
1949 }
1950 if let Some(f) = &assertion.field {
1953 match f.as_str() {
1954 "chunks_have_content" => {
1955 let synthetic_pred =
1956 format!("({result_var}.Chunks ?? new()).All(c => !string.IsNullOrEmpty(c.Content))");
1957 let synthetic_pred_type = match assertion.assertion_type.as_str() {
1958 "is_true" => "is_true",
1959 "is_false" => "is_false",
1960 _ => {
1961 out.push_str(&format!(
1962 " // skipped: unsupported assertion type on synthetic field '{f}'\n"
1963 ));
1964 return;
1965 }
1966 };
1967 let rendered = crate::template_env::render(
1968 "csharp/assertion.jinja",
1969 minijinja::context! {
1970 assertion_type => "synthetic_assertion",
1971 synthetic_pred => synthetic_pred,
1972 synthetic_pred_type => synthetic_pred_type,
1973 },
1974 );
1975 out.push_str(&rendered);
1976 return;
1977 }
1978 "chunks_have_embeddings" => {
1979 let synthetic_pred =
1980 format!("({result_var}.Chunks ?? new()).All(c => c.Embedding != null && c.Embedding.Count > 0)");
1981 let synthetic_pred_type = match assertion.assertion_type.as_str() {
1982 "is_true" => "is_true",
1983 "is_false" => "is_false",
1984 _ => {
1985 out.push_str(&format!(
1986 " // skipped: unsupported assertion type on synthetic field '{f}'\n"
1987 ));
1988 return;
1989 }
1990 };
1991 let rendered = crate::template_env::render(
1992 "csharp/assertion.jinja",
1993 minijinja::context! {
1994 assertion_type => "synthetic_assertion",
1995 synthetic_pred => synthetic_pred,
1996 synthetic_pred_type => synthetic_pred_type,
1997 },
1998 );
1999 out.push_str(&rendered);
2000 return;
2001 }
2002 "embeddings" => {
2006 match assertion.assertion_type.as_str() {
2007 "count_equals" => {
2008 if let Some(val) = &assertion.value {
2009 if let Some(n) = val.as_u64() {
2010 let rendered = crate::template_env::render(
2011 "csharp/assertion.jinja",
2012 minijinja::context! {
2013 assertion_type => "synthetic_embeddings_count_equals",
2014 synthetic_pred => format!("{result_var}.Count"),
2015 n => n,
2016 },
2017 );
2018 out.push_str(&rendered);
2019 }
2020 }
2021 }
2022 "count_min" => {
2023 if let Some(val) = &assertion.value {
2024 if let Some(n) = val.as_u64() {
2025 let rendered = crate::template_env::render(
2026 "csharp/assertion.jinja",
2027 minijinja::context! {
2028 assertion_type => "synthetic_embeddings_count_min",
2029 synthetic_pred => format!("{result_var}.Count"),
2030 n => n,
2031 },
2032 );
2033 out.push_str(&rendered);
2034 }
2035 }
2036 }
2037 "not_empty" => {
2038 let rendered = crate::template_env::render(
2039 "csharp/assertion.jinja",
2040 minijinja::context! {
2041 assertion_type => "synthetic_embeddings_not_empty",
2042 synthetic_pred => result_var.to_string(),
2043 },
2044 );
2045 out.push_str(&rendered);
2046 }
2047 "is_empty" => {
2048 let rendered = crate::template_env::render(
2049 "csharp/assertion.jinja",
2050 minijinja::context! {
2051 assertion_type => "synthetic_embeddings_is_empty",
2052 synthetic_pred => result_var.to_string(),
2053 },
2054 );
2055 out.push_str(&rendered);
2056 }
2057 _ => {
2058 out.push_str(
2059 " // skipped: unsupported assertion type on synthetic field 'embeddings'\n",
2060 );
2061 }
2062 }
2063 return;
2064 }
2065 "embedding_dimensions" => {
2066 let expr = format!("({result_var}.Count > 0 ? {result_var}[0].Count : 0)");
2067 match assertion.assertion_type.as_str() {
2068 "equals" => {
2069 if let Some(val) = &assertion.value {
2070 if let Some(n) = val.as_u64() {
2071 let rendered = crate::template_env::render(
2072 "csharp/assertion.jinja",
2073 minijinja::context! {
2074 assertion_type => "synthetic_embedding_dimensions_equals",
2075 synthetic_pred => expr,
2076 n => n,
2077 },
2078 );
2079 out.push_str(&rendered);
2080 }
2081 }
2082 }
2083 "greater_than" => {
2084 if let Some(val) = &assertion.value {
2085 if let Some(n) = val.as_u64() {
2086 let rendered = crate::template_env::render(
2087 "csharp/assertion.jinja",
2088 minijinja::context! {
2089 assertion_type => "synthetic_embedding_dimensions_greater_than",
2090 synthetic_pred => expr,
2091 n => n,
2092 },
2093 );
2094 out.push_str(&rendered);
2095 }
2096 }
2097 }
2098 _ => {
2099 out.push_str(" // skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n");
2100 }
2101 }
2102 return;
2103 }
2104 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
2105 let synthetic_pred = match f.as_str() {
2106 "embeddings_valid" => {
2107 format!("{result_var}.All(e => e.Count > 0)")
2108 }
2109 "embeddings_finite" => {
2110 format!("{result_var}.All(e => e.All(v => !float.IsInfinity(v) && !float.IsNaN(v)))")
2111 }
2112 "embeddings_non_zero" => {
2113 format!("{result_var}.All(e => e.Any(v => v != 0.0f))")
2114 }
2115 "embeddings_normalized" => {
2116 format!(
2117 "{result_var}.All(e => {{ var n = e.Sum(v => (double)v * v); return Math.Abs(n - 1.0) < 1e-3; }})"
2118 )
2119 }
2120 _ => unreachable!(),
2121 };
2122 let synthetic_pred_type = match assertion.assertion_type.as_str() {
2123 "is_true" => "is_true",
2124 "is_false" => "is_false",
2125 _ => {
2126 out.push_str(&format!(
2127 " // skipped: unsupported assertion type on synthetic field '{f}'\n"
2128 ));
2129 return;
2130 }
2131 };
2132 let rendered = crate::template_env::render(
2133 "csharp/assertion.jinja",
2134 minijinja::context! {
2135 assertion_type => "synthetic_assertion",
2136 synthetic_pred => synthetic_pred,
2137 synthetic_pred_type => synthetic_pred_type,
2138 },
2139 );
2140 out.push_str(&rendered);
2141 return;
2142 }
2143 "keywords" | "keywords_count" => {
2146 let skipped_reason = format!("field '{f}' not available on C# ExtractionResult");
2147 let rendered = crate::template_env::render(
2148 "csharp/assertion.jinja",
2149 minijinja::context! {
2150 skipped_reason => skipped_reason,
2151 },
2152 );
2153 out.push_str(&rendered);
2154 return;
2155 }
2156 _ => {}
2157 }
2158 }
2159
2160 if let Some(f) = &assertion.field {
2162 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
2163 let skipped_reason = format!("field '{f}' not available on result type");
2164 let rendered = crate::template_env::render(
2165 "csharp/assertion.jinja",
2166 minijinja::context! {
2167 skipped_reason => skipped_reason,
2168 },
2169 );
2170 out.push_str(&rendered);
2171 return;
2172 }
2173 }
2174
2175 let is_count_assertion = matches!(
2178 assertion.assertion_type.as_str(),
2179 "count_equals" | "count_min" | "count_max"
2180 );
2181 let is_no_field = assertion.field.is_none() || assertion.field.as_ref().is_some_and(|f| f.is_empty());
2182 let use_list_directly = result_is_vec && is_count_assertion && is_no_field;
2183
2184 let effective_result_var: String = if result_is_vec && !use_list_directly {
2185 format!("{result_var}[0]")
2186 } else {
2187 result_var.to_string()
2188 };
2189
2190 let is_discriminated_union = assertion
2192 .field
2193 .as_ref()
2194 .is_some_and(|f| parse_discriminated_union_access(f).is_some());
2195
2196 if is_discriminated_union {
2198 if let Some((_, variant_name, inner_field)) = assertion
2199 .field
2200 .as_ref()
2201 .and_then(|f| parse_discriminated_union_access(f))
2202 {
2203 let mut hasher = std::collections::hash_map::DefaultHasher::new();
2205 inner_field.hash(&mut hasher);
2206 let var_hash = format!("{:x}", hasher.finish());
2207 let variant_var = format!("variant_{}", &var_hash[..8]);
2208 let _ = writeln!(
2209 out,
2210 " if ({effective_result_var}.Metadata.Format is FormatMetadata.{} {})",
2211 variant_name, &variant_var
2212 );
2213 let _ = writeln!(out, " {{");
2214 render_discriminated_union_assertion(out, assertion, &variant_var, &inner_field, result_is_vec);
2215 let _ = writeln!(out, " }}");
2216 let _ = writeln!(out, " else");
2217 let _ = writeln!(out, " {{");
2218 let _ = writeln!(
2219 out,
2220 " Assert.Fail(\"Expected {} format metadata\");",
2221 variant_name.to_lowercase()
2222 );
2223 let _ = writeln!(out, " }}");
2224 return;
2225 }
2226 }
2227
2228 let field_expr = if result_is_simple {
2229 effective_result_var.clone()
2230 } else {
2231 match &assertion.field {
2232 Some(f) if !f.is_empty() => field_resolver.accessor(f, "csharp", &effective_result_var),
2233 _ => effective_result_var.clone(),
2234 }
2235 };
2236
2237 let field_needs_json_serialize = if result_is_simple {
2241 result_is_array
2244 } else {
2245 match &assertion.field {
2246 Some(f) if !f.is_empty() => field_resolver.is_array(f),
2247 _ => !result_is_simple,
2249 }
2250 };
2251 let field_as_str = if field_needs_json_serialize {
2253 format!("JsonSerializer.Serialize({field_expr})")
2254 } else {
2255 format!("{field_expr}.ToString()")
2256 };
2257
2258 let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
2262 let resolved = field_resolver.resolve(f);
2263 fields_enum.contains(f) || fields_enum.contains(resolved)
2264 });
2265
2266 match assertion.assertion_type.as_str() {
2267 "equals" => {
2268 if let Some(expected) = &assertion.value {
2269 if field_is_enum && expected.is_string() {
2276 let s_lower = expected.as_str().map(|s| s.to_lowercase()).unwrap_or_default();
2277 let _ = writeln!(
2278 out,
2279 " Assert.Equal(\"{}\", {field_expr} == null ? null : JsonNamingPolicy.SnakeCaseLower.ConvertName({field_expr}.ToString()!));",
2280 escape_csharp(&s_lower)
2281 );
2282 return;
2283 }
2284 let cs_val = json_to_csharp(expected);
2285 let is_string_val = expected.is_string();
2286 let is_bool_true = expected.as_bool() == Some(true);
2287 let is_bool_false = expected.as_bool() == Some(false);
2288 let is_integer_val = expected.is_number() && !expected.as_f64().is_some_and(|f| f.fract() != 0.0);
2289
2290 let rendered = crate::template_env::render(
2291 "csharp/assertion.jinja",
2292 minijinja::context! {
2293 assertion_type => "equals",
2294 field_expr => field_expr.clone(),
2295 cs_val => cs_val,
2296 is_string_val => is_string_val,
2297 is_bool_true => is_bool_true,
2298 is_bool_false => is_bool_false,
2299 is_integer_val => is_integer_val,
2300 },
2301 );
2302 out.push_str(&rendered);
2303 }
2304 }
2305 "contains" => {
2306 if let Some(expected) = &assertion.value {
2307 let lower_expected = expected.as_str().map(|s| s.to_lowercase());
2314 let cs_val = lower_expected
2315 .as_deref()
2316 .map(|s| format!("\"{}\"", escape_csharp(s)))
2317 .unwrap_or_else(|| json_to_csharp(expected));
2318
2319 let rendered = crate::template_env::render(
2320 "csharp/assertion.jinja",
2321 minijinja::context! {
2322 assertion_type => "contains",
2323 field_as_str => field_as_str.clone(),
2324 cs_val => cs_val,
2325 },
2326 );
2327 out.push_str(&rendered);
2328 }
2329 }
2330 "contains_all" => {
2331 if let Some(values) = &assertion.values {
2332 let values_cs_lower: Vec<String> = values
2333 .iter()
2334 .map(|val| {
2335 let lower_val = val.as_str().map(|s| s.to_lowercase());
2336 lower_val
2337 .as_deref()
2338 .map(|s| format!("\"{}\"", escape_csharp(s)))
2339 .unwrap_or_else(|| json_to_csharp(val))
2340 })
2341 .collect();
2342
2343 let rendered = crate::template_env::render(
2344 "csharp/assertion.jinja",
2345 minijinja::context! {
2346 assertion_type => "contains_all",
2347 field_as_str => field_as_str.clone(),
2348 values_cs_lower => values_cs_lower,
2349 },
2350 );
2351 out.push_str(&rendered);
2352 }
2353 }
2354 "not_contains" => {
2355 if let Some(expected) = &assertion.value {
2356 let cs_val = json_to_csharp(expected);
2357
2358 let rendered = crate::template_env::render(
2359 "csharp/assertion.jinja",
2360 minijinja::context! {
2361 assertion_type => "not_contains",
2362 field_as_str => field_as_str.clone(),
2363 cs_val => cs_val,
2364 },
2365 );
2366 out.push_str(&rendered);
2367 }
2368 }
2369 "not_empty" => {
2370 let rendered = crate::template_env::render(
2371 "csharp/assertion.jinja",
2372 minijinja::context! {
2373 assertion_type => "not_empty",
2374 field_expr => field_expr.clone(),
2375 field_needs_json_serialize => field_needs_json_serialize,
2376 },
2377 );
2378 out.push_str(&rendered);
2379 }
2380 "is_empty" => {
2381 let rendered = crate::template_env::render(
2382 "csharp/assertion.jinja",
2383 minijinja::context! {
2384 assertion_type => "is_empty",
2385 field_expr => field_expr.clone(),
2386 field_needs_json_serialize => field_needs_json_serialize,
2387 },
2388 );
2389 out.push_str(&rendered);
2390 }
2391 "contains_any" => {
2392 if let Some(values) = &assertion.values {
2393 let checks: Vec<String> = values
2394 .iter()
2395 .map(|v| {
2396 let cs_val = json_to_csharp(v);
2397 format!("{field_as_str}.Contains({cs_val})")
2398 })
2399 .collect();
2400 let contains_any_expr = checks.join(" || ");
2401
2402 let rendered = crate::template_env::render(
2403 "csharp/assertion.jinja",
2404 minijinja::context! {
2405 assertion_type => "contains_any",
2406 contains_any_expr => contains_any_expr,
2407 },
2408 );
2409 out.push_str(&rendered);
2410 }
2411 }
2412 "greater_than" => {
2413 if let Some(val) = &assertion.value {
2414 let cs_val = json_to_csharp(val);
2415
2416 let rendered = crate::template_env::render(
2417 "csharp/assertion.jinja",
2418 minijinja::context! {
2419 assertion_type => "greater_than",
2420 field_expr => field_expr.clone(),
2421 cs_val => cs_val,
2422 },
2423 );
2424 out.push_str(&rendered);
2425 }
2426 }
2427 "less_than" => {
2428 if let Some(val) = &assertion.value {
2429 let cs_val = json_to_csharp(val);
2430
2431 let rendered = crate::template_env::render(
2432 "csharp/assertion.jinja",
2433 minijinja::context! {
2434 assertion_type => "less_than",
2435 field_expr => field_expr.clone(),
2436 cs_val => cs_val,
2437 },
2438 );
2439 out.push_str(&rendered);
2440 }
2441 }
2442 "greater_than_or_equal" => {
2443 if let Some(val) = &assertion.value {
2444 let cs_val = json_to_csharp(val);
2445
2446 let rendered = crate::template_env::render(
2447 "csharp/assertion.jinja",
2448 minijinja::context! {
2449 assertion_type => "greater_than_or_equal",
2450 field_expr => field_expr.clone(),
2451 cs_val => cs_val,
2452 },
2453 );
2454 out.push_str(&rendered);
2455 }
2456 }
2457 "less_than_or_equal" => {
2458 if let Some(val) = &assertion.value {
2459 let cs_val = json_to_csharp(val);
2460
2461 let rendered = crate::template_env::render(
2462 "csharp/assertion.jinja",
2463 minijinja::context! {
2464 assertion_type => "less_than_or_equal",
2465 field_expr => field_expr.clone(),
2466 cs_val => cs_val,
2467 },
2468 );
2469 out.push_str(&rendered);
2470 }
2471 }
2472 "starts_with" => {
2473 if let Some(expected) = &assertion.value {
2474 let cs_val = json_to_csharp(expected);
2475
2476 let rendered = crate::template_env::render(
2477 "csharp/assertion.jinja",
2478 minijinja::context! {
2479 assertion_type => "starts_with",
2480 field_expr => field_expr.clone(),
2481 cs_val => cs_val,
2482 },
2483 );
2484 out.push_str(&rendered);
2485 }
2486 }
2487 "ends_with" => {
2488 if let Some(expected) = &assertion.value {
2489 let cs_val = json_to_csharp(expected);
2490
2491 let rendered = crate::template_env::render(
2492 "csharp/assertion.jinja",
2493 minijinja::context! {
2494 assertion_type => "ends_with",
2495 field_expr => field_expr.clone(),
2496 cs_val => cs_val,
2497 },
2498 );
2499 out.push_str(&rendered);
2500 }
2501 }
2502 "min_length" => {
2503 if let Some(val) = &assertion.value {
2504 if let Some(n) = val.as_u64() {
2505 let rendered = crate::template_env::render(
2506 "csharp/assertion.jinja",
2507 minijinja::context! {
2508 assertion_type => "min_length",
2509 field_expr => field_expr.clone(),
2510 n => n,
2511 },
2512 );
2513 out.push_str(&rendered);
2514 }
2515 }
2516 }
2517 "max_length" => {
2518 if let Some(val) = &assertion.value {
2519 if let Some(n) = val.as_u64() {
2520 let rendered = crate::template_env::render(
2521 "csharp/assertion.jinja",
2522 minijinja::context! {
2523 assertion_type => "max_length",
2524 field_expr => field_expr.clone(),
2525 n => n,
2526 },
2527 );
2528 out.push_str(&rendered);
2529 }
2530 }
2531 }
2532 "count_min" => {
2533 if let Some(val) = &assertion.value {
2534 if let Some(n) = val.as_u64() {
2535 let rendered = crate::template_env::render(
2536 "csharp/assertion.jinja",
2537 minijinja::context! {
2538 assertion_type => "count_min",
2539 field_expr => field_expr.clone(),
2540 n => n,
2541 },
2542 );
2543 out.push_str(&rendered);
2544 }
2545 }
2546 }
2547 "count_equals" => {
2548 if let Some(val) = &assertion.value {
2549 if let Some(n) = val.as_u64() {
2550 let rendered = crate::template_env::render(
2551 "csharp/assertion.jinja",
2552 minijinja::context! {
2553 assertion_type => "count_equals",
2554 field_expr => field_expr.clone(),
2555 n => n,
2556 },
2557 );
2558 out.push_str(&rendered);
2559 }
2560 }
2561 }
2562 "is_true" => {
2563 let rendered = crate::template_env::render(
2564 "csharp/assertion.jinja",
2565 minijinja::context! {
2566 assertion_type => "is_true",
2567 field_expr => field_expr.clone(),
2568 },
2569 );
2570 out.push_str(&rendered);
2571 }
2572 "is_false" => {
2573 let rendered = crate::template_env::render(
2574 "csharp/assertion.jinja",
2575 minijinja::context! {
2576 assertion_type => "is_false",
2577 field_expr => field_expr.clone(),
2578 },
2579 );
2580 out.push_str(&rendered);
2581 }
2582 "not_error" => {
2583 let rendered = crate::template_env::render(
2585 "csharp/assertion.jinja",
2586 minijinja::context! {
2587 assertion_type => "not_error",
2588 },
2589 );
2590 out.push_str(&rendered);
2591 }
2592 "error" => {
2593 let rendered = crate::template_env::render(
2595 "csharp/assertion.jinja",
2596 minijinja::context! {
2597 assertion_type => "error",
2598 },
2599 );
2600 out.push_str(&rendered);
2601 }
2602 "method_result" => {
2603 if let Some(method_name) = &assertion.method {
2604 let call_expr = build_csharp_method_call(result_var, method_name, assertion.args.as_ref(), class_name);
2605 let check = assertion.check.as_deref().unwrap_or("is_true");
2606
2607 match check {
2608 "equals" => {
2609 if let Some(val) = &assertion.value {
2610 let is_check_bool_true = val.as_bool() == Some(true);
2611 let is_check_bool_false = val.as_bool() == Some(false);
2612 let cs_check_val = json_to_csharp(val);
2613
2614 let rendered = crate::template_env::render(
2615 "csharp/assertion.jinja",
2616 minijinja::context! {
2617 assertion_type => "method_result",
2618 check => "equals",
2619 call_expr => call_expr.clone(),
2620 is_check_bool_true => is_check_bool_true,
2621 is_check_bool_false => is_check_bool_false,
2622 cs_check_val => cs_check_val,
2623 },
2624 );
2625 out.push_str(&rendered);
2626 }
2627 }
2628 "is_true" => {
2629 let rendered = crate::template_env::render(
2630 "csharp/assertion.jinja",
2631 minijinja::context! {
2632 assertion_type => "method_result",
2633 check => "is_true",
2634 call_expr => call_expr.clone(),
2635 },
2636 );
2637 out.push_str(&rendered);
2638 }
2639 "is_false" => {
2640 let rendered = crate::template_env::render(
2641 "csharp/assertion.jinja",
2642 minijinja::context! {
2643 assertion_type => "method_result",
2644 check => "is_false",
2645 call_expr => call_expr.clone(),
2646 },
2647 );
2648 out.push_str(&rendered);
2649 }
2650 "greater_than_or_equal" => {
2651 if let Some(val) = &assertion.value {
2652 let check_n = val.as_u64().unwrap_or(0);
2653
2654 let rendered = crate::template_env::render(
2655 "csharp/assertion.jinja",
2656 minijinja::context! {
2657 assertion_type => "method_result",
2658 check => "greater_than_or_equal",
2659 call_expr => call_expr.clone(),
2660 check_n => check_n,
2661 },
2662 );
2663 out.push_str(&rendered);
2664 }
2665 }
2666 "count_min" => {
2667 if let Some(val) = &assertion.value {
2668 let check_n = val.as_u64().unwrap_or(0);
2669
2670 let rendered = crate::template_env::render(
2671 "csharp/assertion.jinja",
2672 minijinja::context! {
2673 assertion_type => "method_result",
2674 check => "count_min",
2675 call_expr => call_expr.clone(),
2676 check_n => check_n,
2677 },
2678 );
2679 out.push_str(&rendered);
2680 }
2681 }
2682 "is_error" => {
2683 let rendered = crate::template_env::render(
2684 "csharp/assertion.jinja",
2685 minijinja::context! {
2686 assertion_type => "method_result",
2687 check => "is_error",
2688 call_expr => call_expr.clone(),
2689 exception_class => exception_class,
2690 },
2691 );
2692 out.push_str(&rendered);
2693 }
2694 "contains" => {
2695 if let Some(val) = &assertion.value {
2696 let cs_check_val = json_to_csharp(val);
2697
2698 let rendered = crate::template_env::render(
2699 "csharp/assertion.jinja",
2700 minijinja::context! {
2701 assertion_type => "method_result",
2702 check => "contains",
2703 call_expr => call_expr.clone(),
2704 cs_check_val => cs_check_val,
2705 },
2706 );
2707 out.push_str(&rendered);
2708 }
2709 }
2710 other_check => {
2711 panic!("C# e2e generator: unsupported method_result check type: {other_check}");
2712 }
2713 }
2714 } else {
2715 panic!("C# e2e generator: method_result assertion missing 'method' field");
2716 }
2717 }
2718 "matches_regex" => {
2719 if let Some(expected) = &assertion.value {
2720 let cs_val = json_to_csharp(expected);
2721
2722 let rendered = crate::template_env::render(
2723 "csharp/assertion.jinja",
2724 minijinja::context! {
2725 assertion_type => "matches_regex",
2726 field_expr => field_expr.clone(),
2727 cs_val => cs_val,
2728 },
2729 );
2730 out.push_str(&rendered);
2731 }
2732 }
2733 other => {
2734 panic!("C# e2e generator: unsupported assertion type: {other}");
2735 }
2736 }
2737}
2738
2739fn sort_discriminator_first(value: serde_json::Value) -> serde_json::Value {
2746 match value {
2747 serde_json::Value::Object(map) => {
2748 let mut sorted = serde_json::Map::with_capacity(map.len());
2749 if let Some(type_val) = map.get("type") {
2751 sorted.insert("type".to_string(), sort_discriminator_first(type_val.clone()));
2752 }
2753 for (k, v) in map {
2754 if k != "type" {
2755 sorted.insert(k, sort_discriminator_first(v));
2756 }
2757 }
2758 serde_json::Value::Object(sorted)
2759 }
2760 serde_json::Value::Array(arr) => {
2761 serde_json::Value::Array(arr.into_iter().map(sort_discriminator_first).collect())
2762 }
2763 other => other,
2764 }
2765}
2766
2767fn json_to_csharp(value: &serde_json::Value) -> String {
2769 match value {
2770 serde_json::Value::String(s) => format!("\"{}\"", escape_csharp(s)),
2771 serde_json::Value::Bool(true) => "true".to_string(),
2772 serde_json::Value::Bool(false) => "false".to_string(),
2773 serde_json::Value::Number(n) => {
2774 if n.is_f64() {
2775 format!("{}d", n)
2776 } else {
2777 n.to_string()
2778 }
2779 }
2780 serde_json::Value::Null => "null".to_string(),
2781 serde_json::Value::Array(arr) => {
2782 let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2783 format!("new[] {{ {} }}", items.join(", "))
2784 }
2785 serde_json::Value::Object(_) => {
2786 let json_str = serde_json::to_string(value).unwrap_or_default();
2787 format!("\"{}\"", escape_csharp(&json_str))
2788 }
2789 }
2790}
2791
2792fn default_csharp_nested_types() -> HashMap<String, String> {
2799 [
2800 ("chunking", "ChunkingConfig"),
2801 ("ocr", "OcrConfig"),
2802 ("images", "ImageExtractionConfig"),
2803 ("html_output", "HtmlOutputConfig"),
2804 ("language_detection", "LanguageDetectionConfig"),
2805 ("postprocessor", "PostProcessorConfig"),
2806 ("acceleration", "AccelerationConfig"),
2807 ("email", "EmailConfig"),
2808 ("pages", "PageConfig"),
2809 ("pdf_options", "PdfConfig"),
2810 ("layout", "LayoutDetectionConfig"),
2811 ("tree_sitter", "TreeSitterConfig"),
2812 ("structured_extraction", "StructuredExtractionConfig"),
2813 ("content_filter", "ContentFilterConfig"),
2814 ("token_reduction", "TokenReductionOptions"),
2815 ("security_limits", "SecurityLimits"),
2816 ("format", "FormatMetadata"),
2817 ("model", "EmbeddingModelType"),
2818 ]
2819 .iter()
2820 .map(|(k, v)| (k.to_string(), v.to_string()))
2821 .collect()
2822}
2823
2824fn csharp_object_initializer(
2832 obj: &serde_json::Map<String, serde_json::Value>,
2833 type_name: &str,
2834 enum_fields: &HashMap<String, String>,
2835 nested_types: &HashMap<String, String>,
2836) -> String {
2837 if obj.is_empty() {
2838 return format!("new {type_name}()");
2839 }
2840
2841 static IMPLICIT_ENUM_FIELDS: &[(&str, &str)] = &[("output_format", "OutputFormat")];
2844
2845 let props: Vec<String> = obj
2846 .iter()
2847 .map(|(key, val)| {
2848 let pascal_key = key.to_upper_camel_case();
2849 let implicit_enum_type = IMPLICIT_ENUM_FIELDS
2850 .iter()
2851 .find(|(k, _)| *k == key.as_str())
2852 .map(|(_, t)| *t);
2853 let camel_key = key.to_lower_camel_case();
2857 let cs_val = if let Some(enum_type) = enum_fields
2858 .get(key.as_str())
2859 .or_else(|| enum_fields.get(camel_key.as_str()))
2860 .map(String::as_str)
2861 .or(implicit_enum_type)
2862 {
2863 if val.is_null() {
2865 "null".to_string()
2866 } else {
2867 let member = val
2868 .as_str()
2869 .map(|s| s.to_upper_camel_case())
2870 .unwrap_or_else(|| "null".to_string());
2871 format!("{enum_type}.{member}")
2872 }
2873 } else if let Some(nested_type) = nested_types
2874 .get(key.as_str())
2875 .or_else(|| nested_types.get(camel_key.as_str()))
2876 {
2877 let normalized = normalize_csharp_enum_values(val, enum_fields);
2879 let json_str = serde_json::to_string(&normalized).unwrap_or_default();
2880 format!(
2881 "JsonSerializer.Deserialize<{nested_type}>(\"{}\", ConfigOptions)!",
2882 escape_csharp(&json_str)
2883 )
2884 } else if let Some(arr) = val.as_array() {
2885 let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
2887 format!("new List<string> {{ {} }}", items.join(", "))
2888 } else {
2889 json_to_csharp(val)
2890 };
2891 format!("{pascal_key} = {cs_val}")
2892 })
2893 .collect();
2894 format!("new {} {{ {} }}", type_name, props.join(", "))
2895}
2896
2897fn normalize_csharp_enum_values(value: &serde_json::Value, enum_fields: &HashMap<String, String>) -> serde_json::Value {
2902 match value {
2903 serde_json::Value::Object(map) => {
2904 let mut result = map.clone();
2905 for (key, val) in result.iter_mut() {
2906 let camel_key = key.to_lower_camel_case();
2909 if enum_fields.contains_key(key) || enum_fields.contains_key(camel_key.as_str()) {
2910 if let Some(s) = val.as_str() {
2912 *val = serde_json::Value::String(s.to_lowercase());
2913 }
2914 }
2915 }
2916 serde_json::Value::Object(result)
2917 }
2918 other => other.clone(),
2919 }
2920}
2921
2922fn build_csharp_visitor(
2933 setup_lines: &mut Vec<String>,
2934 class_decls: &mut Vec<String>,
2935 fixture_id: &str,
2936 visitor_spec: &crate::fixture::VisitorSpec,
2937) -> String {
2938 use heck::ToUpperCamelCase;
2939 let class_name = format!("{}Visitor", fixture_id.to_upper_camel_case());
2940 let var_name = format!("_visitor_{}", fixture_id.replace('-', "_"));
2941
2942 setup_lines.push(format!("var {var_name} = new {class_name}();"));
2943
2944 let mut decl = String::new();
2946 decl.push_str(&format!(" private sealed class {class_name} : IHtmlVisitor\n"));
2947 decl.push_str(" {\n");
2948
2949 let all_methods = [
2951 "visit_element_start",
2952 "visit_element_end",
2953 "visit_text",
2954 "visit_link",
2955 "visit_image",
2956 "visit_heading",
2957 "visit_code_block",
2958 "visit_code_inline",
2959 "visit_list_item",
2960 "visit_list_start",
2961 "visit_list_end",
2962 "visit_table_start",
2963 "visit_table_row",
2964 "visit_table_end",
2965 "visit_blockquote",
2966 "visit_strong",
2967 "visit_emphasis",
2968 "visit_strikethrough",
2969 "visit_underline",
2970 "visit_subscript",
2971 "visit_superscript",
2972 "visit_mark",
2973 "visit_line_break",
2974 "visit_horizontal_rule",
2975 "visit_custom_element",
2976 "visit_definition_list_start",
2977 "visit_definition_term",
2978 "visit_definition_description",
2979 "visit_definition_list_end",
2980 "visit_form",
2981 "visit_input",
2982 "visit_button",
2983 "visit_audio",
2984 "visit_video",
2985 "visit_iframe",
2986 "visit_details",
2987 "visit_summary",
2988 "visit_figure_start",
2989 "visit_figcaption",
2990 "visit_figure_end",
2991 ];
2992
2993 for method_name in &all_methods {
2995 if let Some(action) = visitor_spec.callbacks.get(*method_name) {
2996 emit_csharp_visitor_method(&mut decl, method_name, action);
2997 } else {
2998 emit_csharp_visitor_method(&mut decl, method_name, &CallbackAction::Continue);
3000 }
3001 }
3002
3003 decl.push_str(" }\n");
3004 class_decls.push(decl);
3005
3006 var_name
3007}
3008
3009fn emit_csharp_visitor_method(decl: &mut String, method_name: &str, action: &CallbackAction) {
3011 let camel_method = method_to_camel(method_name);
3012 let params = match method_name {
3013 "visit_link" => "NodeContext ctx, string href, string text, string title",
3014 "visit_image" => "NodeContext ctx, string src, string alt, string title",
3015 "visit_heading" => "NodeContext ctx, uint level, string text, string id",
3016 "visit_code_block" => "NodeContext ctx, string lang, string code",
3017 "visit_code_inline"
3018 | "visit_strong"
3019 | "visit_emphasis"
3020 | "visit_strikethrough"
3021 | "visit_underline"
3022 | "visit_subscript"
3023 | "visit_superscript"
3024 | "visit_mark"
3025 | "visit_button"
3026 | "visit_summary"
3027 | "visit_figcaption"
3028 | "visit_definition_term"
3029 | "visit_definition_description" => "NodeContext ctx, string text",
3030 "visit_text" => "NodeContext ctx, string text",
3031 "visit_list_item" => "NodeContext ctx, bool ordered, string marker, string text",
3032 "visit_blockquote" => "NodeContext ctx, string content, ulong depth",
3033 "visit_table_row" => "NodeContext ctx, List<string> cells, bool isHeader",
3034 "visit_custom_element" => "NodeContext ctx, string tagName, string html",
3035 "visit_form" => "NodeContext ctx, string actionUrl, string method",
3036 "visit_input" => "NodeContext ctx, string inputType, string name, string value",
3037 "visit_audio" | "visit_video" | "visit_iframe" => "NodeContext ctx, string src",
3038 "visit_details" => "NodeContext ctx, bool isOpen",
3039 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
3040 "NodeContext ctx, string output"
3041 }
3042 "visit_list_start" => "NodeContext ctx, bool ordered",
3043 "visit_list_end" => "NodeContext ctx, bool ordered, string output",
3044 "visit_element_start"
3045 | "visit_table_start"
3046 | "visit_definition_list_start"
3047 | "visit_figure_start"
3048 | "visit_line_break"
3049 | "visit_horizontal_rule" => "NodeContext ctx",
3050 _ => "NodeContext ctx",
3051 };
3052
3053 let (action_type, action_value) = match action {
3054 CallbackAction::Skip => ("skip", String::new()),
3055 CallbackAction::Continue => ("continue", String::new()),
3056 CallbackAction::PreserveHtml => ("preserve_html", String::new()),
3057 CallbackAction::Custom { output } => ("custom", escape_csharp(output)),
3058 CallbackAction::CustomTemplate { template, .. } => {
3059 let camel = snake_case_template_to_camel(template);
3060 ("custom_template", escape_csharp(&camel))
3061 }
3062 };
3063
3064 let rendered = crate::template_env::render(
3065 "csharp/visitor_method.jinja",
3066 minijinja::context! {
3067 camel_method => camel_method,
3068 params => params,
3069 action_type => action_type,
3070 action_value => action_value,
3071 },
3072 );
3073 let _ = write!(decl, "{}", rendered);
3074}
3075
3076fn method_to_camel(snake: &str) -> String {
3078 use heck::ToUpperCamelCase;
3079 snake.to_upper_camel_case()
3080}
3081
3082fn snake_case_template_to_camel(template: &str) -> String {
3085 use heck::ToLowerCamelCase;
3086 let mut out = String::with_capacity(template.len());
3087 let mut chars = template.chars().peekable();
3088 while let Some(c) = chars.next() {
3089 if c == '{' {
3090 let mut name = String::new();
3091 while let Some(&nc) = chars.peek() {
3092 if nc == '}' {
3093 chars.next();
3094 break;
3095 }
3096 name.push(nc);
3097 chars.next();
3098 }
3099 out.push('{');
3100 out.push_str(&name.to_lower_camel_case());
3101 out.push('}');
3102 } else {
3103 out.push(c);
3104 }
3105 }
3106 out
3107}
3108
3109fn build_csharp_method_call(
3114 result_var: &str,
3115 method_name: &str,
3116 args: Option<&serde_json::Value>,
3117 class_name: &str,
3118) -> String {
3119 match method_name {
3120 "root_child_count" => format!("{result_var}.RootNode.ChildCount"),
3121 "root_node_type" => format!("{result_var}.RootNode.Kind"),
3122 "named_children_count" => format!("{result_var}.RootNode.NamedChildCount"),
3123 "has_error_nodes" => format!("{class_name}.TreeHasErrorNodes({result_var})"),
3124 "error_count" | "tree_error_count" => format!("{class_name}.TreeErrorCount({result_var})"),
3125 "tree_to_sexp" => format!("{class_name}.TreeToSexp({result_var})"),
3126 "contains_node_type" => {
3127 let node_type = args
3128 .and_then(|a| a.get("node_type"))
3129 .and_then(|v| v.as_str())
3130 .unwrap_or("");
3131 format!("{class_name}.TreeContainsNodeType({result_var}, \"{node_type}\")")
3132 }
3133 "find_nodes_by_type" => {
3134 let node_type = args
3135 .and_then(|a| a.get("node_type"))
3136 .and_then(|v| v.as_str())
3137 .unwrap_or("");
3138 format!("{class_name}.FindNodesByType({result_var}, \"{node_type}\")")
3139 }
3140 "run_query" => {
3141 let query_source = args
3142 .and_then(|a| a.get("query_source"))
3143 .and_then(|v| v.as_str())
3144 .unwrap_or("");
3145 let language = args
3146 .and_then(|a| a.get("language"))
3147 .and_then(|v| v.as_str())
3148 .unwrap_or("");
3149 format!("{class_name}.RunQuery({result_var}, \"{language}\", \"{query_source}\", source)")
3150 }
3151 _ => {
3152 use heck::ToUpperCamelCase;
3153 let pascal = method_name.to_upper_camel_case();
3154 format!("{result_var}.{pascal}()")
3155 }
3156 }
3157}
3158
3159fn fixture_has_csharp_callable(fixture: &Fixture, e2e_config: &E2eConfig) -> bool {
3160 if fixture.is_http_test() {
3162 return false;
3163 }
3164 let call_config = e2e_config.resolve_call_for_fixture(
3166 fixture.call.as_deref(),
3167 &fixture.id,
3168 &fixture.resolved_category(),
3169 &fixture.tags,
3170 &fixture.input,
3171 );
3172 let cs_override = call_config
3173 .overrides
3174 .get("csharp")
3175 .or_else(|| e2e_config.call.overrides.get("csharp"));
3176 if cs_override.and_then(|o| o.client_factory.as_deref()).is_some() {
3178 return true;
3179 }
3180 cs_override.and_then(|o| o.function.as_deref()).is_some() || !call_config.function.is_empty()
3183}
3184
3185fn classify_bytes_value_csharp(s: &str) -> String {
3188 if let Some(first) = s.chars().next() {
3191 if first.is_ascii_alphanumeric() || first == '_' {
3192 if let Some(slash_pos) = s.find('/') {
3193 if slash_pos > 0 {
3194 let after_slash = &s[slash_pos + 1..];
3195 if after_slash.contains('.') && !after_slash.is_empty() {
3196 return format!("System.IO.File.ReadAllBytes(\"{}\")", s);
3198 }
3199 }
3200 }
3201 }
3202 }
3203
3204 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
3207 return format!("System.Text.Encoding.UTF8.GetBytes(\"{}\")", escape_csharp(s));
3209 }
3210
3211 format!("System.Convert.FromBase64String(\"{}\")", s)
3215}
3216
3217#[cfg(test)]
3218mod tests {
3219 use crate::config::{CallConfig, E2eConfig, SelectWhen};
3220 use crate::fixture::Fixture;
3221 use std::collections::HashMap;
3222
3223 fn make_fixture_with_input(id: &str, input: serde_json::Value) -> Fixture {
3224 Fixture {
3225 id: id.to_string(),
3226 category: None,
3227 description: "test fixture".to_string(),
3228 tags: vec![],
3229 skip: None,
3230 env: None,
3231 call: None,
3232 input,
3233 mock_response: None,
3234 source: String::new(),
3235 http: None,
3236 assertions: vec![],
3237 visitor: None,
3238 }
3239 }
3240
3241 #[test]
3244 fn test_csharp_select_when_routes_to_batch_scrape() {
3245 let mut calls = HashMap::new();
3246 calls.insert(
3247 "batch_scrape".to_string(),
3248 CallConfig {
3249 function: "BatchScrape".to_string(),
3250 module: "KreuzBrowser".to_string(),
3251 select_when: Some(SelectWhen {
3252 input_has: Some("batch_urls".to_string()),
3253 ..Default::default()
3254 }),
3255 ..CallConfig::default()
3256 },
3257 );
3258
3259 let e2e_config = E2eConfig {
3260 call: CallConfig {
3261 function: "Scrape".to_string(),
3262 module: "KreuzBrowser".to_string(),
3263 ..CallConfig::default()
3264 },
3265 calls,
3266 ..E2eConfig::default()
3267 };
3268
3269 let fixture = make_fixture_with_input("batch_empty_urls", serde_json::json!({ "batch_urls": [] }));
3271
3272 let resolved_call = e2e_config.resolve_call_for_fixture(
3273 fixture.call.as_deref(),
3274 &fixture.id,
3275 &fixture.resolved_category(),
3276 &fixture.tags,
3277 &fixture.input,
3278 );
3279 assert_eq!(resolved_call.function, "BatchScrape");
3280
3281 let fixture_no_batch =
3283 make_fixture_with_input("simple_scrape", serde_json::json!({ "url": "https://example.com" }));
3284 let resolved_default = e2e_config.resolve_call_for_fixture(
3285 fixture_no_batch.call.as_deref(),
3286 &fixture_no_batch.id,
3287 &fixture_no_batch.resolved_category(),
3288 &fixture_no_batch.tags,
3289 &fixture_no_batch.input,
3290 );
3291 assert_eq!(resolved_default.function, "Scrape");
3292 }
3293}