|
| 1 | +using Microsoft.CodeAnalysis; |
| 2 | +using Microsoft.CodeAnalysis.CSharp; |
| 3 | +using MetaObjects.Codegen; |
| 4 | +using MetaObjects.Codegen.Generators; |
| 5 | +using MetaObjects.Loader; |
| 6 | +using MetaObjects.Meta; |
| 7 | +using Xunit; |
| 8 | + |
| 9 | +namespace MetaObjects.Codegen.Tests; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// OutputParserGenerator emission tests (FR6, ADR-0010). Mirrors |
| 13 | +/// server/typescript/packages/codegen-ts/test/generators/output-parser-file.test.ts — |
| 14 | +/// asserts the file-per-template emit, the Parse / TryParse dual-API shape, and |
| 15 | +/// that the generator stays out of template.prompt's lane. |
| 16 | +/// </summary> |
| 17 | +public sealed class OutputParserGeneratorTests |
| 18 | +{ |
| 19 | + private static MetaRoot Load(string model) |
| 20 | + { |
| 21 | + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "outputs.json")]); |
| 22 | + Assert.Empty(r.Errors); |
| 23 | + return r.Root; |
| 24 | + } |
| 25 | + |
| 26 | + private static GenContext Ctx(MetaRoot root) => new() |
| 27 | + { |
| 28 | + Entities = root.Objects(), |
| 29 | + Root = root, |
| 30 | + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, |
| 31 | + }; |
| 32 | + |
| 33 | + [Fact] |
| 34 | + public void Emits_no_files_when_no_template_output_nodes() |
| 35 | + { |
| 36 | + // A model with only a template.prompt; the output-parser generator stays silent. |
| 37 | + const string m = """ |
| 38 | + { "metadata.root": { "package": "acme::ai", "children": [ |
| 39 | + { "object.value": { "name": "Payload", "children": [ { "field.string": { "name": "x" } } ] } }, |
| 40 | + { "template.prompt": { "name": "promptOnly", "@payloadRef": "Payload", "@textRef": "p/x", "@format": "text" } } |
| 41 | + ]}} |
| 42 | + """; |
| 43 | + var files = new OutputParserGenerator().Generate(Ctx(Load(m))).ToList(); |
| 44 | + Assert.Empty(files); |
| 45 | + } |
| 46 | + |
| 47 | + [Fact] |
| 48 | + public void Emits_one_file_per_template_output_with_expected_path_and_class() |
| 49 | + { |
| 50 | + const string m = """ |
| 51 | + { "metadata.root": { "package": "acme::ai", "children": [ |
| 52 | + { "object.value": { "name": "AlphaPayload", "children": [ { "field.string": { "name": "name" } } ] } }, |
| 53 | + { "object.value": { "name": "BetaPayload", "children": [ { "field.int": { "name": "n" } } ] } }, |
| 54 | + { "template.output": { "name": "Alpha", "@payloadRef": "AlphaPayload", "@textRef": "a/x", "@format": "json" } }, |
| 55 | + { "template.output": { "name": "Beta", "@payloadRef": "BetaPayload", "@textRef": "b/x", "@format": "json" } } |
| 56 | + ]}} |
| 57 | + """; |
| 58 | + var files = new OutputParserGenerator().Generate(Ctx(Load(m))).OrderBy(f => f.Path).ToList(); |
| 59 | + Assert.Equal(2, files.Count); |
| 60 | + Assert.Equal("Alpha.output.cs", files[0].Path); |
| 61 | + Assert.Equal("Beta.output.cs", files[1].Path); |
| 62 | + Assert.Contains("public static class AlphaParser", files[0].Content); |
| 63 | + Assert.Contains("public static class BetaParser", files[1].Content); |
| 64 | + } |
| 65 | + |
| 66 | + [Fact] |
| 67 | + public void Emits_dual_api_returning_the_payload_ref_type() |
| 68 | + { |
| 69 | + const string m = """ |
| 70 | + { "metadata.root": { "package": "acme::ai", "children": [ |
| 71 | + { "object.value": { "name": "NpcResponsePayload", "children": [ |
| 72 | + { "field.string": { "name": "name" } }, |
| 73 | + { "field.int": { "name": "age" } } |
| 74 | + ]}}, |
| 75 | + { "template.output": { "name": "NpcResponseOutput", "@payloadRef": "NpcResponsePayload", |
| 76 | + "@textRef": "npc/output", "@format": "json" } } |
| 77 | + ]}} |
| 78 | + """; |
| 79 | + var file = Assert.Single(new OutputParserGenerator().Generate(Ctx(Load(m)))); |
| 80 | + Assert.Equal("NpcResponseOutput.output.cs", file.Path); |
| 81 | + |
| 82 | + var src = file.Content; |
| 83 | + Assert.Contains("using System.Text.Json;", src); |
| 84 | + Assert.Contains("namespace Acme.Generated;", src); |
| 85 | + Assert.Contains("public static class NpcResponseOutputParser", src); |
| 86 | + |
| 87 | + // Parse returns the payload-VO type and throws on failure. |
| 88 | + Assert.Contains("public static NpcResponsePayload Parse(string text)", src); |
| 89 | + Assert.Contains("throw new JsonException", src); |
| 90 | + |
| 91 | + // TryParse returns bool + nullable out + error out. |
| 92 | + Assert.Contains("public static bool TryParse(string text,", src); |
| 93 | + Assert.Contains("[NotNullWhen(true)] out NpcResponsePayload? value", src); |
| 94 | + Assert.Contains("[NotNullWhen(false)] out string? error", src); |
| 95 | + } |
| 96 | + |
| 97 | + [Fact] |
| 98 | + public void Emitted_source_compiles_alongside_the_payload_record() |
| 99 | + { |
| 100 | + // End-to-end: payload-VO codegen + output-parser codegen should compile |
| 101 | + // together with no errors. Guards against C# language-level regressions |
| 102 | + // in the emitted shape (required keyword, nullable annotations, etc.). |
| 103 | + const string m = """ |
| 104 | + { "metadata.root": { "package": "acme::ai", "children": [ |
| 105 | + { "object.value": { "name": "NpcResponsePayload", "children": [ |
| 106 | + { "field.string": { "name": "name" } }, |
| 107 | + { "field.int": { "name": "age" } } |
| 108 | + ]}}, |
| 109 | + { "template.output": { "name": "NpcResponseOutput", "@payloadRef": "NpcResponsePayload", |
| 110 | + "@textRef": "npc/output", "@format": "json" } } |
| 111 | + ]}} |
| 112 | + """; |
| 113 | + var root = Load(m); |
| 114 | + var parserSrc = Assert.Single(new OutputParserGenerator().Generate(Ctx(root))).Content; |
| 115 | + var payloadSrc = PayloadCodegen.GeneratePayloadRecords(root, "NpcResponsePayload"); |
| 116 | + |
| 117 | + // Wrap the payload record in a namespace matching the parser's. |
| 118 | + var wrappedPayload = "namespace Acme.Generated;\n" + payloadSrc; |
| 119 | + |
| 120 | + var trees = new[] |
| 121 | + { |
| 122 | + CSharpSyntaxTree.ParseText(parserSrc, new CSharpParseOptions(LanguageVersion.CSharp12)), |
| 123 | + CSharpSyntaxTree.ParseText(wrappedPayload, new CSharpParseOptions(LanguageVersion.CSharp12)), |
| 124 | + }; |
| 125 | + var refs = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) |
| 126 | + .Split(Path.PathSeparator).Where(p => p.Length > 0) |
| 127 | + .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); |
| 128 | + var comp = CSharpCompilation.Create("outparse_" + Guid.NewGuid().ToString("N"), |
| 129 | + trees, refs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); |
| 130 | + var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error) |
| 131 | + .Select(d => $"{d.Id}: {d.GetMessage()}").ToList(); |
| 132 | + Assert.True(errors.Count == 0, "parser + payload should compile, got: " + string.Join("; ", errors)); |
| 133 | + } |
| 134 | + |
| 135 | + [Fact] |
| 136 | + public void Emitted_source_matches_the_template_output_simple_fixture() |
| 137 | + { |
| 138 | + // Conformance-adjacent check: the same fixture used by the TS port should |
| 139 | + // drive the C# emit (different output shape — TS = Zod, C# = STJ — but |
| 140 | + // same metadata in). |
| 141 | + var repoRoot = LocateRepoRoot(); |
| 142 | + var fixtureDir = Path.Combine(repoRoot, "fixtures", "conformance", "template-output-simple", "input"); |
| 143 | + Assert.True(Directory.Exists(fixtureDir), $"fixture dir not found at {fixtureDir}"); |
| 144 | + |
| 145 | + var load = MetaDataLoader.FromDirectory(fixtureDir); |
| 146 | + Assert.Empty(load.Errors); |
| 147 | + |
| 148 | + var ctx = new GenContext |
| 149 | + { |
| 150 | + Entities = load.Root.Objects(), |
| 151 | + Root = load.Root, |
| 152 | + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, |
| 153 | + }; |
| 154 | + var file = Assert.Single(new OutputParserGenerator().Generate(ctx)); |
| 155 | + Assert.Equal("NpcResponseOutput.output.cs", file.Path); |
| 156 | + Assert.Contains("public static NpcResponsePayload Parse(string text)", file.Content); |
| 157 | + Assert.Contains("public static bool TryParse(string text,", file.Content); |
| 158 | + } |
| 159 | + |
| 160 | + // Walk upward from the test assembly to the repo root (contains a fixtures/ dir). |
| 161 | + private static string LocateRepoRoot() |
| 162 | + { |
| 163 | + var dir = new DirectoryInfo(AppContext.BaseDirectory); |
| 164 | + while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, "fixtures"))) |
| 165 | + dir = dir.Parent; |
| 166 | + Assert.NotNull(dir); |
| 167 | + return dir!.FullName; |
| 168 | + } |
| 169 | +} |
0 commit comments