From 76c50a29c23a4b38377e5dd0815ef8eaa3f2471d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:48:24 -0500 Subject: [PATCH] fix(commons): flow fold ranks lifecycle before time, schema required/legacy-type checks, CSV trailing comma, case-insensitive audit enum parse (CMN-6,7,8,9,12, WP7 task 7.5) --- docs/requirements/Component-CentralUI.md | 2 +- docs/requirements/Component-InboundAPI.md | 2 +- .../Types/Audit/AuditRowProjection.cs | 4 +- .../Types/CsvLineSplitter.cs | 19 ++++++++ .../Types/Debugging/FlowGraphBuilder.cs | 15 ++++--- .../Types/InboundApi/InboundApiSchema.cs | 31 ++++++++++++- .../NativeAlarmSourceOverrideCsvParser.cs | 7 ++- .../Types/OverrideCsvParser.cs | 8 +++- .../Debugging/FlowGraphBuilderTests.cs | 21 +++++++++ ...NativeAlarmSourceOverrideCsvParserTests.cs | 12 +++++ .../OverrideCsvParserTests.cs | 35 +++++++++++++++ .../Audit/AuditRowProjectionParseEnumTests.cs | 26 +++++++++++ .../InboundApi/InboundApiSchemaWp7Tests.cs | 44 +++++++++++++++++++ 13 files changed, 214 insertions(+), 12 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/Audit/AuditRowProjectionParseEnumTests.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/InboundApi/InboundApiSchemaWp7Tests.cs diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index 96eff1dc..c8488d3d 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -164,7 +164,7 @@ Central cluster only. Sites have no user interface. - **Search** — a search box runs a bounded recursive address-space search (depth + result caps) at the site, matching a case-insensitive substring against node DisplayName/path; clicking a result selects it. The dialog surfaces a "showing first N — refine" note when a result cap is hit. - **Type column** — Variable rows display best-effort type info (data type friendly name, scalar/array value rank, writable flag) read from the server during browse. - Set instance-level attribute overrides (non-locked attributes only). - - **Bulk override CSV import** (`InstanceConfigure`): a Blazor `InputFile` upload accepts a CSV of `AttributeName, Value, ElementType?` rows (`ElementType` only for `List` attributes). Each row is validated against the instance's flattened attribute schema (name exists + value type-compatible, reusing the existing override validation); the import is **all-or-nothing** — any per-row error aborts the whole upload with a per-row error summary and nothing is applied. On success the rows are upserted through the same ManagementActor add/update-override handlers used by the inline editor. The same import is available from the CLI (`instance import-overrides --file`, see Component-CLI.md). + - **Bulk override CSV import** (`InstanceConfigure`): a Blazor `InputFile` upload accepts a CSV of `AttributeName, Value, ElementType?` rows (`ElementType` only for `List` attributes). Each row is validated against the instance's flattened attribute schema (name exists + value type-compatible, reusing the existing override validation); the import is **all-or-nothing** — any per-row error aborts the whole upload with a per-row error summary and nothing is applied. One trailing delimiter per row (a spreadsheet export's trailing comma, header included) is tolerated; any other column-count mismatch is still an error. On success the rows are upserted through the same ManagementActor add/update-override handlers used by the inline editor. The same import is available from the CLI (`instance import-overrides --file`, see Component-CLI.md). - **Alarm Overrides card** (`InstanceConfigure`) gained an **"MES reportable override"** tri-state select (2026-09-11) in the per-alarm **override modal** (not on the list row), bound to `InstanceAlarmOverride.IsMesReportableOverride` — the options are "Inherited (reportable | not reportable)" (the parenthetical reflects the template alarm's own flag) → `null`, "Reportable" → `true`, and "Not reportable" → `false`, which is a real override pinning the alarm off for this instance rather than a clear. The list row shows the inherited flag as a green **MES** badge and any override in its override summary. Locked alarms are **filtered out of the override list entirely** (the card only lists non-locked alarms), so there is no disabled-row state for them. `instance alarm-override set --mes-reportable true|false` (omit the flag to inherit) is the CLI equivalent. - **Native Alarm Source Overrides card** (`InstanceConfigure`): a card placed **after the Alarm Overrides card**, listing the template's native alarm sources for per-instance binding. Each row offers **inline override** of the three fields that typically vary per physical instance: - **Connection** — a dropdown (same alarm-capable filtering as the template editor). diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index e2bc85b8..5585bd03 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -164,7 +164,7 @@ The `sbk__` design already supports zero-downtime rotation — a #### Type Definition Format & Nested Validation -- Parameter and return type definitions are persisted as **JSON Schema** (the canonical format produced by the Central UI schema builder; see the `MigrateParametersToJsonSchema` migration). An object declares its fields via `properties` (+ a `required` array); a list declares its element type via `items`. The legacy flat-array form (`[{name,type,required,itemType?}]`) is still accepted on read for transition safety. +- Parameter and return type definitions are persisted as **JSON Schema** (the canonical format produced by the Central UI schema builder; see the `MigrateParametersToJsonSchema` migration). An object declares its fields via `properties` (+ a `required` array); a list declares its element type via `items`. The legacy flat-array form (`[{name,type,required,itemType?}]`) is still accepted on read for transition safety; an unrecognised `type`/`itemType` token in that form is a parse error naming the field and the valid types (it no longer parses and fails every request later). In the JSON Schema form, a `required` entry matches a property name case-insensitively. - Validation is **recursive and type-aware** for the extended types (request parameters and script return values alike, via a single shared engine so the two cannot drift): - **Object**: each declared field's value is validated against its declared (possibly nested) type; a missing required field and a present-but-wrong type are both reported. - **List**: every element is validated against the declared element type (recursing into nested objects/lists). A list whose element type is left undeclared (`array` without `items`) is shape-checked only. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditRowProjection.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditRowProjection.cs index 6956107a..31f4557d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditRowProjection.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditRowProjection.cs @@ -180,7 +180,7 @@ public static class AuditRowProjection } /// - /// Case-sensitive with a caller-supplied fallback. + /// Case-insensitive (matching AuditQueryParamParsers) with a caller-supplied fallback. /// Returns when is null, empty, /// or does not match any declared member name — so callers never throw on an /// unknown/renamed enum string (legacy or corrupt rows degrade gracefully). @@ -190,7 +190,7 @@ public static class AuditRowProjection /// Value returned when is null, empty, or unrecognised. /// The parsed value, or when the input is null, empty, or unrecognised. public static TEnum ParseEnum(string? value, TEnum fallback) where TEnum : struct, Enum - => !string.IsNullOrEmpty(value) && Enum.TryParse(value, ignoreCase: false, out var parsed) + => !string.IsNullOrEmpty(value) && Enum.TryParse(value, ignoreCase: true, out var parsed) ? parsed : fallback; } diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/CsvLineSplitter.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/CsvLineSplitter.cs index fab9f0ba..d924f43d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/CsvLineSplitter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/CsvLineSplitter.cs @@ -22,6 +22,25 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types; /// public static class CsvLineSplitter { + /// + /// Drops ONE empty last field from (a spreadsheet's trailing + /// delimiter). Returns false, leaving nothing to use, when the last field is not empty. + /// + /// The split fields of one line. + /// The fields without the empty trailing one. + /// true when an empty trailing field was dropped. + public static bool TryDropTrailingEmptyField(IReadOnlyList fields, out List trimmed) + { + if (fields.Count > 0 && fields[^1].Length == 0) + { + trimmed = fields.Take(fields.Count - 1).ToList(); + return true; + } + + trimmed = []; + return false; + } + /// /// Splits a single physical CSV line into its fields, applying the quoting rules /// described on . Returns true with the split diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Debugging/FlowGraphBuilder.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Debugging/FlowGraphBuilder.cs index 781375f4..2a558997 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Debugging/FlowGraphBuilder.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Debugging/FlowGraphBuilder.cs @@ -376,9 +376,10 @@ public static class FlowGraphBuilder } /// - /// Orders the rows of one outbound operation when timestamps tie: submit before attempts before the - /// resolve, then non-terminal before terminal statuses — so "first" and "latest" never fall back - /// to GUID order for rows written in the same tick. + /// Orders the rows of one outbound operation: submit before attempts before the resolve, then + /// non-terminal before terminal statuses. This is the PRIMARY sort key of the fold (time only breaks + /// ties between rows of equal rank, e.g. repeated attempts), so cross-node clock skew cannot put a + /// non-terminal row last. /// /// The audit row kind. /// The audit row status. @@ -446,8 +447,12 @@ public static class FlowGraphBuilder var key = ((FlowStepKind, Guid))item; var rows = groups[key] - .OrderBy(r => r.Row.OccurredAtUtc) - .ThenBy(r => LifecycleRank(r.Row.Kind, r.Row.Status)) + // Lifecycle rank FIRST, time only as a tiebreaker (CMN-6): the rows of one cached + // operation are written on different nodes (submit at the site, resolve centrally) + // whose clocks skew by 1-2 s, so ordering by time could place Submitted after + // Delivered and fold a completed operation as Pending. + .OrderBy(r => LifecycleRank(r.Row.Kind, r.Row.Status)) + .ThenBy(r => r.Row.OccurredAtUtc) .ThenBy(r => r.Row.EventId) .ToList(); var first = rows[0].Step; diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/InboundApi/InboundApiSchema.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/InboundApi/InboundApiSchema.cs index 7542e3ec..b1e27de5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/InboundApi/InboundApiSchema.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/InboundApi/InboundApiSchema.cs @@ -202,7 +202,10 @@ public sealed class InboundApiSchema if (type == "object") { - var requiredSet = new HashSet(StringComparer.Ordinal); + // Case-insensitive: a "required" entry spelled with different casing than the + // property it names (hand-edited / legacy-authored schemas) still marks it required + // instead of silently making the field optional (CMN-7). + var requiredSet = new HashSet(StringComparer.OrdinalIgnoreCase); if (el.TryGetProperty("required", out var req) && req.ValueKind == JsonValueKind.Array) { foreach (var r in req.EnumerateArray()) @@ -384,10 +387,16 @@ public sealed class InboundApiSchema StringComparison.OrdinalIgnoreCase)); var normalized = NormalizeType(rawType); + EnsureKnownLegacyType(name!, rawType, normalized); InboundApiSchema schema; if (normalized == "array") { var inner = TryGetMember(item, "itemType", out var it) ? it.GetString() : null; + if (!string.IsNullOrEmpty(inner)) + { + EnsureKnownLegacyType(name!, inner, NormalizeType(inner), isItemType: true); + } + schema = new InboundApiSchema { Type = "array", @@ -405,6 +414,26 @@ public sealed class InboundApiSchema return new InboundApiSchema { Type = "object", Fields = fields }; } + private static readonly string[] KnownTypes = ["string", "integer", "number", "boolean", "object", "array"]; + + /// + /// Rejects a legacy-array parameter whose type (or itemType) is not a known + /// type, at parse time, with the field and the accepted vocabulary — instead of letting a + /// typo such as strign parse cleanly and fail every request later with "unknown + /// declared type" (CMN-8). + /// + private static void EnsureKnownLegacyType(string fieldName, string? rawType, string normalized, bool isItemType = false) + { + if (Array.IndexOf(KnownTypes, normalized) >= 0) + { + return; + } + + var what = isItemType ? "item type" : "type"; + throw new JsonException( + $"Parameter '{fieldName}' has unknown {what} '{rawType}'. Valid types: String, Integer, Float (Number), Boolean, Object, List (Array), DateTime."); + } + /// /// Case-insensitive object-member lookup, used only on the legacy flat-array /// path so both PascalCase and lowercase legacy keys resolve. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/NativeAlarmSourceOverrideCsvParser.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/NativeAlarmSourceOverrideCsvParser.cs index 897f6d6d..41529c87 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/NativeAlarmSourceOverrideCsvParser.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/NativeAlarmSourceOverrideCsvParser.cs @@ -92,7 +92,9 @@ public static class NativeAlarmSourceOverrideCsvParser if (!headerSeen) { - if (!TryMatchHeader(fields, out hasMes)) + if (!TryMatchHeader(fields, out hasMes) + && !(CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmedHeader) + && TryMatchHeader(trimmedHeader, out hasMes))) { errors.Add(HeaderError); return new NativeAlarmSourceOverrideCsvParseResult(rows, errors); @@ -103,6 +105,9 @@ public static class NativeAlarmSourceOverrideCsvParser } var expected = hasMes ? BaseColumns + 1 : BaseColumns; + // Tolerate exactly one empty trailing field (spreadsheet trailing delimiter) (CMN-9). + if (fields.Count == expected + 1 && CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmed)) + fields = trimmed; if (fields.Count != expected) { errors.Add( diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/OverrideCsvParser.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/OverrideCsvParser.cs index c97bd183..852e42a0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/OverrideCsvParser.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/OverrideCsvParser.cs @@ -68,7 +68,9 @@ public static class OverrideCsvParser if (!headerSeen) { - if (!TryMatchHeader(fields, out hasElementTypeColumn)) + if (!TryMatchHeader(fields, out hasElementTypeColumn) + && !(CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmedHeader) + && TryMatchHeader(trimmedHeader, out hasElementTypeColumn))) { errors.Add(HeaderError); return new OverrideCsvParseResult(rows, errors); @@ -79,6 +81,10 @@ public static class OverrideCsvParser } var expectedColumns = hasElementTypeColumn ? 3 : 2; + // A spreadsheet export often leaves one trailing delimiter on every row; an empty + // extra last field carries no data, so tolerate exactly one (CMN-9). + if (fields.Count == expectedColumns + 1 && CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmed)) + fields = trimmed; if (fields.Count != expectedColumns) { errors.Add( diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Debugging/FlowGraphBuilderTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Debugging/FlowGraphBuilderTests.cs index 64e89aa0..e94705e8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Debugging/FlowGraphBuilderTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Debugging/FlowGraphBuilderTests.cs @@ -655,6 +655,27 @@ public class FlowGraphBuilderTests Assert.Equal(sa.Lifecycle!.Select(r => r.Kind), sb.Lifecycle!.Select(r => r.Kind)); } + /// + /// CMN-6: the resolve row is written centrally and the submit row at the site; with the site clock + /// ahead, the submit row's timestamp is LATER than the delivery's. The fold must still treat the + /// resolve as terminal, not render the completed operation as Pending. + /// + [Fact] + public void Fold_WithCrossNodeClockSkew_StillTreatsResolveAsTerminal() + { + var corr = Guid.NewGuid(); + var submit = Outbound(AuditChannel.ApiOutbound, AuditKind.CachedSubmit, AuditStatus.Submitted, 2000, corr, "Delmia.Ack", node: "node-a", request: "req"); + var resolve = Outbound(AuditChannel.ApiOutbound, AuditKind.CachedResolve, AuditStatus.Delivered, 1000, corr, "Delmia.Ack", node: "central-a", response: "res"); + + var graph = FlowGraphBuilder.Build([SiteRunRow(20), submit, resolve]); + + var step = Assert.Single(graph.Steps, s => s.Kind == FlowStepKind.ApiCall); + Assert.Equal(FlowStepOutcome.Ok, step.Outcome); + Assert.Equal("res", step.OutputJson); + Assert.Equal(["CachedSubmit", "CachedResolve"], step.Lifecycle!.Select(r => r.Kind)); + Assert.True(step.DurationMs >= 0); + } + /// Verifies that a cached step whose submit row is missing is still treated as asynchronous. [Fact] public void CachedStep_WhoseSubmitRowIsMissing_IsStillAsync() diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/NativeAlarmSourceOverrideCsvParserTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/NativeAlarmSourceOverrideCsvParserTests.cs index 7e941765..e3047efd 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/NativeAlarmSourceOverrideCsvParserTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/NativeAlarmSourceOverrideCsvParserTests.cs @@ -197,4 +197,16 @@ public class NativeAlarmSourceOverrideCsvParserTests Assert.Empty(result.Rows); Assert.Contains(result.Errors, e => e.Contains("Line 2") && e.Contains("MesReportable")); } + + /// Verifies that one trailing delimiter on every row (a spreadsheet export) is tolerated, header included. + [Fact] + public void Parse_TrailingCommaOnEveryRow_IsTolerated() + { + const string csv = "SourceName,Connection,SourceReference,Filter,\nPressure,OPC,ns=2;s=P,Active,\n"; + + var result = NativeAlarmSourceOverrideCsvParser.Parse(csv); + + Assert.Empty(result.Errors); + Assert.Equal("Pressure", Assert.Single(result.Rows).SourceName); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/OverrideCsvParserTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/OverrideCsvParserTests.cs index 34f6a5a7..3da1d9e5 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/OverrideCsvParserTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/OverrideCsvParserTests.cs @@ -262,4 +262,39 @@ public class OverrideCsvParserTests Assert.Equal("a,b", row.Value); Assert.Equal("Type", row.ElementType); } + + /// Verifies that one trailing delimiter on every row (a spreadsheet export) is tolerated, header included. + [Fact] + public void Parse_TrailingCommaOnEveryRow_IsTolerated() + { + const string csv = "AttributeName,Value,ElementType,\nSetpoint,42,Int32,\nName,Pump A,,\n"; + + var result = OverrideCsvParser.Parse(csv); + + Assert.Empty(result.Errors); + Assert.Equal(2, result.Rows.Count); + Assert.Equal("Int32", result.Rows[0].ElementType); + Assert.Null(result.Rows[1].ElementType); + } + + /// Verifies that a two-column file with a trailing comma is tolerated. + [Fact] + public void Parse_TwoColumnWithTrailingComma_IsTolerated() + { + var result = OverrideCsvParser.Parse("AttributeName,Value,\nSetpoint,42,\n"); + + Assert.Empty(result.Errors); + Assert.Equal("42", Assert.Single(result.Rows).Value); + } + + /// Verifies that a genuinely wrong column count, or a NON-empty extra column, stays an error. + [Fact] + public void Parse_ExtraNonEmptyColumn_StillAnError() + { + var result = OverrideCsvParser.Parse("AttributeName,Value\nSetpoint,42,extra\nA,1,,\n"); + + Assert.Empty(result.Rows); + Assert.Equal(2, result.Errors.Count); + Assert.All(result.Errors, e => Assert.Contains("expected 2 columns", e)); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/Audit/AuditRowProjectionParseEnumTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/Audit/AuditRowProjectionParseEnumTests.cs new file mode 100644 index 00000000..a706d885 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/Audit/AuditRowProjectionParseEnumTests.cs @@ -0,0 +1,26 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; + +namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Types.Audit; + +/// Review CMN-12: stored enum tokens parse case-insensitively, like the query parsers. +public class AuditRowProjectionParseEnumTests +{ + /// A mis-cased stored token resolves to its member rather than the fallback. + /// The stored token. + [Theory] + [InlineData("DbOutbound")] + [InlineData("dboutbound")] + [InlineData("DBOUTBOUND")] + public void ParseEnum_IsCaseInsensitive(string stored) + => Assert.Equal(AuditChannel.DbOutbound, AuditRowProjection.ParseEnum(stored, AuditChannel.ApiInbound)); + + /// Unknown or empty tokens still fall back. + /// The stored token. + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("NoSuchChannel")] + public void ParseEnum_UnknownFallsBack(string? stored) + => Assert.Equal(AuditChannel.ApiInbound, AuditRowProjection.ParseEnum(stored, AuditChannel.ApiInbound)); +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/InboundApi/InboundApiSchemaWp7Tests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/InboundApi/InboundApiSchemaWp7Tests.cs new file mode 100644 index 00000000..3b43251d --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/InboundApi/InboundApiSchemaWp7Tests.cs @@ -0,0 +1,44 @@ +using System.Text.Json; +using ZB.MOM.WW.ScadaBridge.Commons.Types.InboundApi; + +namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Types.InboundApi; + +/// Review CMN-7 (required matching) and CMN-8 (unknown legacy types). +public class InboundApiSchemaWp7Tests +{ + /// A "required" entry spelled with different casing than the property still makes it required. + [Fact] + public void Required_MatchesPropertyNamesCaseInsensitively() + { + const string json = """{"type":"object","properties":{"WorkOrders":{"type":"string"},"Other":{"type":"string"}},"required":["workorders"]}"""; + + var schema = InboundApiSchema.Parse(json)!; + + Assert.True(schema.Fields.Single(f => f.Name == "WorkOrders").Required); + Assert.False(schema.Fields.Single(f => f.Name == "Other").Required); + } + + /// A typo'd legacy type is a parse error naming the field and the valid vocabulary. + /// The legacy parameter array. + [Theory] + [InlineData("""[{"name":"Qty","type":"strign"}]""")] + [InlineData("""[{"name":"Items","type":"List","itemType":"intger"}]""")] + public void LegacyArray_UnknownType_ThrowsClearError(string legacy) + { + var ex = Assert.Throws(() => InboundApiSchema.Parse(legacy)); + + Assert.Contains("unknown", ex.Message); + Assert.Contains("Valid types", ex.Message); + } + + /// Every legacy alias still parses. + [Fact] + public void LegacyArray_KnownAliases_StillParse() + { + const string legacy = """[{"name":"a","type":"Integer"},{"name":"b","type":"Float"},{"name":"c","type":"DateTime"},{"name":"d","type":"List","itemType":"String"},{"name":"e","type":"Object"},{"name":"f","type":"Boolean"},{"name":"g"}]"""; + + var schema = InboundApiSchema.Parse(legacy)!; + + Assert.Equal(7, schema.Fields.Count); + } +}