Skip to main content

alef_e2e/codegen/
csharp.rs

1//! C# e2e test generator using xUnit.
2//!
3//! Generates `e2e/csharp/E2eTests.csproj` and `tests/{Category}Tests.cs`
4//! files from JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::config::E2eConfig;
7use crate::escape::{escape_csharp, sanitize_filename};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, Fixture, FixtureGroup};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::AlefConfig;
12use anyhow::Result;
13use heck::ToUpperCamelCase;
14use std::collections::HashMap;
15use std::fmt::Write as FmtWrite;
16use std::path::PathBuf;
17
18use super::E2eCodegen;
19
20/// C# e2e code generator.
21pub struct CSharpCodegen;
22
23impl E2eCodegen for CSharpCodegen {
24    fn generate(
25        &self,
26        groups: &[FixtureGroup],
27        e2e_config: &E2eConfig,
28        alef_config: &AlefConfig,
29    ) -> Result<Vec<GeneratedFile>> {
30        let lang = self.language_name();
31        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
32
33        let mut files = Vec::new();
34
35        // Resolve call config with overrides.
36        let call = &e2e_config.call;
37        let overrides = call.overrides.get(lang);
38        let function_name = overrides
39            .and_then(|o| o.function.as_ref())
40            .cloned()
41            .unwrap_or_else(|| call.function.to_upper_camel_case());
42        let class_name = overrides
43            .and_then(|o| o.class.as_ref())
44            .cloned()
45            .unwrap_or_else(|| format!("{}Lib", alef_config.crate_config.name.to_upper_camel_case()));
46        // The exception class is always {CrateName}Exception, generated by the C# backend.
47        let exception_class = format!("{}Exception", alef_config.crate_config.name.to_upper_camel_case());
48        let namespace = overrides.and_then(|o| o.module.as_ref()).cloned().unwrap_or_else(|| {
49            if call.module.is_empty() {
50                "Kreuzberg".to_string()
51            } else {
52                call.module.to_upper_camel_case()
53            }
54        });
55        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
56        let result_var = &call.result_var;
57        let is_async = call.r#async;
58
59        // Resolve package config.
60        let cs_pkg = e2e_config.resolve_package("csharp");
61        let pkg_name = cs_pkg
62            .as_ref()
63            .and_then(|p| p.name.as_ref())
64            .cloned()
65            .unwrap_or_else(|| alef_config.crate_config.name.to_upper_camel_case());
66        // The project reference path uses the crate name (with hyphens) for the directory
67        // and the PascalCase name for the .csproj file.
68        let pkg_path = cs_pkg
69            .as_ref()
70            .and_then(|p| p.path.as_ref())
71            .cloned()
72            .unwrap_or_else(|| {
73                let dir_name = &alef_config.crate_config.name;
74                format!("../../packages/csharp/{dir_name}/{pkg_name}.csproj")
75            });
76        let pkg_version = cs_pkg
77            .as_ref()
78            .and_then(|p| p.version.as_ref())
79            .cloned()
80            .unwrap_or_else(|| "0.1.0".to_string());
81
82        // Generate the .csproj using a unique name derived from the package name so
83        // it does not conflict with any hand-written project files in the same directory.
84        let csproj_name = format!("{pkg_name}.E2eTests.csproj");
85        files.push(GeneratedFile {
86            path: output_base.join(&csproj_name),
87            content: render_csproj(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
88            generated_header: false,
89        });
90
91        // Generate test files per category.
92        let tests_base = output_base.join("tests");
93        let field_resolver = FieldResolver::new(
94            &e2e_config.fields,
95            &e2e_config.fields_optional,
96            &e2e_config.result_fields,
97            &e2e_config.fields_array,
98        );
99
100        // Resolve enum_fields from C# override config.
101        static EMPTY_ENUM_FIELDS: std::sync::LazyLock<HashMap<String, String>> = std::sync::LazyLock::new(HashMap::new);
102        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&EMPTY_ENUM_FIELDS);
103
104        for group in groups {
105            let active: Vec<&Fixture> = group
106                .fixtures
107                .iter()
108                .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip(lang)))
109                .collect();
110
111            if active.is_empty() {
112                continue;
113            }
114
115            let test_class = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
116            let filename = format!("{test_class}.cs");
117            let content = render_test_file(
118                &group.category,
119                &active,
120                &namespace,
121                &class_name,
122                &function_name,
123                &exception_class,
124                result_var,
125                &test_class,
126                &e2e_config.call.args,
127                &field_resolver,
128                result_is_simple,
129                is_async,
130                e2e_config,
131                enum_fields,
132            );
133            files.push(GeneratedFile {
134                path: tests_base.join(filename),
135                content,
136                generated_header: true,
137            });
138        }
139
140        Ok(files)
141    }
142
143    fn language_name(&self) -> &'static str {
144        "csharp"
145    }
146}
147
148// ---------------------------------------------------------------------------
149// Rendering
150// ---------------------------------------------------------------------------
151
152fn render_csproj(pkg_name: &str, pkg_path: &str, pkg_version: &str, dep_mode: crate::config::DependencyMode) -> String {
153    let pkg_ref = match dep_mode {
154        crate::config::DependencyMode::Registry => {
155            format!("    <PackageReference Include=\"{pkg_name}\" Version=\"{pkg_version}\" />")
156        }
157        crate::config::DependencyMode::Local => {
158            format!("    <ProjectReference Include=\"{pkg_path}\" />")
159        }
160    };
161    format!(
162        r#"<Project Sdk="Microsoft.NET.Sdk">
163  <PropertyGroup>
164    <TargetFramework>net10.0</TargetFramework>
165    <Nullable>enable</Nullable>
166    <ImplicitUsings>enable</ImplicitUsings>
167    <IsPackable>false</IsPackable>
168    <IsTestProject>true</IsTestProject>
169  </PropertyGroup>
170
171  <ItemGroup>
172    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
173    <PackageReference Include="xunit" Version="2.9.3" />
174    <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
175  </ItemGroup>
176
177  <ItemGroup>
178{pkg_ref}
179  </ItemGroup>
180</Project>
181"#
182    )
183}
184
185#[allow(clippy::too_many_arguments)]
186fn render_test_file(
187    category: &str,
188    fixtures: &[&Fixture],
189    namespace: &str,
190    class_name: &str,
191    function_name: &str,
192    exception_class: &str,
193    result_var: &str,
194    test_class: &str,
195    args: &[crate::config::ArgMapping],
196    field_resolver: &FieldResolver,
197    result_is_simple: bool,
198    is_async: bool,
199    e2e_config: &E2eConfig,
200    enum_fields: &HashMap<String, String>,
201) -> String {
202    let mut out = String::new();
203    let _ = writeln!(out, "// This file is auto-generated by alef. DO NOT EDIT.");
204    // Always import System.Text.Json for the shared JsonOptions field.
205    let _ = writeln!(out, "using System.Text.Json;");
206    let _ = writeln!(out, "using System.Text.Json.Serialization;");
207    let _ = writeln!(out, "using System.Threading.Tasks;");
208    let _ = writeln!(out, "using Xunit;");
209    let _ = writeln!(out, "using {namespace};");
210    let _ = writeln!(out);
211    let _ = writeln!(out, "namespace Kreuzberg.E2e;");
212    let _ = writeln!(out);
213    let _ = writeln!(out, "/// <summary>E2e tests for category: {category}.</summary>");
214    let _ = writeln!(out, "public class {test_class}");
215    let _ = writeln!(out, "{{");
216    // Shared options used when deserializing config JSON in test setup.
217    // Mirrors the options used by the library to ensure enum values round-trip correctly.
218    let _ = writeln!(
219        out,
220        "    private static readonly JsonSerializerOptions ConfigOptions = new() {{ Converters = {{ new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }}, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault }};"
221    );
222    let _ = writeln!(out);
223
224    for (i, fixture) in fixtures.iter().enumerate() {
225        render_test_method(
226            &mut out,
227            fixture,
228            class_name,
229            function_name,
230            exception_class,
231            result_var,
232            args,
233            field_resolver,
234            result_is_simple,
235            is_async,
236            e2e_config,
237            enum_fields,
238        );
239        if i + 1 < fixtures.len() {
240            let _ = writeln!(out);
241        }
242    }
243
244    let _ = writeln!(out, "}}");
245    out
246}
247
248#[allow(clippy::too_many_arguments)]
249fn render_test_method(
250    out: &mut String,
251    fixture: &Fixture,
252    class_name: &str,
253    function_name: &str,
254    exception_class: &str,
255    result_var: &str,
256    args: &[crate::config::ArgMapping],
257    field_resolver: &FieldResolver,
258    result_is_simple: bool,
259    is_async: bool,
260    e2e_config: &E2eConfig,
261    enum_fields: &HashMap<String, String>,
262) {
263    let method_name = fixture.id.to_upper_camel_case();
264    let description = &fixture.description;
265    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
266
267    let (setup_lines, args_str) =
268        build_args_and_setup(&fixture.input, args, class_name, e2e_config, enum_fields, &fixture.id);
269
270    let return_type = if is_async { "async Task" } else { "void" };
271    let await_kw = if is_async { "await " } else { "" };
272
273    let _ = writeln!(out, "    [Fact]");
274    let _ = writeln!(out, "    public {return_type} Test_{method_name}()");
275    let _ = writeln!(out, "    {{");
276    let _ = writeln!(out, "        // {description}");
277
278    for line in &setup_lines {
279        let _ = writeln!(out, "        {line}");
280    }
281
282    if expects_error {
283        if is_async {
284            let _ = writeln!(
285                out,
286                "        await Assert.ThrowsAsync<{exception_class}>(() => {class_name}.{function_name}({args_str}));"
287            );
288        } else {
289            let _ = writeln!(
290                out,
291                "        Assert.Throws<{exception_class}>(() => {class_name}.{function_name}({args_str}));"
292            );
293        }
294        let _ = writeln!(out, "    }}");
295        return;
296    }
297
298    let _ = writeln!(
299        out,
300        "        var {result_var} = {await_kw}{class_name}.{function_name}({args_str});"
301    );
302
303    for assertion in &fixture.assertions {
304        render_assertion(out, assertion, result_var, field_resolver, result_is_simple);
305    }
306
307    let _ = writeln!(out, "    }}");
308}
309
310/// Build setup lines (e.g. handle creation) and the argument list for the function call.
311///
312/// Returns `(setup_lines, args_string)`.
313fn build_args_and_setup(
314    input: &serde_json::Value,
315    args: &[crate::config::ArgMapping],
316    class_name: &str,
317    e2e_config: &E2eConfig,
318    enum_fields: &HashMap<String, String>,
319    fixture_id: &str,
320) -> (Vec<String>, String) {
321    if args.is_empty() {
322        return (Vec::new(), json_to_csharp(input));
323    }
324
325    let overrides = e2e_config.call.overrides.get("csharp");
326    let options_type = overrides.and_then(|o| o.options_type.as_deref());
327
328    let mut setup_lines: Vec<String> = Vec::new();
329    let mut parts: Vec<String> = Vec::new();
330
331    for arg in args {
332        if arg.arg_type == "mock_url" {
333            setup_lines.push(format!(
334                "var {} = Environment.GetEnvironmentVariable(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\";",
335                arg.name,
336            ));
337            parts.push(arg.name.clone());
338            continue;
339        }
340
341        if arg.arg_type == "handle" {
342            // Generate a CreateEngine (or equivalent) call and pass the variable.
343            let constructor_name = format!("Create{}", arg.name.to_upper_camel_case());
344            let config_value = input.get(&arg.field).unwrap_or(&serde_json::Value::Null);
345            if config_value.is_null()
346                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
347            {
348                setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
349            } else {
350                // Sort discriminator fields ("type") to appear first in nested objects so
351                // System.Text.Json [JsonPolymorphic] can find the type discriminator before
352                // reading other properties (a requirement as of .NET 8).
353                let sorted = sort_discriminator_first(config_value.clone());
354                let json_str = serde_json::to_string(&sorted).unwrap_or_default();
355                let name = &arg.name;
356                setup_lines.push(format!(
357                    "var {name}Config = JsonSerializer.Deserialize<CrawlConfig>(\"{}\", ConfigOptions)!;",
358                    escape_csharp(&json_str),
359                ));
360                setup_lines.push(format!(
361                    "var {} = {class_name}.{constructor_name}({name}Config);",
362                    arg.name,
363                    name = name,
364                ));
365            }
366            parts.push(arg.name.clone());
367            continue;
368        }
369
370        let val = input.get(&arg.field);
371        match val {
372            None | Some(serde_json::Value::Null) if arg.optional => {
373                // Optional arg with no fixture value: pass null explicitly since
374                // C# nullable parameters still require an argument at the call site.
375                parts.push("null".to_string());
376                continue;
377            }
378            None | Some(serde_json::Value::Null) => {
379                // Required arg with no fixture value: pass a language-appropriate default.
380                let default_val = match arg.arg_type.as_str() {
381                    "string" => "\"\"".to_string(),
382                    "int" | "integer" => "0".to_string(),
383                    "float" | "number" => "0.0d".to_string(),
384                    "bool" | "boolean" => "false".to_string(),
385                    _ => "null".to_string(),
386                };
387                parts.push(default_val);
388            }
389            Some(v) => {
390                // For json_object args with options_type, construct a typed C# object.
391                if let (Some(opts_type), "json_object") = (options_type, arg.arg_type.as_str()) {
392                    if let Some(obj) = v.as_object() {
393                        let props: Vec<String> = obj
394                            .iter()
395                            .map(|(k, vv)| {
396                                let pascal_key = k.to_upper_camel_case();
397                                // Check if this field maps to an enum type.
398                                let cs_val = if let Some(enum_type) = enum_fields.get(k) {
399                                    // Map string value to enum constant (PascalCase).
400                                    if let Some(s) = vv.as_str() {
401                                        let pascal_val = s.to_upper_camel_case();
402                                        format!("{enum_type}.{pascal_val}")
403                                    } else {
404                                        json_to_csharp(vv)
405                                    }
406                                } else {
407                                    json_to_csharp(vv)
408                                };
409                                format!("{pascal_key} = {cs_val}")
410                            })
411                            .collect();
412                        parts.push(format!("new {opts_type} {{ {} }}", props.join(", ")));
413                        continue;
414                    }
415                }
416                parts.push(json_to_csharp(v));
417            }
418        }
419    }
420
421    (setup_lines, parts.join(", "))
422}
423
424fn render_assertion(
425    out: &mut String,
426    assertion: &Assertion,
427    result_var: &str,
428    field_resolver: &FieldResolver,
429    result_is_simple: bool,
430) {
431    // Skip assertions on fields that don't exist on the result type.
432    if let Some(f) = &assertion.field {
433        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
434            let _ = writeln!(out, "        // skipped: field '{f}' not available on result type");
435            return;
436        }
437    }
438
439    let field_expr = if result_is_simple {
440        result_var.to_string()
441    } else {
442        match &assertion.field {
443            Some(f) if !f.is_empty() => field_resolver.accessor(f, "csharp", result_var),
444            _ => result_var.to_string(),
445        }
446    };
447
448    // Determine whether the field resolves to an optional (nullable) type in C#.
449    let field_is_optional = assertion
450        .field
451        .as_deref()
452        .map(|f| field_resolver.is_optional(field_resolver.resolve(f)))
453        .unwrap_or(false);
454
455    match assertion.assertion_type.as_str() {
456        "equals" => {
457            if let Some(expected) = &assertion.value {
458                let cs_val = json_to_csharp(expected);
459                // Only call .Trim() on string fields, not numeric or boolean ones.
460                if expected.is_string() {
461                    let _ = writeln!(out, "        Assert.Equal({cs_val}, {field_expr}.Trim());");
462                } else if expected.is_number() && field_is_optional {
463                    // Nullable numeric fields require an explicit cast of the expected
464                    // literal so that C# can resolve the overload (e.g. ulong?).
465                    let _ = writeln!(out, "        Assert.Equal((object?){cs_val}, (object?){field_expr});");
466                } else {
467                    let _ = writeln!(out, "        Assert.Equal({cs_val}, {field_expr});");
468                }
469            }
470        }
471        "contains" => {
472            if let Some(expected) = &assertion.value {
473                // Lowercase both expected and actual so that enum fields (where .ToString()
474                // returns the PascalCase C# member name like "Anchor") correctly match
475                // fixture snake_case values like "anchor".  String fields are unaffected
476                // because lowercasing both sides preserves substring matches.
477                let lower_expected = expected.as_str().map(|s| s.to_lowercase());
478                let cs_val = lower_expected
479                    .as_deref()
480                    .map(|s| format!("\"{}\"", escape_csharp(s)))
481                    .unwrap_or_else(|| json_to_csharp(expected));
482                let _ = writeln!(
483                    out,
484                    "        Assert.Contains({cs_val}, {field_expr}.ToString().ToLower());"
485                );
486            }
487        }
488        "contains_all" => {
489            if let Some(values) = &assertion.values {
490                for val in values {
491                    let lower_val = val.as_str().map(|s| s.to_lowercase());
492                    let cs_val = lower_val
493                        .as_deref()
494                        .map(|s| format!("\"{}\"", escape_csharp(s)))
495                        .unwrap_or_else(|| json_to_csharp(val));
496                    let _ = writeln!(
497                        out,
498                        "        Assert.Contains({cs_val}, {field_expr}.ToString().ToLower());"
499                    );
500                }
501            }
502        }
503        "not_contains" => {
504            if let Some(expected) = &assertion.value {
505                let cs_val = json_to_csharp(expected);
506                let _ = writeln!(out, "        Assert.DoesNotContain({cs_val}, {field_expr}.ToString());");
507            }
508        }
509        "not_empty" => {
510            let _ = writeln!(
511                out,
512                "        Assert.False(string.IsNullOrEmpty({field_expr}?.ToString()));"
513            );
514        }
515        "is_empty" => {
516            let _ = writeln!(
517                out,
518                "        Assert.True(string.IsNullOrEmpty({field_expr}?.ToString()));"
519            );
520        }
521        "contains_any" => {
522            if let Some(values) = &assertion.values {
523                let checks: Vec<String> = values
524                    .iter()
525                    .map(|v| {
526                        let cs_val = json_to_csharp(v);
527                        format!("{field_expr}.ToString().Contains({cs_val})")
528                    })
529                    .collect();
530                let joined = checks.join(" || ");
531                let _ = writeln!(
532                    out,
533                    "        Assert.True({joined}, \"expected to contain at least one of the specified values\");"
534                );
535            }
536        }
537        "greater_than" => {
538            if let Some(val) = &assertion.value {
539                let cs_val = json_to_csharp(val);
540                let _ = writeln!(
541                    out,
542                    "        Assert.True({field_expr} > {cs_val}, \"expected > {cs_val}\");"
543                );
544            }
545        }
546        "less_than" => {
547            if let Some(val) = &assertion.value {
548                let cs_val = json_to_csharp(val);
549                let _ = writeln!(
550                    out,
551                    "        Assert.True({field_expr} < {cs_val}, \"expected < {cs_val}\");"
552                );
553            }
554        }
555        "greater_than_or_equal" => {
556            if let Some(val) = &assertion.value {
557                let cs_val = json_to_csharp(val);
558                let _ = writeln!(
559                    out,
560                    "        Assert.True({field_expr} >= {cs_val}, \"expected >= {cs_val}\");"
561                );
562            }
563        }
564        "less_than_or_equal" => {
565            if let Some(val) = &assertion.value {
566                let cs_val = json_to_csharp(val);
567                let _ = writeln!(
568                    out,
569                    "        Assert.True({field_expr} <= {cs_val}, \"expected <= {cs_val}\");"
570                );
571            }
572        }
573        "starts_with" => {
574            if let Some(expected) = &assertion.value {
575                let cs_val = json_to_csharp(expected);
576                let _ = writeln!(out, "        Assert.StartsWith({cs_val}, {field_expr});");
577            }
578        }
579        "ends_with" => {
580            if let Some(expected) = &assertion.value {
581                let cs_val = json_to_csharp(expected);
582                let _ = writeln!(out, "        Assert.EndsWith({cs_val}, {field_expr});");
583            }
584        }
585        "min_length" => {
586            if let Some(val) = &assertion.value {
587                if let Some(n) = val.as_u64() {
588                    let _ = writeln!(
589                        out,
590                        "        Assert.True({field_expr}.Length >= {n}, \"expected length >= {n}\");"
591                    );
592                }
593            }
594        }
595        "max_length" => {
596            if let Some(val) = &assertion.value {
597                if let Some(n) = val.as_u64() {
598                    let _ = writeln!(
599                        out,
600                        "        Assert.True({field_expr}.Length <= {n}, \"expected length <= {n}\");"
601                    );
602                }
603            }
604        }
605        "count_min" => {
606            if let Some(val) = &assertion.value {
607                if let Some(n) = val.as_u64() {
608                    let _ = writeln!(
609                        out,
610                        "        Assert.True({field_expr}.Count >= {n}, \"expected at least {n} elements\");"
611                    );
612                }
613            }
614        }
615        "not_error" => {
616            // Already handled by the call succeeding without exception.
617        }
618        "error" => {
619            // Handled at the test method level.
620        }
621        other => {
622            let _ = writeln!(out, "        // TODO: unsupported assertion type: {other}");
623        }
624    }
625}
626
627/// Recursively sort JSON objects so that any key named `"type"` appears first.
628///
629/// System.Text.Json's `[JsonPolymorphic]` requires the type discriminator to be
630/// the first property when deserializing polymorphic types. Fixture config values
631/// serialised via serde_json preserve insertion/alphabetical order, which may put
632/// `"type"` after other keys (e.g. `"password"` before `"type"` in auth configs).
633fn sort_discriminator_first(value: serde_json::Value) -> serde_json::Value {
634    match value {
635        serde_json::Value::Object(map) => {
636            let mut sorted = serde_json::Map::with_capacity(map.len());
637            // Insert "type" first if present.
638            if let Some(type_val) = map.get("type") {
639                sorted.insert("type".to_string(), sort_discriminator_first(type_val.clone()));
640            }
641            for (k, v) in map {
642                if k != "type" {
643                    sorted.insert(k, sort_discriminator_first(v));
644                }
645            }
646            serde_json::Value::Object(sorted)
647        }
648        serde_json::Value::Array(arr) => {
649            serde_json::Value::Array(arr.into_iter().map(sort_discriminator_first).collect())
650        }
651        other => other,
652    }
653}
654
655/// Convert a `serde_json::Value` to a C# literal string.
656fn json_to_csharp(value: &serde_json::Value) -> String {
657    match value {
658        serde_json::Value::String(s) => format!("\"{}\"", escape_csharp(s)),
659        serde_json::Value::Bool(true) => "true".to_string(),
660        serde_json::Value::Bool(false) => "false".to_string(),
661        serde_json::Value::Number(n) => {
662            if n.is_f64() {
663                format!("{}d", n)
664            } else {
665                n.to_string()
666            }
667        }
668        serde_json::Value::Null => "null".to_string(),
669        serde_json::Value::Array(arr) => {
670            let items: Vec<String> = arr.iter().map(json_to_csharp).collect();
671            format!("new[] {{ {} }}", items.join(", "))
672        }
673        serde_json::Value::Object(_) => {
674            let json_str = serde_json::to_string(value).unwrap_or_default();
675            format!("\"{}\"", escape_csharp(&json_str))
676        }
677    }
678}