From de899014e6e653ea71320eb1e8fd22d1405071c6 Mon Sep 17 00:00:00 2001 From: Michael Hoffer Date: Sun, 29 Nov 2026 00:18:36 +0100 Subject: [PATCH] C# conformance: remove the 239 test methods that detect nothing of their own The suite had 1280 cases in 866 methods, written feature by feature while C# was compared with Java. Many repeat each other: 130 of the 215 classes covered no runtime line that another class did not cover. This removes the methods (283 cases) that the remaining tests and the portable scenarios make superfluous, and keeps 997 cases in 627 methods. A test stayed if - it exchanges documents with the Java programs or reads a shared expectation in fixtures/ (268 methods): the gate checks every such file in both languages as before; - it was written together with a runtime change (14 methods); - it guards against what a seeded fault cannot show: recursion as deep as a limit allows, the largest sequence numbers, concurrent use (6); - or the others needed it (339 methods) to still notice every fault that the full suite noticed, reach every place of the runtime it reached, and run every shape of generated code it ran. Faults are from mutation testing with Stryker.NET 5.1: 9,521 single changes of the runtime, of which the full suite and the portable scenarios noticed 6,799. A repeat with the kept tests noticed 6,793 of them again; the tests that had noticed the six others are among the kept ones, and their result varies between runs of the instrumented runtime. No model set lost all of its tests, so the gate generates and compiles what it did before and takes as long. TEST-AREAS.md has the new counts per area and describes the rules; the README says that not every sentence of its list has a C# test of its own any more. ReferenceDefaultBindings.DuplicateSeed was only set by a removed test. --- conformance/README.md | 10 +- conformance/TEST-AREAS.md | 159 +++--- .../AbstractArgumentsTests.cs | 13 - conformance/behavior-csharp/BehaviorTests.cs | 75 --- .../HookedManagedDefaultsTests.cs | 69 --- .../InheritedManagedDefaultsTests.cs | 51 -- .../RedeclaredManagedDefaultsTests.cs | 12 - .../BehaviorHierarchyTests.cs | 82 ---- .../CollectionDefaultTests.cs | 25 - .../CollectionRedeclarationTests.cs | 25 - .../ConcreteBasesTests.cs | 53 -- .../covariance-csharp/CovarianceTests.cs | 22 - .../csharp/CollectionObservationTests.cs | 128 ----- .../csharp/ConfiguredValidationTests.cs | 79 --- .../csharp/ContainmentCursorAncestryTests.cs | 67 --- conformance/csharp/ContainmentCursorTests.cs | 59 --- .../csharp/ContainmentObservationTests.cs | 176 ------- conformance/csharp/ContentEqualityTests.cs | 102 ---- conformance/csharp/DeepCopyTests.cs | 132 ----- conformance/csharp/DefaultTests.cs | 39 -- conformance/csharp/DynamicDefaultsTests.cs | 139 ------ .../csharp/ExternalSnapshotCodecTests.cs | 49 -- conformance/csharp/FeatureBundleTests.cs | 41 -- .../csharp/GetterRoleOwnershipTests.cs | 14 - .../csharp/GetterRoleSetOwnershipTests.cs | 32 -- conformance/csharp/HierarchyTests.cs | 35 -- .../csharp/ImmutableCollectionTests.cs | 69 --- conformance/csharp/ImmutableValueTests.cs | 18 - conformance/csharp/JournalHistoryTests.cs | 117 ----- conformance/csharp/JournalTests.cs | 144 ------ .../csharp/KeyedGetterRoleOwnershipTests.cs | 36 -- conformance/csharp/KeyedTests.cs | 103 ---- .../csharp/KeyedUnorderedOwnershipTests.cs | 67 --- conformance/csharp/ListPredicateTests.cs | 17 - conformance/csharp/ListReplacementTests.cs | 26 - conformance/csharp/ModelMergeAliasTests.cs | 41 -- conformance/csharp/ModelPatchAliasTests.cs | 40 -- .../csharp/ModelPatchCopyReferenceTests.cs | 78 --- .../csharp/ModelPatchImmutableTests.cs | 49 -- conformance/csharp/ModelPatchTests.cs | 145 ------ .../csharp/ModelPatchUndoIdentityTests.cs | 23 - conformance/csharp/ModelTypeCatalogTests.cs | 36 -- conformance/csharp/ModelVersionTests.cs | 65 --- .../csharp/NamedRoleContainmentTests.cs | 35 -- .../csharp/NativePropertyChangedTests.cs | 43 -- conformance/csharp/ObservationTests.cs | 274 ----------- conformance/csharp/ObserverOrderTests.cs | 464 ------------------ conformance/csharp/PositionalJournalTests.cs | 19 - .../csharp/ProjectedListLifetimeTests.cs | 48 -- .../csharp/ProjectedListObservationTests.cs | 154 ------ .../ReadOnlyReplayCompatibilityTests.cs | 31 -- conformance/csharp/ReadOnlyTests.cs | 58 --- .../csharp/ReciprocalListObservationTests.cs | 82 ---- conformance/csharp/ReciprocalTests.cs | 35 -- conformance/csharp/ReferenceCursorTests.cs | 44 -- .../csharp/ReferenceListObservationTests.cs | 116 ----- .../csharp/ReflectionAnnotationTests.cs | 13 - conformance/csharp/ReflectionDefaultTests.cs | 24 - conformance/csharp/ReflectionTests.cs | 30 -- .../csharp/RetainedContainmentCursorTests.cs | 56 --- .../csharp/ScalarCollectionApplyTests.cs | 15 - .../csharp/ScalarMapObservationTests.cs | 15 - .../csharp/ScalarSetObservationTests.cs | 68 --- conformance/csharp/ScalarTests.cs | 23 - conformance/csharp/ShallowCopyTests.cs | 128 ----- conformance/csharp/ShipmentTests.cs | 38 -- conformance/csharp/SnapshotSchemaTests.cs | 31 -- .../csharp/StockApplicationAliasTests.cs | 22 - .../csharp/StockCollectionContractTests.cs | 34 -- .../csharp/StockCollectionDefaultTests.cs | 18 - .../csharp/StockManagedBuilderTests.cs | 40 -- conformance/csharp/StockMiniClangTests.cs | 12 - conformance/csharp/StockModelMergeTests.cs | 42 -- conformance/csharp/StockModelRegistryTests.cs | 14 - .../csharp/StockModelSharedDiffTests.cs | 71 --- .../csharp/StockPropertyInheritanceTests.cs | 15 - conformance/csharp/StockPropertyOrderTests.cs | 38 -- .../csharp/StockReciprocalBuilderTests.cs | 182 ------- .../csharp/StockReciprocalListBuilderTests.cs | 36 -- .../csharp/StockReferenceBuilderTests.cs | 99 ---- .../csharp/StockReferenceDefaultTests.cs | 67 --- .../csharp/StockScalarGetterBuilderTests.cs | 26 - conformance/csharp/StockSeriesBuilderTests.cs | 44 -- .../csharp/StockSharedParentBuilderTests.cs | 41 -- .../csharp/StockSingularOwningBuilderTests.cs | 19 - conformance/csharp/UnorderedCursorTests.cs | 26 - conformance/csharp/YamlTests.cs | 26 - .../DelegatedListsTests.cs | 28 -- .../ExecutableDefaultTests.cs | 76 --- .../GenericEnumBindingTests.cs | 23 - .../StockExternalBindingTests.cs | 112 ----- .../generic-bound-csharp/GenericBoundTests.cs | 19 - .../generic-keyed-csharp/GenericKeyedTests.cs | 32 -- .../ImmutablePortSettingsTests.cs | 20 - .../ImmutableBehaviorTests.cs | 32 -- .../ImmutableToStringTests.cs | 65 --- .../GetterRoleReciprocalTests.cs | 12 - .../InheritedOppositeTests.cs | 45 -- .../SequenceRoleReciprocalTests.cs | 9 - .../KeyedRedeclarationTests.cs | 34 -- .../ProjectedRelationshipTests.cs | 9 - .../BulkListAliasTests.cs | 186 ------- .../OrdinaryContainmentTests.cs | 20 - .../OrdinaryOwningBuilderTests.cs | 66 --- .../OwningPredicateTests.cs | 33 -- .../OwningReplacementTests.cs | 64 --- .../SharedInverseTests.cs | 87 ---- .../UnorderedContainmentTests.cs | 30 -- .../ValueMatchingAliasTests.cs | 13 - .../RedeclarationTests.cs | 99 ---- .../redeclaration-csharp/ValueChoiceTests.cs | 37 -- .../ComposedReferenceDefaultsTests.cs | 40 -- .../HookReferenceDefaultsTests.cs | 41 -- .../InheritedMixedDefaultsTests.cs | 16 - .../ProjectedDefaultsTests.cs | 66 --- .../ReferenceDefaultBindings.cs | 4 +- .../ReferenceDefaultTests.cs | 125 ----- .../RootHookDefaultsTests.cs | 50 -- 118 files changed, 105 insertions(+), 6866 deletions(-) delete mode 100644 conformance/csharp/ContainmentCursorAncestryTests.cs delete mode 100644 conformance/csharp/DeepCopyTests.cs delete mode 100644 conformance/csharp/ModelMergeAliasTests.cs delete mode 100644 conformance/csharp/ModelPatchAliasTests.cs delete mode 100644 conformance/csharp/ModelPatchCopyReferenceTests.cs delete mode 100644 conformance/csharp/ModelPatchImmutableTests.cs delete mode 100644 conformance/csharp/ProjectedListObservationTests.cs delete mode 100644 conformance/csharp/ReadOnlyTests.cs delete mode 100644 conformance/csharp/ReciprocalListObservationTests.cs delete mode 100644 conformance/csharp/ScalarSetObservationTests.cs delete mode 100644 conformance/csharp/StockReciprocalBuilderTests.cs delete mode 100644 conformance/csharp/StockSeriesBuilderTests.cs delete mode 100644 conformance/immutable-behavior-csharp/ImmutableToStringTests.cs diff --git a/conformance/README.md b/conformance/README.md index 977e692a..b0c09056 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -9,8 +9,9 @@ SDK that can build and run .NET 8. The cross-language rules are the [portable contract](portable/CONTRACT.md); this suite tests the C# implementation in much more detail. -[TEST-AREAS.md](TEST-AREAS.md) assigns its tests to areas and says which areas -the contract covers. +[TEST-AREAS.md](TEST-AREAS.md) assigns its tests to areas, says which areas +the contract covers, and describes how the suite was trimmed to the tests +that detect something the others do not. Gradle generates Java and C# model classes from the same Java interface declarations. The generated Java classes, running on the Java VMF runtime, @@ -65,6 +66,11 @@ JSON, XML, and YAML journal documents. ## Shared expectations +This list describes the behavior that Java and C# share. Every fixture and +every exchanged document below is checked in both languages. Since the suite +was trimmed, not every sentence has a C# test of its own: a case that only +repeated what other tests detect was removed. + - [Workshop operations](fixtures/workshop-operations.json) define expected containment order, reference identity, inverse links, and model validity after each accepted or rejected edit. Java and C# each check the fixture. diff --git a/conformance/TEST-AREAS.md b/conformance/TEST-AREAS.md index 51a2e55a..34bc8b5d 100644 --- a/conformance/TEST-AREAS.md +++ b/conformance/TEST-AREAS.md @@ -1,6 +1,6 @@ # Areas of the C# conformance tests -The C# conformance suite has 1266 test cases in 215 classes. They were written while +The C# conformance suite has 997 test cases in 205 classes. They were written while comparing the C# target with Java feature by feature, so they test C#'s implementation, not a contract. This list assigns every class to one area and says whether the [portable contract](portable/CONTRACT.md) covers the area, so that each area can be decided: contract module, C#-only, or dropped. @@ -12,103 +12,136 @@ cross-language rule; for them, Java's behavior was the specification. Counts come from the last test run (one row per test case, including each case of a theory). +## How the suite was trimmed + +The suite had 1280 cases in 866 test methods. In November 2026, 239 methods (283 cases) were removed: those that +detected nothing which the remaining tests and the portable scenarios do not detect as well. A test stayed if + +- it exchanges documents with the Java programs or reads one of the shared expectations in `fixtures/` (268 + methods), so the gate still checks every such file in both languages; or +- it was written together with a change of the runtime, to pin that change (14 methods); or +- it guards against something a seeded fault cannot show: recursion that is as deep as a limit allows, the + largest sequence numbers, concurrent use (6 methods); or +- the remaining tests, together with the portable scenarios, needed it (339 methods) to still + - notice every fault that the full suite noticed. Mutation testing (Stryker.NET 5.1) changed the runtime in + 9,521 places, one at a time. The full suite and the scenarios noticed 6,799 of the changes, the scenarios + by themselves 1,717. About 2,160 further changes could not be tried, because the changed code does not + compile; + - reach every place of the runtime that the full suite reached: every line, and every expression or + statement that mutation testing changed, also where no test noticed the change; + - run every shape of generated model code that the full suite ran: a line of generated code with the names + of the model replaced by placeholders. The full suite ran 2,304 shapes, and each is one variant of what the + generator writes. + +Afterwards the mutation run was repeated with the remaining tests: they noticed 6,793 of the 6,799 changes again. +None of the six others went with a removed test. The tests that had noticed five of them are still there, and +they notice these changes only in some runs of the instrumented runtime, not when the change is made by hand; +the sixth was a timeout of the first run. Suite and scenarios together still cover the same runtime lines. + +What this does not show: a removed test may have checked something that no seeded fault resembles and that no +line or shape tells apart. Tests that pin behavior the contract leaves open, such as the listener order beyond +E7 to E9, were measured like all others. The removed tests are in the history of this folder. + +To repeat the mutation run, give the test hosts a larger stack (`DOTNET_DefaultStackSize=1000000`): the +instrumented runtime has larger stack frames, and the YAML depth test otherwise overflows the stack, which ends +every run early and makes its results useless. + ## What the suite covers -Measured on 2026-11-28 with `dotnet-coverage` (line coverage of `Vmf.Runtime`; each test class was also run -alone) and JaCoCo (generator lines reached while generating each model set): - -- **Runtime.** The suite covers 95.0% of the runtime's 9,207 coverable lines, the portable scenarios 34.7%. All - but 8 of the lines the scenarios cover are also covered by the suite. The 60% that only the suite covers are - the features outside the contract: journals, patches, diff and merge, JSON schema, XML and YAML, cursors, - feature bundles, builders, summaries. -- **Overlap inside the suite.** 130 of the 215 classes (521 cases) cover no runtime line that another class does - not cover as well. 30 classes (367 cases) reach 95% of the suite's line coverage, 59 classes (605 cases) 99% - and 92 classes (837 cases) all of it. Line coverage is a lower bound of what a test checks: two tests can - cover the same lines in different states, which matters most for the listener-order and containment tests. +Measured on 2026-11-28 with `dotnet-coverage` (line coverage of `Vmf.Runtime`; each test method was also run +alone), Stryker.NET (see above) and JaCoCo (generator lines reached while generating each model set): + +- **Runtime lines.** The suite covers 95.0% of the runtime's 9,415 coverable lines, the portable scenarios + 35.1%. All but 13 of the lines the scenarios cover are also covered by the suite. The 60% that only the suite + covers are the features outside the contract: journals, patches, diff and merge, JSON schema, XML and YAML, + cursors, feature bundles, builders, summaries. +- **Seeded faults.** The suite and the scenarios notice 71% of the 9,521 seeded faults. 794 are in code that no + test runs, and 1,928 change nothing that a test checks. Line coverage is the weaker measure: a test can run a + line without checking what it does. - **Generator.** The portable, stock (every test-suite and vmf-jackson model) and workshop models reach 5,703 generator lines for C#. The 36 conformance model sets add 606 lines (9.6%). A single set reaches 348 of them, and 308 of those belong to the sets of the behavior, hierarchy, default and applied-call areas; 19 sets reach - no line of their own. -- **Duplicates.** The 852 test methods contain no copies: none are equal after normalizing literals, and one - group of three is similar (80% of their token sequences). -- **Time.** The 1266 cases run in 2 to 3 seconds. The gate takes about 7 minutes; that is code generation and - compilation of the 36 model sets in two languages, not test execution. + no line of their own. The trim removed no model set: each still has tests. +- **Time.** The 997 cases run in 1 to 3 seconds. The gate takes about 7 minutes; that is code generation and + compilation of the 36 model sets in two languages, not test execution, so the trim did not shorten it. -The column "Own lines" is the number of runtime lines that only the tests of that area cover. +The column "Own lines" is the number of runtime lines that only the tests of that area cover. The recommendations +are from before the trim: where one says to trim or to drop tests, the trim has removed what it could show to be +superfluous, and what remains open is the decision about the area. | Area | Cases | Own lines | Contract | What the tests check | Recommendation | Decision | |---|---:|---:|---|---|---|---| -| Containment, opposites, references | 169 | 99 | core C, R | moves, ownership, cycles, opposite updates, equal-but-distinct objects, aliasing in bulk edits | Keep as C# regression tests; the contract states the cross-language rules. Review the tests that pin internal details (sparse slots, alias resolvers, held views). | | -| Scalars and scalar lists | 23 | 11 | core T | defaults, extreme values, constraints, capacity checks, set membership | Keep as C# regression tests. | | -| Events | 92 | 18 | E | property, list, set and reference-list events, local and recursive listeners | Keep as C# regression tests. | | -| Listener order and reentrancy | 69 | 1 | E7, E8, E9, H4; the rest deliberately unspecified | the order in which listeners of several objects and scopes are called, edits made inside listeners, subscriptions changed during delivery | The tests follow E7 to E9 and H4; traces that mix model, view and raw listeners are compared per kind. The cases about subscriptions changed during delivery, exceptions and recordings started inside listeners pin behavior the contract leaves open: keep them only as long as C# promises that behavior. | Rules E7 to E9 and H4 decided (2026-11-27); Java and C# changed to them. | +| Containment, opposites, references | 147 | 142 | core C, R | moves, ownership, cycles, opposite updates, equal-but-distinct objects, aliasing in bulk edits | Keep as C# regression tests; the contract states the cross-language rules. Review the tests that pin internal details (sparse slots, alias resolvers, held views). | | +| Scalars and scalar lists | 22 | 11 | core T | defaults, extreme values, constraints, capacity checks, set membership | Keep as C# regression tests. | | +| Events | 70 | 22 | E | property, list, set and reference-list events, local and recursive listeners | Keep as C# regression tests. | | +| Listener order and reentrancy | 43 | 8 | E7, E8, E9, H4; the rest deliberately unspecified | the order in which listeners of several objects and scopes are called, edits made inside listeners, subscriptions changed during delivery | The tests follow E7 to E9 and H4; traces that mix model, view and raw listeners are compared per kind. The cases about subscriptions changed during delivery, exceptions and recordings started inside listeners pin behavior the contract leaves open: keep them only as long as C# promises that behavior. | Rules E7 to E9 and H4 decided (2026-11-27); Java and C# changed to them. | | History | 4 | 0 | H | undo and redo of opposite updates | Keep as C# regression tests. | | -| Views and immutables | 42 | 43 | V | read-only projections, live read-only lists, immutable values and their bases, getter-only traits | Keep as C# regression tests. | | -| Equality and copies | 25 | 27 | Q, N | content equality, equality modes, deep copies; shallow copies (not in the contract) | Keep. Shallow copy: C#-only, or a contract rule if every target should offer it. | | -| Reflection | 14 | 14 | F | property order and annotations; type catalog and default metadata (not in the contract) | Keep. | | -| JSON documents | 31 | 13 | J | reference-aware and plain documents, references by value, real-model round trips | Keep. | | -| XML and YAML | 68 | 32 | none | XML and YAML snapshots, nil collections, XML attributes | C#-only, unless XML or YAML documents must pass between languages (then a module, and TypeScript needs it too). JSON is the exchange format today. | | -| Journals, patches, diff, merge, versions | 147 | 204 | none | the V1 change journal and its file format, positional and creation journals, checkpoints, model patches, merges, shared diffs, model versions | Largest area. If change journals are meant to pass between languages, make them a module with a format specification and a few dozen scenarios once the journal design is final (it is a preview); otherwise C#-only. | | -| Validation and schema | 62 | 188 | L for the declared constraints; JSON schema none | configured validation, constraints, multiplicities, JSON schema generation | The declared constraints are contract module L: keep a few C# cases for the C# API. Application rules and JSON schema generation stay C#-only (most of the own lines are schema generation). | | -| Keyed containment, maps, sets | 62 | 12 | K | keyed collections, maps, identity keys, sets of scalars and their events | Contract module K (29 scenarios on all three targets). Trim to the cases that test the C# collection classes beyond the rules. | | -| Behavior delegation and roles | 35 | 0 | B | @DelegateTo bindings, behavior hierarchies, role variants, applied calls | Contract module B. The tests add no runtime line; their models add generator lines (role resolution). Keep the models in a generate-and-compile check and one test per kind of binding; drop the 13 one-test role variants. | | -| Defaults beyond literals | 114 | 77 | K12 (collection defaults), X2 (enum defaults); the rest none | executable, dynamic, managed, hooked and reference defaults and their precedence | Collection and enum defaults are in the contract. Executable and hooked defaults run host code: C#-only. Trim the variants. | | -| Builders and apply | 55 | 31 | none (API shape is unspecified) | builders, applyFrom/applyTo, appended collections | C#-only. | | -| Cursors and traversal | 34 | 321 | none | containment and reference cursors, traversal | C#-only, or drop the feature if no C# user needs it: these tests are the only cover of 321 lines. | | -| External types, enums, codecs | 54 | 50 | X | bindings of custom Java value types, enums, snapshot codecs, untyped objects | Contract module X. Keep the cases about C# codecs and bindings. | | -| Generics, redeclaration, covariance | 93 | 48 | T7, T8 for redeclared properties and scalar type parameters; the rest none | generic model types and bounds, redeclared and covariant properties, untyped lists, concrete bases | The contract covers what all targets generate. The other cases test the C# generator: keep one per generated shape. | | -| Real-model ports | 37 | 30 | partly | models from existing VMF users (DevCom, MiniClang, VFlow, ...) end to end | Keep as acceptance tests. | | -| Feature bundles | 14 | 240 | none | plugin composition and feature persistence | C#-only. | | -| List operations beyond the contract | 12 | 46 | none | sorting and predicate removal on lists, their undo | C#-only, or contract rules if every target should offer sort and removeIf. | | -| Summaries and toString | 5 | 47 | deliberately unspecified | Java-compatible summary and toString formats | Drop, or keep a minimal smoke test: formats are not part of any contract. | | -| C# platform integration | 5 | 26 | none | INotifyPropertyChanged | C#-only. | | +| Views and immutables | 30 | 45 | V | read-only projections, live read-only lists, immutable values and their bases, getter-only traits | Keep as C# regression tests. | | +| Equality and copies | 13 | 27 | Q, N | content equality, equality modes, deep copies; shallow copies (not in the contract) | Keep. Shallow copy: C#-only, or a contract rule if every target should offer it. | | +| Reflection | 8 | 20 | F | property order and annotations; type catalog and default metadata (not in the contract) | Keep. | | +| JSON documents | 31 | 14 | J | reference-aware and plain documents, references by value, real-model round trips | Keep. | | +| XML and YAML | 66 | 32 | none | XML and YAML snapshots, nil collections, XML attributes | C#-only, unless XML or YAML documents must pass between languages (then a module, and TypeScript needs it too). JSON is the exchange format today. | | +| Journals, patches, diff, merge, versions | 117 | 239 | none | the V1 change journal and its file format, positional and creation journals, checkpoints, model patches, merges, shared diffs, model versions | Largest area. If change journals are meant to pass between languages, make them a module with a format specification and a few dozen scenarios once the journal design is final (it is a preview); otherwise C#-only. | | +| Validation and schema | 47 | 192 | L for the declared constraints; JSON schema none | configured validation, constraints, multiplicities, JSON schema generation | The declared constraints are contract module L: keep a few C# cases for the C# API. Application rules and JSON schema generation stay C#-only (most of the own lines are schema generation). | | +| Keyed containment, maps, sets | 50 | 12 | K | keyed collections, maps, identity keys, sets of scalars and their events | Contract module K (29 scenarios on all three targets). Trim to the cases that test the C# collection classes beyond the rules. | | +| Behavior delegation and roles | 27 | 0 | B | @DelegateTo bindings, behavior hierarchies, role variants, applied calls | Contract module B. The tests add no runtime line; their models add generator lines (role resolution). Keep the models in a generate-and-compile check and one test per kind of binding; drop the 13 one-test role variants. | | +| Defaults beyond literals | 79 | 81 | K12 (collection defaults), X2 (enum defaults); the rest none | executable, dynamic, managed, hooked and reference defaults and their precedence | Collection and enum defaults are in the contract. Executable and hooked defaults run host code: C#-only. Trim the variants. | | +| Builders and apply | 32 | 33 | none (API shape is unspecified) | builders, applyFrom/applyTo, appended collections | C#-only. | | +| Cursors and traversal | 21 | 213 | none | containment and reference cursors, traversal | C#-only, or drop the feature if no C# user needs it: these tests are the only cover of 321 lines. | | +| External types, enums, codecs | 48 | 48 | X | bindings of custom Java value types, enums, snapshot codecs, untyped objects | Contract module X. Keep the cases about C# codecs and bindings. | | +| Generics, redeclaration, covariance | 79 | 68 | T7, T8 for redeclared properties and scalar type parameters; the rest none | generic model types and bounds, redeclared and covariant properties, untyped lists, concrete bases | The contract covers what all targets generate. The other cases test the C# generator: keep one per generated shape. | | +| Real-model ports | 34 | 30 | partly | models from existing VMF users (DevCom, MiniClang, VFlow, ...) end to end | Keep as acceptance tests. | | +| Feature bundles | 12 | 246 | none | plugin composition and feature persistence | C#-only. | | +| List operations beyond the contract | 10 | 46 | none | sorting and predicate removal on lists, their undo | C#-only, or contract rules if every target should offer sort and removeIf. | | +| Summaries and toString | 4 | 47 | deliberately unspecified | Java-compatible summary and toString formats | Drop, or keep a minimal smoke test: formats are not part of any contract. | | +| C# platform integration | 3 | 26 | none | INotifyPropertyChanged | C#-only. | | ## Classes per area -**Containment, opposites, references** (169): OrdinaryContainmentTests (35), BulkListAliasTests (19), UnorderedContainmentTests (8), NamedRoleContainmentTests (7), OwningReplacementTests (4), ListReplacementTests (3), HierarchyTests (7), ArchiveTests (8), ReciprocalTests (20), SequenceRoleReciprocalTests (13), InheritedOppositeTests (7), SharedInverseTests (7), NamedInverseTests (2), GetterRoleOwnershipTests (5), GetterRoleReciprocalTests (5), GetterRoleSetOwnershipTests (4), StockReferenceIdentityTests (4), StockCollectionContractTests (3), ShipmentTests (4), ValueMatchingAliasTests (4) +**Containment, opposites, references** (147): OrdinaryContainmentTests (34), BulkListAliasTests (14), UnorderedContainmentTests (7), NamedRoleContainmentTests (6), OwningReplacementTests (2), ListReplacementTests (2), HierarchyTests (4), ArchiveTests (8), ReciprocalTests (17), SequenceRoleReciprocalTests (12), InheritedOppositeTests (5), SharedInverseTests (4), NamedInverseTests (2), GetterRoleOwnershipTests (4), GetterRoleReciprocalTests (4), GetterRoleSetOwnershipTests (3), StockReferenceIdentityTests (4), StockCollectionContractTests (2), ShipmentTests (3), ValueMatchingAliasTests (3), ContainmentMoveTests (7) -**Scalars and scalar lists** (23): ScalarTests (14), CollectionTests (9) +**Scalars and scalar lists** (22): ScalarTests (13), CollectionTests (9) -**Events** (92): ObservationTests (25), ContainmentObservationTests (9), CollectionObservationTests (7), DirectPropertyObservationTests (5), MixedListObservationTests (8), ReferenceListObservationTests (5), ReciprocalListObservationTests (7), ModelIdentitySetObserverTests (12), ModeledRelationshipSetObserverTests (14) +**Events** (70): ObservationTests (15), ContainmentObservationTests (6), CollectionObservationTests (3), DirectPropertyObservationTests (5), MixedListObservationTests (8), ReferenceListObservationTests (1), ModelIdentitySetObserverTests (12), ModeledRelationshipSetObserverTests (14), HandWrittenModelObservationTests (6) -**Listener order and reentrancy** (69): ObserverOrderTests (39), ScalarMembershipObserverRouteTests (30) +**Listener order and reentrancy** (43): ObserverOrderTests (13), ScalarMembershipObserverRouteTests (30) **History** (4): ReciprocalPropertyHistoryTests (4) -**Views and immutables** (42): ReadOnlyTests (2), ProjectedRelationshipTests (2), OpaquePropertyProjectionTests (2), ProjectedListLifetimeTests (3), ProjectedListObservationTests (4), ImmutableValueTests (3), ImmutableCollectionTests (7), ImmutableDataBasesTests (3), ImmutableAncestryTests (2), ImmutableSecondaryTests (2), ImmutableParentOrderTests (1), ImmutableCovariantTests (1), ImmutablePortSettingsTests (4), GetterOnlyTraitTests (6) +**Views and immutables** (30): ProjectedRelationshipTests (1), OpaquePropertyProjectionTests (2), ProjectedListLifetimeTests (1), ImmutableValueTests (2), ImmutableCollectionTests (6), ImmutableDataBasesTests (3), ImmutableAncestryTests (2), ImmutableSecondaryTests (2), ImmutableParentOrderTests (1), ImmutableCovariantTests (1), ImmutablePortSettingsTests (3), GetterOnlyTraitTests (6) -**Equality and copies** (25): ContentEqualityTests (8), DeepCopyTests (4), MutableEqualityTests (1), InheritedEqualityTests (1), ImmutableEqualityTests (1), ShallowCopyTests (10) +**Equality and copies** (13): ContentEqualityTests (4), MutableEqualityTests (1), InheritedEqualityTests (1), ImmutableEqualityTests (1), ShallowCopyTests (6) -**Reflection** (14): ReflectionTests (5), ReflectionAnnotationTests (2), StockPropertyOrderTests (4), ModelTypeCatalogTests (3) +**Reflection** (8): ReflectionTests (4), ReflectionAnnotationTests (1), StockPropertyOrderTests (1), ModelTypeCatalogTests (1), ReflectionBindingTests (1) **JSON documents** (31): TypedValueReferencesTests (9), WorkshopGraphTests (15), StockJsonTests (3), StockCollectionPersistenceTests (4) -**XML and YAML** (68): XmlSnapshotTests (27), YamlTests (20), DeepXmlSnapshotTests (4), DeepYamlSnapshotTests (4), XmlNilCollectionsTests (10), ExternalXmlAttributeTests (3) +**XML and YAML** (66): XmlSnapshotTests (27), YamlTests (18), DeepXmlSnapshotTests (4), DeepYamlSnapshotTests (4), XmlNilCollectionsTests (10), ExternalXmlAttributeTests (3) -**Journals, patches, diff, merge, versions** (147): JournalTests (23), CreationJournalTests (18), JournalHistoryTests (12), PositionalJournalTests (8), CreationCollectionJournalTests (5), MembershipJournalTests (5), ExternalValueJournalTests (7), JournalPreviewVersionTests (6), JournalRegistryCompositionTests (3), JournalBindingTests (3), JournalCheckpointFactoryTests (1), JournalNativeCheckpointFactoryTests (2), KeyedUnorderedJournalTests (2), NamedRoleJournalTests (1), SecondaryReciprocalJournalTests (3), ModelPatchTests (19), ModelPatchAliasTests (1), ModelPatchCopyReferenceTests (2), ModelPatchImmutableTests (1), ModelPatchUndoIdentityTests (2), ModelMergeAliasTests (2), StockModelMergeTests (4), StockModelSharedDiffTests (8), ModelVersionTests (7), ReadOnlyReplayCompatibilityTests (2) +**Journals, patches, diff, merge, versions** (117): JournalTests (17), CreationJournalTests (18), JournalHistoryTests (9), PositionalJournalTests (7), CreationCollectionJournalTests (5), MembershipJournalTests (5), ExternalValueJournalTests (7), JournalPreviewVersionTests (6), JournalRegistryCompositionTests (3), JournalBindingTests (3), JournalCheckpointFactoryTests (1), JournalNativeCheckpointFactoryTests (2), KeyedUnorderedJournalTests (2), NamedRoleJournalTests (1), SecondaryReciprocalJournalTests (3), ModelPatchTests (14), ModelPatchUndoIdentityTests (1), StockModelMergeTests (2), StockModelSharedDiffTests (6), ModelVersionTests (4), ReadOnlyReplayCompatibilityTests (1) -**Validation and schema** (62): ConfiguredValidationTests (21), SnapshotSchemaTests (33), StockValidationSchemaTests (7), OwningValidationTests (1) +**Validation and schema** (47): ConfiguredValidationTests (10), SnapshotSchemaTests (29), StockValidationSchemaTests (7), OwningValidationTests (1) -**Keyed containment, maps, sets** (62): KeyedTests (23), KeyedUnorderedOwnershipTests (11), KeyedGetterRoleOwnershipTests (4), KeyedOwningPredicateTests (2), KeyedBuilderCallbackTests (1), KeyedRedeclarationTests (2), GenericKeyedTests (3), GenericKeyTests (3), GenericIdentityKeyTests (3), StockPlainMapTests (5), ScalarMapObservationTests (3), ScalarSetObservationTests (2) +**Keyed containment, maps, sets** (50): KeyedTests (20), KeyedUnorderedOwnershipTests (8), KeyedGetterRoleOwnershipTests (3), KeyedOwningPredicateTests (2), KeyedBuilderCallbackTests (1), KeyedRedeclarationTests (1), GenericKeyedTests (2), GenericKeyTests (3), GenericIdentityKeyTests (3), StockPlainMapTests (5), ScalarMapObservationTests (2) -**Behavior delegation and roles** (35): BehaviorTests (4), BehaviorHierarchyTests (4), CombinedBehaviorTests (1), AbstractRoleBehaviorTests (1), CovariantRoleTests (1), DeepRoleTests (1), LocalBindingTests (1), NestedRoleTests (1), PrimarySpineTests (1), QualifiedBindingTests (1), RepeatedRoleTests (1), RoleContestTests (1), SecondaryBehaviorTests (1), SharedRoleTests (1), SiblingRoleTests (1), TrioRoleTests (1), ImmutableBehaviorTests (4), AppliedCallsTests (4), AbstractArgumentsTests (4), StockDelegationTests (1) +**Behavior delegation and roles** (27): BehaviorTests (1), BehaviorHierarchyTests (1), CombinedBehaviorTests (1), AbstractRoleBehaviorTests (1), CovariantRoleTests (1), DeepRoleTests (1), LocalBindingTests (1), NestedRoleTests (1), PrimarySpineTests (1), QualifiedBindingTests (1), RepeatedRoleTests (1), RoleContestTests (1), SecondaryBehaviorTests (1), SharedRoleTests (1), SiblingRoleTests (1), TrioRoleTests (1), ImmutableBehaviorTests (3), AppliedCallsTests (4), AbstractArgumentsTests (3), StockDelegationTests (1) -**Defaults beyond literals** (114): ExecutableDefaultTests (8), ImmutableExecutableDefaultTests (2), DynamicDefaultsTests (9), InheritedManagedDefaultsTests (16), HookedManagedDefaultsTests (12), HookReferenceDefaultsTests (5), InheritedMixedDefaultsTests (3), InheritedReferenceDefaultsTests (1), MixedDefaultTests (2), DefaultTests (4), DefaultPrecedenceTests (2), CollectionDefaultTests (8), StockCollectionDefaultTests (2), ReferenceDefaultTests (8), StockReferenceDefaultTests (6), ProjectedDefaultsTests (2), TraitProviderDefaultsTests (2), ScalarHookTests (7), ConstantExpressionTests (3), ReflectionDefaultTests (4), SnapshotCollectionBehaviorTests (8) +**Defaults beyond literals** (79): ExecutableDefaultTests (5), ImmutableExecutableDefaultTests (2), DynamicDefaultsTests (5), InheritedManagedDefaultsTests (13), HookedManagedDefaultsTests (6), HookReferenceDefaultsTests (2), InheritedMixedDefaultsTests (1), InheritedReferenceDefaultsTests (1), MixedDefaultTests (2), DefaultTests (1), DefaultPrecedenceTests (2), CollectionDefaultTests (7), StockCollectionDefaultTests (1), ReferenceDefaultTests (4), StockReferenceDefaultTests (3), ProjectedDefaultsTests (1), TraitProviderDefaultsTests (2), ScalarHookTests (7), ConstantExpressionTests (3), ReflectionDefaultTests (3), SnapshotCollectionBehaviorTests (8) -**Builders and apply** (55): ArchiveBuilderTests (2), OrdinaryOwningBuilderTests (7), OrderedReferenceBuilderTests (3), StockReferenceBuilderTests (9), StockReciprocalBuilderTests (7), StockReciprocalListBuilderTests (4), StockManagedBuilderTests (4), StockOwnershipBuilderTests (3), StockScalarGetterBuilderTests (2), StockSeriesBuilderTests (2), StockSharedParentBuilderTests (5), StockSingularOwningBuilderTests (2), StockAbstractCustomerBuilderTests (2), ScalarCollectionApplyTests (3) +**Builders and apply** (32): ArchiveBuilderTests (2), OrdinaryOwningBuilderTests (4), OrderedReferenceBuilderTests (3), StockReferenceBuilderTests (6), StockReciprocalListBuilderTests (2), StockManagedBuilderTests (3), StockOwnershipBuilderTests (3), StockScalarGetterBuilderTests (1), StockSharedParentBuilderTests (3), StockSingularOwningBuilderTests (1), StockAbstractCustomerBuilderTests (2), ScalarCollectionApplyTests (2) -**Cursors and traversal** (34): ContainmentCursorTests (10), ContainmentCursorAncestryTests (4), ReferenceCursorTests (8), RetainedContainmentCursorTests (5), UnorderedCursorTests (4), StockCursorInsertTests (1), StockTraversalTests (2) +**Cursors and traversal** (21): ContainmentCursorTests (7), ReferenceCursorTests (6), RetainedContainmentCursorTests (2), UnorderedCursorTests (3), StockCursorInsertTests (1), StockTraversalTests (2) -**External types, enums, codecs** (54): GeneratedExternalBindingTests (8), StockExternalBindingTests (8), StockRawExternalTypesTests (6), EnumBindingTests (4), GenericEnumBindingTests (6), ExternalSnapshotCodecTests (14), OpenScalarChannelTests (4), LegacyObjectTests (4) +**External types, enums, codecs** (48): GeneratedExternalBindingTests (8), StockExternalBindingTests (4), StockRawExternalTypesTests (6), EnumBindingTests (4), GenericEnumBindingTests (5), ExternalSnapshotCodecTests (13), OpenScalarChannelTests (4), LegacyObjectTests (4) -**Generics, redeclaration, covariance** (93): GenericBoundTests (7), NominalBoundTests (6), GenericValueTests (4), GenericScalarTests (2), NumericGenericTests (2), GenericRoleMetadataTests (2), RedeclarationTests (5), CollectionRedeclarationTests (13), ExactRedeclarationsTests (4), UntypedListTests (10), ValueChoiceTests (7), CovarianceTests (5), ArrayDeclarationTests (4), DelegatedListsTests (4), ConcreteBasesTests (11), StockPropertyInheritanceTests (2), SecondaryScalarTests (4), MixedManifestTests (1) +**Generics, redeclaration, covariance** (79): GenericBoundTests (5), NominalBoundTests (6), GenericValueTests (4), GenericScalarTests (2), NumericGenericTests (2), GenericRoleMetadataTests (2), RedeclarationTests (2), CollectionRedeclarationTests (12), ExactRedeclarationsTests (4), UntypedListTests (10), ValueChoiceTests (4), CovarianceTests (4), ArrayDeclarationTests (4), DelegatedListsTests (3), ConcreteBasesTests (9), StockPropertyInheritanceTests (1), SecondaryScalarTests (4), MixedManifestTests (1) -**Real-model ports** (37): StockDevComTests (8), StockMiniClangTests (4), StockVFlowTests (3), StockNamedHostTests (5), StockUnparserMarkerTests (1), StockModelRegistryTests (3), StockCodeEntityTests (1), StockApplicationAliasTests (8), WarehousePromotionTests (4) +**Real-model ports** (34): StockDevComTests (8), StockMiniClangTests (3), StockVFlowTests (3), StockNamedHostTests (5), StockUnparserMarkerTests (1), StockModelRegistryTests (2), StockCodeEntityTests (1), StockApplicationAliasTests (7), WarehousePromotionTests (4) -**Feature bundles** (14): FeatureBundleTests (14) +**Feature bundles** (12): FeatureBundleTests (12) -**List operations beyond the contract** (12): ListPredicateTests (3), OwningPredicateTests (2), ScalarListSortTests (4), StockOwningSortTests (3) +**List operations beyond the contract** (10): ListPredicateTests (2), OwningPredicateTests (1), ScalarListSortTests (4), StockOwningSortTests (3) -**Summaries and toString** (5): ModelSummaryTests (3), MutableToStringTests (1), ImmutableToStringTests (1) +**Summaries and toString** (4): ModelSummaryTests (3), MutableToStringTests (1) -**C# platform integration** (5): NativePropertyChangedTests (5) +**C# platform integration** (3): NativePropertyChangedTests (3) diff --git a/conformance/applied-call-csharp/AbstractArgumentsTests.cs b/conformance/applied-call-csharp/AbstractArgumentsTests.cs index 207aac9c..17ec0a67 100644 --- a/conformance/applied-call-csharp/AbstractArgumentsTests.cs +++ b/conformance/applied-call-csharp/AbstractArgumentsTests.cs @@ -16,19 +16,6 @@ public sealed class AbstractArgumentsTests _ => throw new ArgumentException($"Unexpected journal model {value.GetType()}.", nameof(value)) }); - [Fact] - public void DelegatesAcceptTheNativePrimaryAndCompanionContracts() - { - var rename = typeof(ArgumentCallHost).GetMethod(nameof(ArgumentCallHost.Rename))!; - Assert.Equal(typeof(PrimaryArgument), rename.GetParameters()[0].ParameterType); - Assert.Equal(typeof(PrimaryArgument), rename.ReturnType); - var relabel = typeof(ArgumentCallHost).GetMethod(nameof(ArgumentCallHost.Relabel))!; - Assert.Equal(typeof(ISecondaryArgument), relabel.GetParameters()[0].ParameterType); - Assert.Equal(typeof(ISecondaryArgument), relabel.ReturnType); - - Invoke(Specimen()); - } - [Theory] [InlineData("json")] [InlineData("yaml")] diff --git a/conformance/behavior-csharp/BehaviorTests.cs b/conformance/behavior-csharp/BehaviorTests.cs index d393cacf..c11a190e 100644 --- a/conformance/behavior-csharp/BehaviorTests.cs +++ b/conformance/behavior-csharp/BehaviorTests.cs @@ -7,81 +7,6 @@ namespace Vmf.CSharp.Conformance; public class BehaviorTests { - [Fact] - public void NativeSignaturesAndConstructorHookUseTheTypedModel() - { - int firstHook = MutableGauge.HookValues.Count; - var defaulted = new MutableGauge(); - var built = MutableGauge.NewBuilder().WithBase(13).Build(); - Assert.Equal(new (int, string?)[] { (0, null), (0, null) }, MutableGauge.HookValues.Skip(firstHook)); - Assert.Equal(8, defaulted.Base); - Assert.Equal("ready", defaulted.State); - Assert.Equal(13, built.Base); - Assert.Equal("ready", built.State); - Assert.Null(defaulted.BehaviorOverride); - Assert.Null(built.BehaviorOverride); - Assert.Equal(15, built.Adjust(2)); - Assert.Equal(11, built.Adjust((int?)2)); - Assert.Null(built.Adjust((int?)null)); - Assert.Equal(10, built.Sum(2, 3, 5)); - Assert.Equal("ready", built.Diagnose(true)); - Assert.Equal("ok", built.Diagnose(false)); - var input = CallResult.NewBuilder().WithText("input").Build(); - Assert.Equal("input!", built.Compose(input, "!")?.Text); - Assert.Null(built.Compose(null, "!")); - Assert.DoesNotContain(typeof(IReadOnlyMutableGauge).GetMethods(), method => method.Name == nameof(built.Adjust)); - } - - [Fact] - public void LiveJournalCopiesRunOneFreshHookAndReplaceItsSeededManagedStorage() - { - int baseline = HookedJournalCheckpoint.HookCount; - var original = new HookedJournalCheckpoint(); - var field = ModelSnapshot.Reflection.Reflect(original).FindProperty("slots")!; - Assert.Equal([1], original.Slots); - field.SetDefault(new[] { 2 }); - field.Reset(); - Assert.Equal(1, original.Invocation()); - Assert.Equal(2, original.Invocation()); - var binding = new JournalBinding("hook-checkpoint", 1, _ => "root"); - var empty = new ChangeJournal("hook-checkpoint", 1, "root", "base", 0, []); - var copy = JournalReplayer.Replay(original, binding, "base", empty, ModelSnapshot.Registry); - Assert.Equal(baseline + 2, HookedJournalCheckpoint.HookCount); - Assert.Equal([2], copy.AsReadOnly().Slots); - Assert.Equal(1, copy.Invocation()); - Assert.Equal(3, original.Invocation()); - - using var recorder = JournalRecorder.Start(original, ModelSnapshot.Registry, binding, "base", 0); - Assert.Equal(baseline + 3, HookedJournalCheckpoint.HookCount); - original.Slots.Add(3); - var journal = recorder.Finish(); - Assert.Equal(1, journal.WireVersion); - Assert.Single(journal.Transactions); - var restored = JournalReplayer.Replay(copy, binding, "base", journal, ModelSnapshot.Registry); - Assert.Equal(baseline + 4, HookedJournalCheckpoint.HookCount); - Assert.Equal([2, 3], restored.Slots); - Assert.Equal([2], copy.Slots); - Assert.Equal(1, restored.Invocation()); - var restoredField = ModelSnapshot.Reflection.Reflect(restored).FindProperty("slots")!; - Assert.True(restoredField.IsSet); - restoredField.Reset(); - Assert.Equal([2], restored.Slots); - Assert.Equal([2, 3], original.Slots); - } - - [Fact] - public void MethodOnlyBindingIsLazyAndKeepsStatePerInstance() - { - int before = SignalGauge.BindingCount; - var first = SignalGauge.NewBuilder().WithLevel(10).Build(); - var second = new SignalGauge(); - Assert.Equal(before, SignalGauge.BindingCount); - Assert.Equal(14, first.Signal(3)); - Assert.Equal(15, first.Signal(3)); - Assert.Equal(before + 1, SignalGauge.BindingCount); - Assert.Equal(8, second.Signal(3)); - Assert.Equal(before + 2, SignalGauge.BindingCount); - } [Fact] public void PerInstanceReplacementAffectsNativeEditsAndResetsOnCopyAndInterchange() diff --git a/conformance/behavior-csharp/HookedManagedDefaultsTests.cs b/conformance/behavior-csharp/HookedManagedDefaultsTests.cs index 06455e55..cba5cafa 100644 --- a/conformance/behavior-csharp/HookedManagedDefaultsTests.cs +++ b/conformance/behavior-csharp/HookedManagedDefaultsTests.cs @@ -11,53 +11,6 @@ public sealed class HookedManagedDefaultsTests ["numbers:1", "token:1", "values:1", "hook:0", "numbers:2", "token:2", "values:2"]; private const string MapInitialization = "seed-a>|seed-b>|>saved-2|saved-2>"; - [Fact] - public void NewAndBuilderConstructWithTheSamePhasesAsJava() - { - ManagedDefaultBehaviorState.Reset(); - var direct = new HookedManagedDefaults(); - Assert.Equal(["hook:0", "numbers:1", "token:1", "values:1"], ManagedDefaultBehaviorState.Phases); - AssertState(direct, [1], 100, "saved-1", 1, "seed-a>|seed-b>|>saved-1"); - - ManagedDefaultBehaviorState.Reset(); - var builder = HookedManagedDefaults.NewBuilder(); - Assert.Equal(["numbers:1", "token:1", "values:1"], ManagedDefaultBehaviorState.Phases); - var built = builder.WithNumbers([27]).WithToken(57).WithValues([new("wire", 31)]).Build(); - Assert.Equal(StagedPhases, ManagedDefaultBehaviorState.Phases); - AssertState(built, [27], 57, "wire", 31, MapInitialization + "|>wire"); - } - - [Theory] - [InlineData("plain")] - [InlineData("typed")] - [InlineData("references")] - public void SnapshotStagesDefaultsBeforeItsConstructorAndRetainsExplicitValues(string profile) - { - ManagedDefaultBehaviorState.Reset(); - var omitted = Read(profile); - Assert.Equal(StagedPhases, ManagedDefaultBehaviorState.Phases); - AssertState(omitted, [1], 100, "saved-1", 1, MapInitialization + "|>saved-1"); - if (profile == "references") Assert.Same(omitted, omitted.Link); - - ManagedDefaultBehaviorState.Reset(); - var partial = Read(profile, "\"token\":57"); - Assert.Equal(StagedPhases, ManagedDefaultBehaviorState.Phases); - AssertState(partial, [1], 57, "saved-1", 1, MapInitialization + "|>saved-1"); - - ManagedDefaultBehaviorState.Reset(); - var explicitValues = Read(profile, "\"numbers\":[27],\"token\":57,\"values\":{\"wire\":31}"); - Assert.Equal(StagedPhases, ManagedDefaultBehaviorState.Phases); - AssertState(explicitValues, [27], 57, "wire", 31, MapInitialization + "|>wire"); - - ManagedDefaultBehaviorState.Reset(); - var cleared = Read(profile, "\"numbers\":[],\"token\":0,\"values\":{}"); - Assert.Equal(StagedPhases, ManagedDefaultBehaviorState.Phases); - Assert.Empty(cleared.Numbers); - Assert.Equal(0, cleared.Token); - Assert.Empty(cleared.Values); - Assert.Equal(MapInitialization, cleared.ObservedMapEdits()); - } - [Theory] [InlineData(false, VmfDocumentFormat.Json)] [InlineData(false, VmfDocumentFormat.Xml)] @@ -132,28 +85,6 @@ void VerifyRestored(HookedManagedDefaults restored, string state) } } - [Fact] - public void AlreadySupportedModelWithoutHookAlsoRetainsItsStagedValues() - { - ManagedDefaultBehaviorState.Reset(); - var model = ModelSnapshot.ReadPlain("{}"); - Assert.Equal(["numbers:1", "values:1", "numbers:2", "values:2"], ManagedDefaultBehaviorState.Phases); - Assert.Equal(1, Assert.Single(model.Numbers)); - Assert.Equal(1, model.Values["saved-1"]); - } - - [Fact] - public void AThrowingMapCallbackStopsAfterTheCommittedRemoval() - { - ManagedDefaultBehaviorState.Reset(); - ManagedDefaultBehaviorState.ThrowOnRemoval = true; - var error = Assert.Throws(() => Read("plain")); - Assert.Equal("stop after seed-a", error.Message); - Assert.Equal(StagedPhases, ManagedDefaultBehaviorState.Phases); - var owner = Assert.IsType(ManagedDefaultBehaviorState.LastOwner); - AssertState(owner, [2], 200, "seed-b", 2, "seed-a>"); - } - private static void AssertState(HookedManagedDefaults model, int[] numbers, int token, string key, int value, string events) { diff --git a/conformance/behavior-csharp/InheritedManagedDefaultsTests.cs b/conformance/behavior-csharp/InheritedManagedDefaultsTests.cs index c9cf7b3e..7ee06f4b 100644 --- a/conformance/behavior-csharp/InheritedManagedDefaultsTests.cs +++ b/conformance/behavior-csharp/InheritedManagedDefaultsTests.cs @@ -7,32 +7,6 @@ namespace Vmf.CSharp.Conformance; public sealed partial class InheritedManagedDefaultsTests { - [Fact] - public void ConstructorAndBuilderApplyInheritedDefaultsAndKeepHookObservers() - { - InheritedManagedDefaultsState.Reset(); - Assert.NotNull(ModelSnapshot.TypeCatalog.Find(typeof(InheritedManagedValues))?.FindProperty("numbers")); - Assert.Empty(InheritedManagedDefaultsState.Phases); - - var direct = new InheritedManagedValues(); - AssertState(direct, "values", false, [1], "saved-1", 1, ["[99]>[1]"], ["seed-a>", "seed-b>", ">saved-1"]); - - InheritedManagedDefaultsState.Reset(); - var builder = InheritedManagedValues.NewBuilder(); - Assert.Equal(["numbers:1", "settings:1"], InheritedManagedDefaultsState.Phases); - Assert.Null(InheritedManagedDefaultsState.LastOwner); - AssertStaged(builder.Build(), "values"); - - InheritedManagedDefaultsState.Reset(); - var references = ModelSnapshot.Read( - """{"picked":"child-1","child":{"@vmf-id":"child-1","label":"child"}}"""); - AssertStaged(references, "references"); - Assert.Same(references.Child, references.Selection); - - InheritedManagedDefaultsState.Reset(); - var cleared = ModelSnapshot.ReadPlain("""{"counts":[],"settings":{}}"""); - AssertStaged(cleared, "values", cleared: true); - } [Theory] [InlineData(false, VmfDocumentFormat.Json)] @@ -93,31 +67,6 @@ void VerifyProfile(bool typedValues) } } - [Fact] - public void DerivedConstructorAndBuilderUseOnlyTheSelectedHook() - { - InheritedManagedDefaultsState.Reset(); - Assert.NotNull(ModelSnapshot.TypeCatalog.Find(typeof(InheritedManagedOverridden))?.FindProperty("numbers")); - Assert.Empty(InheritedManagedDefaultsState.Phases); - - AssertDirect(new InheritedManagedDerived(), "references"); - InheritedManagedDefaultsState.Reset(); - AssertDirect(new InheritedManagedOverridden(), "replacement"); - - InheritedManagedDefaultsState.Reset(); - var builder = InheritedManagedDerived.NewBuilder(); - Assert.Equal(["numbers:1", "settings:1"], InheritedManagedDefaultsState.Phases); - Assert.Null(InheritedManagedDefaultsState.LastOwner); - AssertStaged(builder.Build(), "references"); - - InheritedManagedDefaultsState.Reset(); - var cleared = InheritedManagedOverridden.NewBuilder().WithNumbers([]).WithSettings([]).Build(); - AssertStaged(cleared, "replacement", cleared: true); - - static void AssertDirect(InheritedManagedFields owner, string kind) => - AssertState(owner, kind, false, [1], "saved-1", 1, ["[99]>[1]"], ["seed-a>", "seed-b>", ">saved-1"]); - } - [Theory] [InlineData(false, VmfDocumentFormat.Json)] [InlineData(false, VmfDocumentFormat.Xml)] diff --git a/conformance/behavior-csharp/RedeclaredManagedDefaultsTests.cs b/conformance/behavior-csharp/RedeclaredManagedDefaultsTests.cs index 40680ed4..bd60101a 100644 --- a/conformance/behavior-csharp/RedeclaredManagedDefaultsTests.cs +++ b/conformance/behavior-csharp/RedeclaredManagedDefaultsTests.cs @@ -6,18 +6,6 @@ namespace Vmf.CSharp.Conformance; public sealed partial class InheritedManagedDefaultsTests { - [Fact] - public void RedeclaredManagedCollectionsImportParentStorageWithoutEvaluatingOldDefaults() - { - InheritedManagedDefaultsState.Reset(); - var parent = new InheritedManagedReferences(); - InheritedManagedDefaultsState.Reset(); - var imported = RedeclaredManagedReplacement.NewBuilder().AppendCollections(false).ApplyFrom(parent).Build(); - Assert.Equal([1], imported.Numbers); - Assert.Equal(new KeyValuePair("saved-1", 1), Assert.Single(imported.Settings)); - Assert.Equal(["alternative-numbers:1", "alternative-settings:1", "hook:references", - "alternative-numbers:2", "alternative-settings:2"], InheritedManagedDefaultsState.Phases); - } [Fact] public void ManagedCollectionRedeclarationsSelectEffectiveConstructorBuilderAndSnapshotDefaults() diff --git a/conformance/behavior-hierarchy-csharp/BehaviorHierarchyTests.cs b/conformance/behavior-hierarchy-csharp/BehaviorHierarchyTests.cs index 5a4705aa..53ef7982 100644 --- a/conformance/behavior-hierarchy-csharp/BehaviorHierarchyTests.cs +++ b/conformance/behavior-hierarchy-csharp/BehaviorHierarchyTests.cs @@ -6,86 +6,6 @@ namespace Vmf.CSharp.Conformance; public class BehaviorHierarchyTests { - [Fact] - public void RuntimeTypeSelectsOneHookBeforeDefaultsAndRetainsLazyInheritedBindings() - { - int priorHooks = Engine.HookValues.Count; - int priorFastHooks = FastEngine.FastHookValues.Count; - int priorBindings = Engine.DefaultBindingCount; - var ordinary = Engine.NewBuilder().WithPower(12).Build(); - var inherited = InheritedEngine.NewBuilder().WithPower(13).WithRate(15).Build(); - var fast = FastEngine.NewBuilder().WithPower(14).WithBonus(40).Build(); - - Assert.Equal(new (Type, int, int?)[] { (typeof(Engine), 0, null), (typeof(InheritedEngine), 0, 0) }, - Engine.HookValues.Skip(priorHooks)); - Assert.Equal(new[] { (0, 0) }, FastEngine.FastHookValues.Skip(priorFastHooks)); - Assert.Equal(priorBindings + 2, Engine.DefaultBindingCount); - Assert.Equal(15, inherited.Rate); - Assert.Equal(40, fast.Bonus); - Assert.Equal(14, ordinary.Transform(2)); - Assert.Equal(15, inherited.Transform(2)); - - Engine baseView = fast; - Assert.Equal(56, baseView.Transform(2)); - Assert.Equal(priorBindings + 2, Engine.DefaultBindingCount); - Assert.Equal("base:14", baseView.Label("base")); - Assert.Equal(priorBindings + 3, Engine.DefaultBindingCount); - Assert.Equal(priorHooks + 2, Engine.HookValues.Count); - Assert.Null(baseView.BehaviorOverride); - Assert.Null(fast.BehaviorOverride); - Assert.DoesNotContain(typeof(IReadOnlyEngine).GetMethods(), method => method.Name == nameof(ordinary.Transform)); - } - - [Fact] - public void BaseTypedReplacementRequiresTheConcreteBehaviorContract() - { - var fast = FastEngine.NewBuilder().WithPower(14).WithBonus(40).Build(); - Engine baseView = fast; - var ordinary = Engine.NewBuilder().WithPower(12).Build(); - Assert.Throws(() => baseView.ReplaceBehavior(new EngineReplacement())); - Assert.Null(baseView.BehaviorOverride); - Assert.Equal(56, baseView.Transform(2)); - - var replacement = new FastReplacement(); - baseView.ReplaceBehavior(replacement); - Assert.Same(replacement, baseView.BehaviorOverride); - Assert.Same(replacement, fast.BehaviorOverride); - Assert.Equal(102, baseView.Transform(2)); - Assert.Equal("x:override", baseView.Label("x")); - Assert.Same(fast, replacement.LastCaller); - Assert.Equal(14, ordinary.Transform(2)); - - var inherited = InheritedEngine.NewBuilder().WithPower(13).Build(); - Engine inheritedBase = inherited; - Assert.Throws(() => inheritedBase.ReplaceBehavior(replacement)); - var inheritedReplacement = new InheritedReplacement(); - inherited.ReplaceBehavior(inheritedReplacement); - Assert.Same(inheritedReplacement, inheritedBase.BehaviorOverride); - Assert.Same(inheritedReplacement, inherited.BehaviorOverride); - Assert.Equal(102, inheritedBase.Transform(2)); - } - - [Fact] - public void ClosedGenericModelExposesItsCallableWithoutEagerBinding() - { - int priorBindings = IntLookup.DefaultBindingCount; - var lookup = IntLookup.NewBuilder().WithValue(5).Build(); - Lookup typed = lookup; - Assert.Equal(5, typed.Value); - Assert.Equal(priorBindings, IntLookup.DefaultBindingCount); - Assert.Equal(13, typed.Metric(8)); - Assert.Equal(14, typed.Metric(9)); - Assert.Equal(priorBindings + 1, IntLookup.DefaultBindingCount); - Assert.DoesNotContain(typeof(IReadOnlyLookup).GetMethods(), method => method.Name == nameof(typed.Metric)); - - Assert.Throws(() => typed.ReplaceBehavior(new LookupReplacement())); - var replacement = new IntLookupReplacement(); - typed.ReplaceBehavior(replacement); - Assert.Same(replacement, lookup.BehaviorOverride); - Assert.Same(replacement, typed.BehaviorOverride); - Assert.Equal(58, typed.Metric(8)); - Assert.Same(lookup, replacement.LastCaller); - } [Fact] public void CopyAndTypedSnapshotRetainSubtypeDataAndRestoreDefaultBindings() @@ -173,8 +93,6 @@ public int Transform(Engine caller, int delta) private sealed class FastReplacement : EngineReplacement, FastEngine.Behavior; - private sealed class InheritedReplacement : EngineReplacement, InheritedEngine.Behavior; - private class LookupReplacement : Lookup.Behavior { internal Lookup? LastCaller { get; private set; } diff --git a/conformance/collection-default-csharp/CollectionDefaultTests.cs b/conformance/collection-default-csharp/CollectionDefaultTests.cs index 7850c7a6..9db0c48d 100644 --- a/conformance/collection-default-csharp/CollectionDefaultTests.cs +++ b/conformance/collection-default-csharp/CollectionDefaultTests.cs @@ -140,31 +140,6 @@ public void ManagedCollectionDefaultsAreDefensivelyCapturedAndReflectedFreshly() Assert.Equal(new object?[] { 3, 5 }, Assert.IsAssignableFrom>(Field(restored, "numbers").DefaultValue)); } - [Fact] - public void MutableAndImmutableBuildersCaptureDefaultsAndApplyExplicitValues() - { - int before = CollectionDefaultBindings.NumberCalls; - var builder = ManagedSamples.NewBuilder(); - Assert.Equal(before + 1, CollectionDefaultBindings.NumberCalls); - var mutable = builder.WithNumbers([9]).WithOptions([]).Build(); - Assert.Equal(before + 2, CollectionDefaultBindings.NumberCalls); - Assert.Equal([9], mutable.Numbers); - Assert.Empty(mutable.Options); - - before = CollectionDefaultBindings.NumberCalls; - var candidate = new List { 8 }; - var frozenBuilder = FrozenSamples.NewBuilder().WithNumbers(candidate); - candidate.Add(7); - Assert.Equal(before + 1, CollectionDefaultBindings.NumberCalls); - var frozen = frozenBuilder.Build(); - Assert.Equal(before + 1, CollectionDefaultBindings.NumberCalls); - Assert.Equal([8], frozen.Numbers); - Assert.False(frozen.Numbers is ICollection numbers && !numbers.IsReadOnly); - Assert.False(Field(frozen, "numbers").CanSetDefault); - Assert.Equal([3, 5], new FrozenSamples().Numbers); - Assert.Empty(new FrozenSamples(numbers: []).Numbers); - } - [Fact] public void JavaAndCSharpSnapshotsPreserveExplicitEmptyAndOmittedCollections() { diff --git a/conformance/collection-redeclaration-csharp/CollectionRedeclarationTests.cs b/conformance/collection-redeclaration-csharp/CollectionRedeclarationTests.cs index db00a0d3..5c8c1352 100644 --- a/conformance/collection-redeclaration-csharp/CollectionRedeclarationTests.cs +++ b/conformance/collection-redeclaration-csharp/CollectionRedeclarationTests.cs @@ -66,31 +66,6 @@ public void MutableRedeclarationsReuseTheBaseCollectionAndRetainTheirContracts() Assert.Null(extra.Basis); } - [Fact] - public void ImmutableAndClosedGenericRedeclarationsKeepEffectiveTypesAndValues() - { - var source = new List { 7, 8 }; - var derived = FrozenVariant.NewBuilder().WithNumbers(source).Build(); - source.Clear(); - FrozenBasis parent = derived; - Assert.Same(derived.Numbers, parent.Numbers); - Assert.Same(derived.AsReadOnly(), derived); - Assert.Equal([7, 8], parent.Numbers); - Assert.False(parent.Numbers is ICollection collection && !collection.IsReadOnly); - Assert.ThrowsAny(() => FrozenVariant.NewBuilder().WithNumbers([1, 2, 3, 4])); - var property = ModelSnapshot.Reflection.Reflect(parent).FindProperty("numbers")!; - Assert.Equal("numbers", property.WireName); - Assert.EndsWith(".FrozenVariant", property.DeclaringType); - - var integral = CreateNumeric(); - NumericSeries openBase = integral; - Assert.Same(openBase.Readings, integral.Readings); - Assert.Same(openBase.Marks, integral.Marks); - Assert.Equal([long.MinValue, 0L], openBase.Readings); - Assert.Equal(long.MaxValue, integral.Marks["limit"]); - Assert.Null(integral.Marks["unknown"]); - } - [Fact] public void RedeclaredAliasesAndIdentitiesRoundTripThroughJavaAndCSharp() { diff --git a/conformance/concrete-base-csharp/ConcreteBasesTests.cs b/conformance/concrete-base-csharp/ConcreteBasesTests.cs index 1a47a474..0a407b41 100644 --- a/conformance/concrete-base-csharp/ConcreteBasesTests.cs +++ b/conformance/concrete-base-csharp/ConcreteBasesTests.cs @@ -156,59 +156,6 @@ public void ScalarHistoryAppliesToAnotherImplementationOfTheSameSecondaryRole() source.VmfChanges.Stop(); } - [Fact] - public void PrimaryClassAndSecondaryContractShareDefaultsIdentityAndReflection() - { - var value = new JoinedRecord(); - PrimaryRecord primary = value; - ISecondaryRecord secondary = value; - Assert.Same(primary, secondary); - Assert.Equal(5, primary.Level); - Assert.Equal(11, secondary.Weight); - - var reflection = ModelSnapshot.Reflection.Reflect(secondary); - Assert.Equal(5, reflection.Properties.Count); - Assert.Equal("shared", reflection.FindProperty("title")!.Get()); - reflection.FindProperty("weight")!.Set(13); - secondary.Title = "changed"; - secondary.Peer = primary; - Assert.Equal("changed", primary.Title); - Assert.Equal(13, value.Weight); - Assert.Same(value, secondary.Peer); - Assert.Same(value.AsReadOnly(), secondary.AsReadOnly()); - Assert.Equal(13, secondary.AsReadOnly().Weight); - - var catalog = ModelSnapshot.TypeCatalog; - var joined = catalog.Find(typeof(JoinedRecord))!; - var left = catalog.Find(typeof(PrimaryRecord))!; - var right = catalog.Find(typeof(SecondaryRecord))!; - Assert.Equal([left.Declaration, right.Declaration], joined.DirectSupertypes); - Assert.Equal(11, joined.FindProperty("weight")?.DeclaredDefault?.GetInt32()); - Assert.True(catalog.IsSubtypeOf(joined.Declaration, right.Declaration)); - Assert.Equal([typeof(JoinedRecord), typeof(SecondaryRecord)], - catalog.TypesAssignableTo(typeof(ISecondaryRecord)).Select(type => type.RuntimeType)); - Assert.Same(joined, catalog.TypeOf(secondary.AsReadOnly())); - } - - [Fact] - public void GetterOnlyPrimaryAndConcreteSecondaryContractsExposeTheSameCoordinates() - { - var point = CoordinateXY.NewBuilder().WithX(3).WithY(4).Build(); - WithXY primary = point; - ICoordinateX left = point; - ICoordinateY right = point; - Assert.Equal(3, left.X); - Assert.Equal(4, right.Y); - left.X = 8; - right.Y = 9; - Assert.Equal(8, primary.X); - Assert.Equal(9, primary.Y); - Assert.Same(point.AsReadOnly(), left.AsReadOnly()); - Assert.Same(point.AsReadOnly(), right.AsReadOnly()); - Assert.Equal(2, ModelSnapshot.Reflection.Reflect(point).Properties.Count); - Assert.Equal(3, ModelSnapshot.TypeCatalog.TypeOf(point)!.DirectSupertypes.Count); - } - [Fact] public void SecondaryTypedSnapshotRestoresTheConcreteJoinedRecord() { diff --git a/conformance/covariance-csharp/CovarianceTests.cs b/conformance/covariance-csharp/CovarianceTests.cs index f382cca6..971f76a9 100644 --- a/conformance/covariance-csharp/CovarianceTests.cs +++ b/conformance/covariance-csharp/CovarianceTests.cs @@ -81,28 +81,6 @@ public void NarrowMutableAndReadOnlyContractsShareOneReferenceSlot() Assert.Same(first.AsReadOnly(), ((IReadOnlyPickTrait)reaffirmed.AsReadOnly()).Current); } - [Fact] - public void ImmutableCovariantGetterReadsThePrimaryBaseStorage() - { - var item = new ColorTag(color: "green", title: "active"); - var narrow = new FrozenColorChoice(current: item); - FrozenChoice wide = narrow; - ColorTag? typed = narrow.Current; - Assert.Same(typed, wide.Current); - Assert.Same(item, typed); - Assert.Same(narrow, narrow.AsReadOnly()); - var field = Assert.Single(ModelSnapshot.Reflection.Reflect(wide).Properties, candidate => candidate.Name == "current"); - Assert.Equal(typeof(ColorTag), field.ValueType); - Assert.Equal("color_tag", field.WireName); - Assert.False(field.CanWrite); - Assert.Same(item, field.Get()); - var immutableTrait = new FrozenTraitChoice(current: item); - IReadOnlyFrozenPickTrait getterOnlyTrait = immutableTrait; - Assert.Same(item, immutableTrait.Current); - Assert.Same(item, getterOnlyTrait.Current); - Assert.Same(immutableTrait, immutableTrait.AsReadOnly()); - } - [Fact] public void MutableAndImmutableCovariantReferencesUseEffectiveWireContracts() { diff --git a/conformance/csharp/CollectionObservationTests.cs b/conformance/csharp/CollectionObservationTests.cs index 08f6b6c8..bdac905a 100644 --- a/conformance/csharp/CollectionObservationTests.cs +++ b/conformance/csharp/CollectionObservationTests.cs @@ -111,26 +111,6 @@ public void OrdinaryScalarFiltersUseSparsePositionsForHistoryAndCompatibleApply( AssertBits(receiverSurvivors, other.Readings); } - [Fact] - public void BoundedOrdinaryScalarFilterProducesASparseV1Removal() - { - const string checkpointId = "bulk-filter"; - var source = new CollectionProfile(); - source.Counts.AddRange([1, 2, 1]); - var baseline = ModelSnapshot.Read(ModelSnapshot.Write(source)); - var binding = new JournalBinding("scalar-list-filter", 1, _ => "profile"); - using var recorder = JournalRecorder.Start(source, ModelSnapshot.Registry, binding, checkpointId, 0); - Assert.True(source.Counts.RemoveAll(new[] { 1 })); - var journal = JournalJson.Read(JournalJson.Write(recorder.Finish())); - Assert.Equal(1, journal.WireVersion); - var operation = Assert.IsType(Assert.Single(Assert.Single(journal.Transactions).Operations)); - Assert.Equal(JournalListEditKind.Remove, operation.Kind); - Assert.Equal(new[] { 0, 2 }, operation.Indices); - var replay = JournalReplayer.Replay(baseline, binding, checkpointId, journal, ModelSnapshot.Registry); - Assert.Equal(new[] { 2 }, replay.Counts); - Assert.Equal(new[] { 1, 2, 1 }, baseline.Counts); - } - private static double?[] ScalarFilterReadings() => [+0.0, -0.0, null, 4.0, -0.0, BitConverter.Int64BitsToDouble(0x7ff8000000000042L), BitConverter.Int64BitsToDouble(unchecked((long)0xfff8000000000017UL)), 7.0]; @@ -139,112 +119,4 @@ private static void AssertBits(IEnumerable expected, IEnumerable value is double number ? BitConverter.DoubleToInt64Bits(number) : null; - - [Fact] - public void MapBulkEditKeepsExplicitNullAndCanBeUndoneAndReapplied() - { - var model = new CollectionProfile(); - model.Limits["existing"] = null; - var changes = model.VmfChanges; - var events = new List(); - using var watch = changes.AddLocalListener(events.Add); - changes.Start(); - model.Limits.PutAll([new("existing", 5L), new("added", null)]); - changes.Stop(); - - var edit = Assert.IsType(Assert.Single(events)); - Assert.Equal(ModelChangeKind.Map, edit.Kind); - Assert.Equal([new ModelCollectionEntry(null, Key: "existing")], edit.Removed); - Assert.Equal([new ModelCollectionEntry(5L, Key: "existing"), new ModelCollectionEntry(null, Key: "added")], edit.Added); - Assert.Same(edit, Assert.Single(changes.History)); - Assert.True(edit.Undo()); - Assert.True(model.Limits.TryGetValue("existing", out var restored)); - Assert.Null(restored); - Assert.False(model.Limits.ContainsKey("added")); - Assert.True(edit.Redo()); - Assert.Equal(5L, model.Limits["existing"]); - Assert.True(model.Limits.ContainsKey("added")); - Assert.Null(model.Limits["added"]); - - var copy = new CollectionProfile(); - copy.Limits["existing"] = null; - edit.Apply(copy); - Assert.Equal(5L, copy.Limits["existing"]); - Assert.True(copy.Limits.ContainsKey("added")); - Assert.Null(copy.Limits["added"]); - } - - [Fact] - public void ModelReferenceCollectionsPreserveSlotAndMembershipIdentityInRecordedEvents() - { - var head = new ArchiveNode(); - var child = new ArchiveNode(); - var hosted = new ArchiveRoot { Head = head }; - var changes = hosted.VmfChanges; - var events = new List(); - using var watch = changes.AddRecursiveListener(events.Add); - changes.Start(); - head.Trail.AddRange([child, null, child]); - head.Featured.Add(child); - Assert.False(head.Featured.Add(child)); - changes.Stop(); - - var sequence = Assert.IsType(events[0]); - Assert.Equal(ModelChangeKind.List, sequence.Kind); - Assert.True(sequence.IsModelReference); - Assert.Equal([new ModelCollectionEntry(child, 0), new ModelCollectionEntry(null, 1), - new ModelCollectionEntry(child, 2)], sequence.Added); - var membership = Assert.IsType(events[1]); - Assert.Equal(ModelChangeKind.ReferenceSet, membership.Kind); - Assert.Same(child, Assert.Single(membership.Added).Value); - Assert.Equal(0, Assert.Single(membership.Added).Index); - Assert.True(Assert.Single(changes.Transactions).Undo()); - Assert.Empty(head.Trail); - Assert.Empty(head.Featured); - Assert.True(Assert.Single(changes.Transactions).Redo()); - Assert.Same(child, head.Trail[0]); - Assert.Null(head.Trail[1]); - Assert.Same(child, head.Trail[2]); - Assert.Same(child, head.Featured[0]); - Assert.ThrowsAny(() => sequence.Apply(new ArchiveNode())); - - var selection = new ValueSelection(); - var first = new ValueLabel("equal"); - var second = new ValueLabel("equal"); - Assert.Equal(first, second); - var unique = new List(); - using var watchUnique = selection.VmfChanges.AddLocalListener(unique.Add); - selection.Selected.Add(first); - selection.Selected.Add(second); - Assert.False(selection.Selected.Add(second)); - var distinct = Assert.IsType(unique[1]); - Assert.Equal(ModelChangeKind.ReferenceSet, distinct.Kind); - Assert.Null(Assert.Single(distinct.Added).Index); - Assert.Same(second, Assert.Single(distinct.Added).Value); - } - - [Fact] - public void ReentrantSetEditRecordsBeforeNestedScalarAndObserversSeeAppliedMembers() - { - var model = new CollectionProfile(); - var changes = model.VmfChanges; - var notes = new List(); - using var membership = changes.AddLocalListener(change => - { - notes.Add("first " + change.PropertyName); - if (change.PropertyName == "levels") - { - Assert.True(model.Levels.Contains(2.0)); - model.Messages.Add("nested"); - } - }); - using var other = changes.AddLocalListener(change => notes.Add("second " + change.PropertyName)); - - changes.Start(); - model.Levels.Add(2.0); - changes.Stop(); - Assert.Equal(["first levels", "first messages", "second messages", "second levels"], notes); - Assert.Equal(["levels", "messages"], changes.History.Select(change => change.PropertyName)); - Assert.Equal(ModelChangeKind.Set, changes.History[0].Kind); - } } diff --git a/conformance/csharp/ConfiguredValidationTests.cs b/conformance/csharp/ConfiguredValidationTests.cs index 00214844..29bea9ec 100644 --- a/conformance/csharp/ConfiguredValidationTests.cs +++ b/conformance/csharp/ConfiguredValidationTests.cs @@ -114,53 +114,6 @@ public void ChecksDisabledScalarsAndRequiredInverseContainersAfterHydration() Assert.Null(fields["rack"]); } - [Theory] - [InlineData(null, 0)] - [InlineData("AB12", 0)] - [InlineData("NP90", 0)] - [InlineData("AI12", 1)] - [InlineData("BO09", 1)] - [InlineData("ab12", 1)] - [InlineData("AB12\n", 2)] - [InlineData("AB00", 1)] - [InlineData("IO00", 2)] - public void BindsEachNativePatternToItsOwnDeclarationAndReportsTheLogicalPath(string? input, int count) - { - var model = new NonzeroPatternedLabel { Label = input }; - var validator = NewValidator().Build(); - - foreach (var target in new object[] { model, model.AsReadOnly() }) - { - var report = validator.Validate(target); - Assert.Equal(count == 0, report.IsValid); - Assert.Equal(count, report.Issues.Count); - Assert.All(report.Issues, issue => - { - Assert.Equal("vmf.pattern", issue.Code); - Assert.Equal("/label", issue.Path); - Assert.Equal("tracking_label", issue.Property!.WireName); - Assert.Same(target, issue.Object); - }); - } - } - - [Fact] - public void ValidatesNativePatternsOnImportAndKeepsThePortableSchemaConstraints() - { - var validator = NewValidator().Build(); - var valid = ModelSnapshot.ReadPlain("""{"tracking_label":"NP90"}""", validator); - Assert.Equal("NP90", valid.Label); - var invalid = Assert.Throws(() => - ModelSnapshot.ReadPlain("""{"tracking_label":"AB00"}""", validator)); - Assert.Equal("vmf.pattern", Assert.Single(invalid.Report.Issues).Code); - - var schema = JsonNode.Parse(SnapshotSchema.Generate(ModelSnapshot.Registry, SnapshotSchemaProfile.Plain)); - var field = schema!["properties"]!["tracking_label"]!; - Assert.Equal(4, field["minLength"]!.GetValue()); - Assert.Equal(8, field["maxLength"]!.GetValue()); - Assert.Null(field["pattern"]); - } - [Fact] public void ReportsDeclaredConstraintsBeforeAssignableRulesAndPreservesTheView() { @@ -231,38 +184,6 @@ public void ReportsDeclaredConstraintsBeforeAssignableRulesAndPreservesTheView() Assert.Throws(() => missing.Validate(batch)); } - [Fact] - public void VisitsContainmentBeforeReferencesAndKeepsTheFirstPathForEachAlias() - { - var head = Node("head"); - var left = Node("left"); - var remote = Node("remote"); - var root = new ArchiveRoot { Head = head }; - head.Children.Add(left); - head.Inset = Node("right"); - root.Review.AddRange([null, left, remote, remote]); - head.Anchor = remote; - remote.Children.Add(Node("deep")); - remote.Trail.Add(Node("far")); - remote.Anchor = head; - - var containmentOnly = NewValidator().WithRule((_, context) => - context.Report(ValidationSeverity.Info, "visit", "Visited model")).Build(); - Assert.Equal(["", "/head", "/head/children/0", "/head/inset"], Paths(containmentOnly.Validate(root))); - - var recursive = NewValidator().WithFollowReferences().WithRule((_, context) => - context.Report(ValidationSeverity.Info, "visit", "Visited model")).Build(); - var report = recursive.Validate(root); - Assert.Equal(["", "/head", "/head/children/0", "/head/inset", "/review/2", "/review/2/children/0", - "/review/2/trail/0"], Paths(report)); - Assert.Same(remote, report.Issues[4].Object); - var view = root.AsReadOnly(); - var readOnly = recursive.Validate(view); - Assert.Equal(Paths(report), Paths(readOnly)); - Assert.Same(view.Review[2], readOnly.Issues[4].Object); - Assert.Equal([""], Paths(recursive.Validate(left))); - } - [Fact] public void VisitsImmutableAliasesOnceWithoutCollapsingEqualValues() { diff --git a/conformance/csharp/ContainmentCursorAncestryTests.cs b/conformance/csharp/ContainmentCursorAncestryTests.cs deleted file mode 100644 index 479ce184..00000000 --- a/conformance/csharp/ContainmentCursorAncestryTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -using Eu.Mihosoft.Vmftest.Setteridentity; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class ContainmentCursorAncestryTests -{ - [Theory] - [InlineData(false)] - [InlineData(true)] - public void RestoringASingularSlotInvalidatesItsSelection(bool clearFirst) - { - var selected = new NumberExpression { Value = 1 }; - var root = new BinaryExpression { Left = selected }; - using var cursor = ModelSnapshot.Reflection.OpenContainmentCursor(root); - Assert.True(cursor.MoveNext()); - Assert.True(cursor.MoveNext()); - Assert.Same(selected, cursor.Current); - if (clearFirst) cursor.ReplaceCurrent(null); - var expected = root.Left; - - var transientChild = new NumberExpression { Value = 2 }; - root.Left = transientChild; - root.Left = expected; - - Assert.False(cursor.CanReplace); - var attempted = new NumberExpression { Value = 3 }; - Assert.Throws(() => cursor.ReplaceCurrent(attempted)); - Assert.Same(expected, root.Left); - Assert.Null(transientChild.Parent); - Assert.Null(attempted.Parent); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void DetachingASingularOrListAncestorInvalidatesEdits(bool list) - { - var first = new NumberExpression { Value = 1 }; - var second = new NumberExpression { Value = 2 }; - var branch = new BinaryExpression(); - branch.Arguments.AddRange([first, second]); - var root = new BinaryExpression(); - if (list) root.Arguments.Add(branch); - else root.Left = branch; - - using var cursor = ModelSnapshot.Reflection.OpenContainmentCursor(root); - Assert.True(cursor.MoveNext()); - Assert.True(cursor.MoveNext()); - Assert.True(cursor.MoveNext()); - Assert.Same(first, cursor.Current); - Assert.True(cursor.TryPeek(out var pending)); - Assert.Same(second, pending); - - if (list) root.Arguments.Clear(); - else root.Left = null; - var attempted = new NumberExpression { Value = 3 }; - Assert.False(cursor.CanReplace); - Assert.False(cursor.CanInsertAfter); - Assert.Throws(() => cursor.ReplaceCurrent(attempted)); - Assert.Throws(() => cursor.InsertAfterCurrent(attempted)); - Assert.Throws(() => cursor.TryPeek(out _)); - Assert.Same(first, branch.Arguments[0]); - Assert.Same(second, branch.Arguments[1]); - Assert.Null(attempted.Parent); - } -} diff --git a/conformance/csharp/ContainmentCursorTests.cs b/conformance/csharp/ContainmentCursorTests.cs index 5b711cfb..0a69bb01 100644 --- a/conformance/csharp/ContainmentCursorTests.cs +++ b/conformance/csharp/ContainmentCursorTests.cs @@ -93,29 +93,6 @@ public void PreservesTheGraphOnInvalidChildrenAndUsesManagedReparenting() Move(cursor, last); } - [Fact] - public void DetectsAChangedDuplicateSlotEvenWhenTheSameIdentityRemainsAtTheIndex() - { - var catalog = new Catalog(); - var first = Item("first"); - var tail = Item("tail"); - catalog.Items.AddRange([first, Item("placeholder"), tail]); - catalog.Items[1] = first; - using var cursor = ModelSnapshot.Reflection.OpenContainmentCursor(catalog); - Move(cursor, catalog); - Move(cursor, first); - Assert.True(cursor.TryPeek(out var alias)); - Assert.Same(first, alias); - - catalog.Items.RemoveAt(0); - Assert.Same(first, catalog.Items[0]); - Assert.False(cursor.CanReplace); - Assert.Throws(() => cursor.ReplaceCurrent(Item("untouched"))); - Assert.Throws(() => cursor.TryPeek(out _)); - Assert.Throws(() => cursor.MoveNext()); - Assert.Equal(new[] { first, tail }, catalog.Items); - } - [Fact] public void DetectsAnExternallyReplacedPendingEdgeAndSingularAba() { @@ -208,42 +185,6 @@ public void SingularAndOrderedEdgesUseTheirOwnManagedMutationRules() Move(ordered, last); } - [Fact] - public void UnorderedEdgesTraverseWithoutPositionalEdits() - { - var book = new Ordinary.Volume { Name = "book" }; - var shelf = new Ordinary.Shelf(); - shelf.Volumes.Add(book); - using var cursor = Ordinary.ModelSnapshot.Reflection.OpenContainmentCursor(shelf); - Move(cursor, shelf); - Move(cursor, book); - Assert.False(cursor.CanReplace); - Assert.False(cursor.CanInsertAfter); - Assert.Throws(() => cursor.ReplaceCurrent(new Ordinary.Volume())); - Assert.Throws(() => cursor.InsertAfterCurrent(new Ordinary.Volume())); - Assert.Same(book, Assert.Single(shelf.Volumes)); - shelf.Volumes.Remove(book); - Assert.Throws(() => cursor.MoveNext()); - } - - [Fact] - public void ChangingAnAncestorInvalidatesTheSelectedDescendant() - { - var leaf = new Values.ArchiveNode(); - var branch = new Values.ArchiveNode { Inset = leaf }; - var root = new Values.ArchiveNode { Inset = branch }; - using var cursor = Values.ModelSnapshot.Reflection.OpenContainmentCursor(root); - Move(cursor, root); - Move(cursor, branch); - Move(cursor, leaf); - root.Inset = null; - root.Inset = branch; - - Assert.False(cursor.CanReplace); - Assert.Throws(() => cursor.ReplaceCurrent(null)); - Assert.Same(leaf, branch.Inset); - } - [Fact] public void AnObserverChangingTheActiveCollectionMakesTheCursorStale() { diff --git a/conformance/csharp/ContainmentObservationTests.cs b/conformance/csharp/ContainmentObservationTests.cs index 487f66e0..36bb2860 100644 --- a/conformance/csharp/ContainmentObservationTests.cs +++ b/conformance/csharp/ContainmentObservationTests.cs @@ -111,87 +111,6 @@ public void OrderedTransferJournalsReplayTheSourceRemovalBeforeAnObserverReplace Assert.Equal("moving", Assert.Single(replayed.Children[1].Children).Name); } - [Fact] - public void ListReparentingExposesTheSameStagesAndKeepsUndoOrder() - { - var graph = new Fixture(); - var source = graph.Source; - var destination = graph.Destination; - var child = graph.Child; - var other = new ArchiveNode(); - source.Children.Add(child); - var changes = graph.Root.VmfChanges; - var order = new List(); - using var recursive = changes.AddRecursiveListener(change => - { - if (ReferenceEquals(change.Source, source)) - { - order.Add("source removed"); - Assert.Empty(source.Children); - Assert.Same(source, child.Parent); - Assert.Same(child, Assert.Single(destination.Children)); - var removal = Assert.IsType(change); - Assert.Equal(ModelChangeKind.ReferenceSet, removal.Kind); - Assert.True(removal.IsContainment); - Assert.Equal([new ModelCollectionEntry(child, 0)], removal.Removed); - Assert.Empty(removal.Added); - Assert.ThrowsAny(() => other.Children.Add(child)); - Assert.ThrowsAny(() => destination.Children.Remove(child)); - Assert.ThrowsAny(() => child.Parent = null); - Assert.Empty(other.Children); - child.Name = "during removal"; - } - else if (ReferenceEquals(change.Source, destination)) - { - order.Add("destination added"); - Assert.Same(destination, child.Parent); - Assert.Same(child, Assert.Single(destination.Children)); - var addition = Assert.IsType(change); - Assert.Empty(addition.Removed); - Assert.Equal([new ModelCollectionEntry(child, 0)], addition.Added); - } - else - { - order.Add("recursive " + change.PropertyName + " " + change.NewValue); - } - }); - using var inverse = child.VmfChanges.AddPropertyListener("parent", change => - { - Assert.True(change.IsInverse); - if (change.NewValue is null) - { - Assert.Same(source, change.OldValue); - Assert.Null(child.Parent); - order.Add("child detached"); - } - else - { - Assert.Null(change.OldValue); - Assert.Same(destination, change.NewValue); - Assert.Same(destination, child.Parent); - order.Add("child attached"); - } - }); - - changes.Start(); - destination.Children.Add(child); - child.Name = "after move"; - recursive.Dispose(); - inverse.Dispose(); - changes.Stop(); - - Assert.Equal(["source removed", "recursive name during removal", "child detached", "child attached", - "destination added", "recursive name after move"], order); - // The triggering edit is recorded before the edits its listeners made (portable contract H4). - Assert.Equal(["source:children", "name:during removal", "destination:children", "name:after move"], - changes.History.Select(Describe)); - Assert.True(Assert.Single(changes.Transactions).Undo()); - Assert.Same(child, Assert.Single(source.Children)); - Assert.Same(source, child.Parent); - Assert.Empty(destination.Children); - Assert.Equal("child", child.Name); - } - [Fact] public void SingularReplacementClearsTheFormerChildBeforeMovingTheIncomingChild() { @@ -282,101 +201,6 @@ public void SingularReplacementClearsTheFormerChildBeforeMovingTheIncomingChild( Assert.Same(destination, former.InsetOf); } - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ObserverFailuresDoNotInterruptReparentingOrHideLaterEvents(bool singular) - { - var graph = new Fixture(); - var source = graph.Source; - var destination = graph.Destination; - var child = graph.Child; - if (singular) - { - source.Inset = child; - } - else - { - source.Children.Add(child); - } - - string forward = singular ? "inset" : "children"; - string reverse = singular ? "insetOf" : "parent"; - var changes = graph.Root.VmfChanges; - var order = new List(); - var initial = new InvalidOperationException("first source callback"); - var following = new NotSupportedException("second source callback"); - var detach = new ArgumentException("inverse detach callback"); - var last = new InvalidOperationException("destination callback"); - using var first = changes.AddRecursiveListener(change => - { - if (ReferenceEquals(change.Source, source)) - { - order.Add("first source"); - throw initial; - } - if (ReferenceEquals(change.Source, destination)) - { - order.Add("first destination"); - throw last; - } - order.Add("recursive " + change.PropertyName); - }); - using var second = changes.AddRecursiveListener(change => - { - if (ReferenceEquals(change.Source, source)) - { - order.Add("second source"); - throw following; - } - if (ReferenceEquals(change.Source, destination)) - { - order.Add("second destination"); - } - }); - using var watchInverse = child.VmfChanges.AddPropertyListener(reverse, change => - { - if (change.NewValue is null) - { - order.Add("child detached"); - throw detach; - } - order.Add("child attached"); - }); - - changes.Start(); - var error = Assert.Throws(() => - { - if (singular) - { - destination.Inset = child; - } - else - { - destination.Children.Add(child); - } - }); - Assert.Same(initial, error); - Assert.Equal([following, detach, last], ModelChanges.GetSuppressedObserverExceptions(error)); - if (singular) - { - Assert.Null(source.Inset); - Assert.Same(child, destination.Inset); - Assert.Same(destination, child.InsetOf); - } - else - { - Assert.Empty(source.Children); - Assert.Same(child, Assert.Single(destination.Children)); - Assert.Same(destination, child.Parent); - } - child.Name = "verified"; - changes.Stop(); - Assert.Equal(["first source", "second source", "child detached", "child attached", "first destination", - "second destination", "recursive name"], order); - Assert.Equal(["source:" + forward, "destination:" + forward, "name:verified"], changes.History.Select(Describe)); - } - [Fact] public void AChildReattachedByItsDetachListenerRetainsBothScopesUntilRemovalSettles() { diff --git a/conformance/csharp/ContentEqualityTests.cs b/conformance/csharp/ContentEqualityTests.cs index b1e80d7d..ac434207 100644 --- a/conformance/csharp/ContentEqualityTests.cs +++ b/conformance/csharp/ContentEqualityTests.cs @@ -41,83 +41,6 @@ public void ClrEqualityPoliciesUseContentOnlyForOptedInTypes() Assert.False(first.ContentEquals(second)); } - [Fact] - public void ContainmentPolicyComparesOwningEdgesAndIgnoresExternalReferencesAndInverses() - { - var first = new EqualityContainer - { - Name = "owner", Child = new EqualityNode { Name = "single" }, External = new EqualityIdentity { Name = "left" }, - }; - var second = new EqualityContainer - { - Name = "owner", Child = new EqualityNode { Name = "single" }, External = new EqualityIdentity { Name = "right" }, - }; - first.Children.Add(new EqualityNode { Name = "a" }); - first.Children.Add(new EqualityNode { Name = "b" }); - second.Children.Add(new EqualityNode { Name = "a" }); - second.Children.Add(new EqualityNode { Name = "b" }); - Assert.True(first.Equals(second)); - Assert.True(first.ContentEquals(second)); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); - - second.Child!.Name = "changed single"; - Assert.False(first.Equals(second)); - second.Child.Name = "single"; - second.Children.Move(0, 1); - Assert.False(first.Equals(second)); - - second.Name = "different owner"; - Assert.Same(first, first.Children[0].Container); - Assert.Same(second, second.Children[1].Container); - AssertEquivalent(first.Children[0], second.Children[1]); - } - - [Fact] - public void EffectiveDerivedFieldsAndReadOnlyViewsUseTheConcreteContent() - { - EqualityNode first = new EqualityDerived { Name = "base", Extra = "trait", Note = "ignored" }; - var second = new EqualityDerived { Name = "base", Extra = "trait" }; - AssertEquivalent(first, second); - Assert.False(first.Equals(new EqualityNode { Name = "base" })); - - var firstView = first.AsReadOnly(); - var secondView = second.AsReadOnly(); - Assert.True(EqualityModels.Reflection.ContentEquals(firstView, secondView)); - Assert.True(first.Equals(secondView)); - Assert.True(secondView.Equals(first)); - Assert.True(firstView.Equals(secondView)); - Assert.Equal(first.GetHashCode(), secondView.GetHashCode()); - Assert.Equal(first.ContentHashCode(), EqualityModels.Reflection.ContentHashCode(secondView)); - - second.Extra = "changed trait"; - Assert.False(firstView.Equals(secondView)); - second.Extra = "trait"; - second.Name = "changed base"; - Assert.False(EqualityModels.Reflection.ContentEquals(firstView, secondView)); - } - - [Fact] - public void ReferenceCollectionContentDistinguishesOrderAndEquivalentMultiplicityFromIdentity() - { - var shared = new EqualityNode { Name = "entry" }; - var left = new EqualityNode { Name = "outer" }; - var right = new EqualityNode { Name = "outer" }; - left.Links.AddRange([shared, null, shared]); - right.Links.AddRange([new EqualityNode { Name = "entry" }, null, new EqualityNode { Name = "entry" }]); - left.Members.AddRange([shared, new EqualityNode { Name = "second" }, new EqualityNode { Name = "entry" }]); - right.Members.AddRange([new EqualityNode { Name = "second" }, new EqualityNode { Name = "entry" }, new EqualityNode { Name = "entry" }]); - Assert.Equal(3, left.Members.Count); - Assert.False(left.Members.Contains(new EqualityNode { Name = "entry" })); - AssertEquivalent(left, right); - - right.Links.Move(1, 0); - Assert.False(left.Equals(right)); - right.Links.Move(0, 1); - right.Members.Clear(); - right.Members.AddRange([new EqualityNode { Name = "second" }, new EqualityNode { Name = "second" }, new EqualityNode { Name = "entry" }]); - Assert.False(left.Equals(right)); - } - [Fact] public void CyclicEqualityAndHashAreStableWhenEquivalentStatesHaveDifferentIdentityCounts() { @@ -138,31 +61,6 @@ public void CyclicEqualityAndHashAreStableWhenEquivalentStatesHaveDifferentIdent Assert.False(head.ContentEquals(self)); } - [Fact] - public void PortableScalarContentsPreserveSignedZeroNaNAndMapKeyPresence() - { - var first = new EqualityNode { Reading = +0.0 }; - var second = new EqualityNode { Reading = NegativeZero }; - Assert.False(first.Equals(second)); - first.Reading = double.NaN; - second.Reading = BitConverter.Int64BitsToDouble(0x7ff8000000000001L); - AssertEquivalent(first, second); - - var left = new CollectionProfile(); - var right = new CollectionProfile(); - left.Markers.Put(+0.0, null); - left.Markers.Put(NegativeZero, '-'); - right.Markers.Put(NegativeZero, '-'); - right.Markers.Put(+0.0, null); - left.Levels.AddRange([+0.0, NegativeZero, double.NaN]); - right.Levels.AddRange([double.NaN, NegativeZero, +0.0]); - var reflection = ValueModels.Reflection; - Assert.True(reflection.ContentEquals(left, right)); - Assert.Equal(reflection.ContentHashCode(left), reflection.ContentHashCode(right.AsReadOnly())); - right.Markers.Remove(+0.0); - Assert.False(reflection.ContentEquals(left, right)); - } - [Fact] public void DeepAcyclicContentCanBeComparedWithoutGrowingTheCallStack() { diff --git a/conformance/csharp/DeepCopyTests.cs b/conformance/csharp/DeepCopyTests.cs deleted file mode 100644 index 13c0d936..00000000 --- a/conformance/csharp/DeepCopyTests.cs +++ /dev/null @@ -1,132 +0,0 @@ -using Eu.Mihosoft.Vmf.Conformance.Values; -using Vmf.Runtime; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public class DeepCopyTests -{ - private static ModelReflectionRegistry Reflection => ModelSnapshot.Reflection; - - [Fact] - public void DeepCopyRebuildsOwnershipAndCopiesDetachedAliasesAndCycles() - { - var root = Named("root"); - var child = Named("child"); - var inset = Named("inset"); - var detached = Named("detached"); - root.Children.Add(child); - root.Inset = inset; - root.Anchor = detached; - detached.Anchor = root; - root.Featured.AddRange([child, inset]); - root.Peers.Add(detached); - root.Trail.AddRange([child, null, detached, child, root]); - - var copy = Reflection.DeepCopy(root); - var newChild = Assert.Single(copy.Children); - var newInset = Assert.IsType(copy.Inset); - var newDetached = Assert.IsType(copy.Anchor); - Assert.NotSame(root, copy); - Assert.NotSame(child, newChild); - Assert.NotSame(inset, newInset); - Assert.NotSame(detached, newDetached); - Assert.Same(copy, newChild.Parent); - Assert.Same(copy, newInset.InsetOf); - Assert.Null(newDetached.Parent); - Assert.Same(copy, newDetached.Anchor); - Assert.Same(newChild, copy.Featured[0]); - Assert.Same(newInset, copy.Featured[1]); - Assert.Same(newDetached, Assert.Single(copy.Peers)); - Assert.Equal(new ArchiveNode?[] { newChild, null, newDetached, newChild, copy }, copy.Trail); - newDetached.Name = "local"; - Assert.Equal("detached", detached.Name); - Assert.Same(root, child.Parent); - Assert.Null(Reflection.DeepCopy(child).Parent); - } - - [Fact] - public void AReadOnlyInputProducesAReadOnlyIndependentCopy() - { - var root = Named("root"); - var child = Named("child"); - root.Children.Add(child); - root.Anchor = child; - child.Anchor = root; - var view = root.AsReadOnly(); - IReadOnlyArchiveNode copy = Reflection.DeepCopy(view); - Assert.NotSame(view, copy); - Assert.IsNotType(copy); - Assert.Same(copy.Children[0], copy.Anchor); - Assert.Same(copy, copy.Anchor!.Anchor); - Assert.Same(copy, copy.Children[0].Parent); - Assert.Equal("root", copy.Name); - root.Name = "edited"; - child.Name = "child edited"; - Assert.Equal("root", copy.Name); - Assert.Equal("child", copy.Children[0].Name); - } - - [Fact] - public void ReferenceAndScalarKeysAreInstalledBeforeContainment() - { - var inventory = new KeyedInventory(); - var part = new KeyedPart { Name = "bolt" }; - var assignment = new KeyedAssignment { Part = part, Count = 5 }; - var product = new KeyedItem { Sku = "sku-a", Quantity = 2 }; - inventory.Parts.Add(part); - inventory.Assignments.Add(assignment); - inventory.Products.Add(product); - - var copy = Reflection.DeepCopy(inventory); - var newPart = Assert.Single(copy.Parts); - var newAssignment = Assert.Single(copy.Assignments); - var newProduct = Assert.IsType(copy.FindProductsBySku("sku-a")); - Assert.NotSame(part, newPart); - Assert.NotSame(assignment, newAssignment); - Assert.NotSame(product, newProduct); - Assert.Same(newPart, newAssignment.Part); - Assert.Same(newAssignment, copy.FindAssignmentsByPart(newPart)); - Assert.Null(copy.FindAssignmentsByPart(part)); - Assert.Equal(2, newProduct.Quantity); - } - - [Fact] - public void ScalarCollectionsAreIndependentAndImmutableAliasesAreShared() - { - var profile = new CollectionProfile(); - profile.Messages.AddRange(new string?[] { "ready", null }); - profile.Levels.AddRange([0.0, -0.0, double.NaN]); - profile.Limits.Add("pending", null); - profile.Markers.Add(0.0, '+'); - profile.Markers.Add(-0.0, '-'); - var copy = Reflection.DeepCopy(profile); - Assert.Equal(new string?[] { "ready", null }, copy.Messages); - Assert.Equal(3, copy.Levels.Count); - Assert.All(new[] { 0.0, -0.0, double.NaN }, value => Assert.True(copy.Levels.Contains(value))); - Assert.True(copy.Limits.ContainsKey("pending")); - Assert.Null(copy.Limits["pending"]); - Assert.Equal('+', copy.Markers[0.0]); - Assert.Equal('-', copy.Markers[-0.0]); - copy.Messages.Clear(); - copy.Limits.Clear(); - Assert.Equal(2, profile.Messages.Count); - Assert.True(profile.Limits.ContainsKey("pending")); - - var defaults = Reflection.DeepCopy(new DefaultSettings { Name = null, Limit = null }); - Assert.Null(defaults.Name); - Assert.Null(defaults.Limit); - Assert.Equal(long.MinValue, BitConverter.DoubleToInt64Bits(defaults.Baseline)); - - var value = new ValueLabel("shared"); - var selection = new ValueSelection { Current = value }; - selection.Selected.Add(value); - var copiedSelection = Reflection.DeepCopy(selection); - Assert.NotSame(selection, copiedSelection); - Assert.Same(value, copiedSelection.Current); - Assert.Same(value, Assert.Single(copiedSelection.Selected)); - Assert.Same(value, Reflection.DeepCopy(value)); - } - - private static ArchiveNode Named(string name) => ArchiveNode.NewBuilder().WithName(name).Build(); -} diff --git a/conformance/csharp/DefaultTests.cs b/conformance/csharp/DefaultTests.cs index 148218a3..8b345a01 100644 --- a/conformance/csharp/DefaultTests.cs +++ b/conformance/csharp/DefaultTests.cs @@ -8,45 +8,6 @@ namespace Vmf.CSharp.Conformance; public class DefaultTests { - [Fact] - public void ConstructorsBuildersAndMissingSnapshotFieldsUseTheDeclaredDefaults() - { - VerifyDefaults(new DefaultSettings()); - VerifyDefaults(DefaultSettings.NewBuilder().Build()); - VerifyDefaults(Snapshot.ReadPlain("{}")); - VerifyDefaults(Snapshot.Read("{}")); - Assert.Equal("idle\nready", DefaultBase.NewBuilder().Build().Name); - } - - [Fact] - public void BuildersCopyCollectionInputsAndKeepPreviousStateAfterRejectedEdits() - { - var stages = new List { "check", "publish" }; - var builder = DefaultSettings.NewBuilder().WithName(null).WithLimit(null).WithStages(stages); - stages[1] = "external edit"; - Assert.ThrowsAny(() => builder.WithStages(["check", "check"])); - Assert.ThrowsAny(() => builder.WithStages(["a", "b", "c", "d"])); - - var first = builder.Build(); - first.Stages.Move(1, 0); - var second = builder.Build(); - Assert.NotSame(first, second); - Assert.Equal(["publish", "check"], first.Stages); - Assert.Equal(["check", "publish"], second.Stages); - Assert.Null(second.Name); - Assert.Null(second.Limit); - Assert.Equal("new", DefaultEntry.NewBuilder().Build().Label); - } - - [Fact] - public void BuilderPreservesTheConcreteGenericRelationshipTypes() - { - var item = Thermometer.NewBuilder().WithSku("T-1").WithUnit("C").Build(); - var catalog = Catalog.NewBuilder().WithProducts([item]).WithFeatured(item).Build(); - Assert.Same(item, Assert.Single(catalog.Products)); - Assert.Same(item, catalog.Featured); - Assert.Equal("T-1", Assert.IsType(catalog.Featured).Sku); - } [Fact] public void ExplicitNullOverridesDefaultInBothJsonProfilesAndLanguages() diff --git a/conformance/csharp/DynamicDefaultsTests.cs b/conformance/csharp/DynamicDefaultsTests.cs index 7375475c..73030762 100644 --- a/conformance/csharp/DynamicDefaultsTests.cs +++ b/conformance/csharp/DynamicDefaultsTests.cs @@ -6,87 +6,6 @@ namespace Vmf.CSharp.Conformance; public class DynamicDefaultsTests { - [Fact] - public void HeldViewReadsTheEffectiveScalarDefaultAndSetState() - { - Check("name", "idle\nready", "custom", "replacement", null, view => view.Name); - Check("baseline", -0.0d, 1.5d, 2.5d, -1.0d, view => view.Baseline); - - static void Check(string name, object declared, object configured, object replacement, object? explicitValue, - Func get) - { - var model = new DefaultSettings(); - var source = Field(model, name); - var view = model.AsReadOnly(); - var projected = Field(view, name); - CheckState(declared, declared, false); - - source.SetDefault(configured); - CheckState(configured, configured, false); - source.Set(explicitValue); - CheckState(configured, explicitValue, true); - source.SetDefault(replacement); - CheckState(replacement, explicitValue, true); - - Assert.Throws(() => projected.SetDefault(configured)); - Assert.Throws(projected.Reset); - CheckState(replacement, explicitValue, true); - source.Reset(); - CheckState(replacement, replacement, false); - - Assert.Equal(declared, Field(new DefaultSettings(), name).DefaultValue); - source.SetDefault(null); - CheckState(declared, declared, false); - - void CheckState(object expectedDefault, object? expectedValue, bool set) - { - Assert.Equal(expectedDefault, source.DefaultValue); - Assert.Equal(expectedDefault, projected.DefaultValue); - Assert.Equal(expectedValue, source.Get()); - Assert.Equal(expectedValue, projected.Get()); - Assert.Equal(expectedValue, get(view)); - Assert.Equal(set, source.IsSet); - Assert.Equal(set, projected.IsSet); - } - } - } - - [Fact] - public void UpdatesAnUnsetFieldThroughTheSetterAndKeepsASetField() - { - var model = new DefaultSettings(); - var name = Field(model, "name"); - var view = Field(model.AsReadOnly(), "name"); - var events = new List<(object? Before, object? After, object? Default)>(); - using var listener = model.VmfChanges.AddPropertyListener("name", change => - { - Assert.Equal(ModelChangeKind.Property, change.Kind); - events.Add((change.OldValue, change.NewValue, name.DefaultValue)); - }); - model.VmfChanges.Start(); - - name.SetDefault("custom"); - Assert.False(name.IsSet); - Assert.Equal("custom", view.DefaultValue); - Assert.False(view.IsSet); - Assert.Equal("custom", model.Name); - Assert.Equal(("idle\nready", "custom", "custom"), Assert.Single(events)); - - model.Name = "explicit"; - name.SetDefault("explicit"); - Assert.False(name.IsSet); - Assert.Equal(2, events.Count); - name.SetDefault(null); - Assert.Equal("idle\nready", model.Name); - Assert.Equal("idle\nready", name.DefaultValue); - Assert.False(name.IsSet); - Assert.Equal(3, model.VmfChanges.History.Count); - model.VmfChanges.Stop(); - Assert.Equal(3, Assert.Single(model.VmfChanges.Transactions).Changes.Count); - Assert.Equal("idle\nready", Field(new DefaultSettings(), "name").DefaultValue); - Assert.False(view.CanSetDefault); - Assert.Throws(() => view.SetDefault("hidden")); - } [Fact] public void RejectsInvalidDefaultsBeforeChangingCurrentValuesOrMetadata() @@ -261,39 +180,6 @@ public void CopiesPreserveManagedScalarCollectionAndMapOverrides() Assert.Equal(2, Assert.Single(DefaultMembers(Field(model, "counts")))); } - [Fact] - public void CopiesKeepTheLiveValuesButDropLegacyDefaultOverrides() - { - var profile = new CollectionProfile(); - Field(profile, "messages").SetDefault(new string?[] { "same", null, "same" }); - var node = new ArchiveNode(); - var target = new ArchiveNode { Name = "target" }; - Field(node, "name").SetDefault("runtime-name"); - Field(node, "anchor").SetDefault(target); - Field(node, "trail").SetDefault(new ArchiveNode?[] { target, null, target }); - - foreach (var copy in new[] { ModelSnapshot.Reflection.DeepCopy(profile), ModelSnapshot.Reflection.ShallowCopy(profile) }) - { - Assert.Equal(new string?[] { "same", null, "same" }, copy.Messages.ToArray()); - Assert.Empty(DefaultMembers(Field(copy, "messages"))); - Assert.True(Field(copy, "messages").IsSet); - } - foreach (var copy in new[] { ModelSnapshot.Reflection.DeepCopy(node), ModelSnapshot.Reflection.ShallowCopy(node) }) - { - Assert.Equal("runtime-name", copy.Name); - Assert.Null(Field(copy, "name").DefaultValue); - Assert.True(Field(copy, "name").IsSet); - Assert.NotNull(copy.Anchor); - Assert.Null(Field(copy, "anchor").DefaultValue); - Assert.True(Field(copy, "anchor").IsSet); - Assert.Same(copy.Anchor, copy.Trail[0]); - Assert.Null(copy.Trail[1]); - Assert.Same(copy.Trail[0], copy.Trail[2]); - Assert.Empty(DefaultMembers(Field(copy, "trail"))); - Assert.True(Field(copy, "trail").IsSet); - } - } - [Fact] public void IdentitySetDefaultsUseTheSameDeepCopyIdentitiesAsLiveEdges() { @@ -340,31 +226,6 @@ public void IdentitySetDefaultsUseTheSameDeepCopyIdentitiesAsLiveEdges() Assert.Same(Assert.Single(view.Featured), DefaultMembers(Field(view, "featured"))[0]); } - [Fact] - public void SnapshotsPersistLiveDataAndRecreateDeclarationDefaults() - { - var profile = new CollectionProfile(); - Field(profile, "counts").SetDefault(new[] { 2 }); - Field(profile, "limits").SetDefault(new Dictionary { ["pending"] = null }); - var restored = ModelSnapshot.ReadPlain(ModelSnapshot.WritePlain(profile)); - Assert.Equal(2, Assert.Single(restored.Counts)); - Assert.Empty(DefaultMembers(Field(restored, "counts"))); - Assert.Empty(Assert.IsAssignableFrom>(Field(restored, "limits").DefaultValue)); - Assert.True(restored.Limits.ContainsKey("pending")); - Assert.Null(restored.Limits["pending"]); - Assert.True(Field(restored, "counts").IsSet); - - var node = new ArchiveNode { Name = "root" }; - var target = new ArchiveNode { Name = "contained" }; - node.Children.Add(target); - node.Peers.Add(target); - Field(node, "peers").SetDefault(new[] { target, new ArchiveNode { Name = "default-only" } }); - var loaded = ModelSnapshot.Read(ModelSnapshot.Write(node)); - Assert.Same(Assert.Single(loaded.Children), Assert.Single(loaded.Peers)); - Assert.Empty(DefaultMembers(Field(loaded, "peers"))); - Assert.True(Field(loaded, "peers").IsSet); - } - private static IReadOnlyList DefaultMembers(ModelProperty property) => Assert.IsAssignableFrom>(property.DefaultValue); diff --git a/conformance/csharp/ExternalSnapshotCodecTests.cs b/conformance/csharp/ExternalSnapshotCodecTests.cs index d6cb04ef..775df342 100644 --- a/conformance/csharp/ExternalSnapshotCodecTests.cs +++ b/conformance/csharp/ExternalSnapshotCodecTests.cs @@ -112,7 +112,6 @@ string Markup(int depth) => string.Concat(Enumerable.Repeat("", depth)) + Assert.Contains("maximum element depth", error.Message); } - [Fact] public void UsesConfiguredWireSchemaAndPreservesBindingsAcrossCanonicalComposition() { @@ -182,54 +181,6 @@ public void TreatsWholeExternalTreesAsDetachedValues() Assert.Contains("/value", Assert.Throws(() => SnapshotJson.WritePlain(invalid, registry)).Message); } - [Fact] - public void UsesSeparateCanonicalTextCodecsForPortableJournals() - { - var registry = BuiltIns.WithExternalValueCodecs(Codecs(StructuredXml)); - var journals = JournalValueCodecs.Standard - .WithImmutable("probe.uri/v1", static uri => uri.OriginalString, - static text => new Uri(text, UriKind.RelativeOrAbsolute)) - .WithImmutable("probe.distance/v1", - static value => value.Millimetres.ToString(CultureInfo.InvariantCulture) + "|" + value.Note + "|" - + (value.Estimated ? "true" : "false"), - static text => - { - var parts = text.Split('|'); - return new Distance(long.Parse(parts[0], CultureInfo.InvariantCulture), parts[1], bool.Parse(parts[2])); - }); - var binding = new JournalBinding("external-probe", 1, static model => ((Endpoint)model).Id!, null, journals); - const string changedLocation = "https://Example.invalid:443/changed/%2f/../b?x=%e2%82%ac#second"; - var work = Fixture(); - var journal = JournalRecorder.RecordFrame(work, registry, binding, "start", 0, endpoint => - { - endpoint.Location = new Uri(changedLocation); - endpoint.Links.Add(new Uri("urn:sample:item")); - endpoint.Measurement = new Distance(7L, "note", true); - }); - Assert.Equal(1, journal.WireVersion); - var operations = Assert.Single(journal.Transactions).Operations; - var location = Assert.IsType(operations[0]); - Assert.Equal("probe.uri/v1", location.After.CodecId); - Assert.Equal(changedLocation, location.After.Text); - var distance = Assert.IsType(operations[2]); - Assert.Equal("probe.distance/v1", distance.Before.CodecId); - Assert.Equal("9007199254740993|true|false", distance.Before.Text); - var checkpoint = Fixture(); - foreach (var replay in new[] - { - JournalJson.Read(JournalJson.Write(journal)), - JournalYaml.Read(JournalYaml.Write(journal)), - JournalXml.Read(JournalXml.Write(journal)), - }) - { - var result = JournalReplayer.Replay(checkpoint, binding, "start", replay, registry); - Assert.Equal(changedLocation, result.Location?.OriginalString); - Assert.Equal("urn:sample:item", result.Links[3]?.OriginalString); - Assert.Equal(new Distance(7L, "note", true), result.Measurement); - } - Verify(checkpoint); - } - private static ExternalSnapshotCodecs Codecs(ExternalSnapshotXmlCodec? structuredXml) => ExternalSnapshotCodecs.Empty .WithImmutable(UriType, static value => JsonSerializer.SerializeToElement(value.OriginalString), diff --git a/conformance/csharp/FeatureBundleTests.cs b/conformance/csharp/FeatureBundleTests.cs index c4e28a57..cfc34274 100644 --- a/conformance/csharp/FeatureBundleTests.cs +++ b/conformance/csharp/FeatureBundleTests.cs @@ -230,44 +230,6 @@ public void ReadChecksTheEnvelopeTypesDuplicatesAndRegistryBeforeReturningABundl "", VmfDocumentFormat.Xml)); } - [Fact] - public void MutableReferencesCannotResolveAgainstASeparateBundleEntry() - { - var codec = new FeatureBundleCodec(Registry); - var owner = new ArchiveRoot { Head = new ArchiveNode { Name = "owner" } }; - owner.Review.Add(owner.Head); - var archive = new ArchiveRoot { Head = new ArchiveNode { Name = "feature" } }; - var features = new FeatureAttachments(Registry); - features.Attach(owner, archive); - var wire = JsonNode.Parse(codec.Write(owner, features))!; - string ownerId = wire["owner"]!["value"]!["head"]!["@vmf-id"]!.GetValue(); - wire["features"]![0]!["value"]!["head"]!["anchor"] = ownerId; - Assert.Throws(() => codec.Read(wire.ToJsonString())); - archive.Head!.Anchor = owner.Head; - Assert.Throws(() => codec.Write(owner, features)); - } - - [Fact] - public void CanonicalCompositionKeepsCollidingPackageAliasesIndependent() - { - var rootType = new SnapshotType("App.Owner", typeof(AppOwner), () => new AppOwner(), [], writeType: true); - var featureType = new SnapshotType("Plugin.Feature", typeof(PluginFeature), () => new PluginFeature(), [], writeType: true); - var rootRegistry = new SnapshotRegistry([rootType], new Dictionary { ["shared"] = "App.Owner" }); - var featureRegistry = new SnapshotRegistry([featureType], new Dictionary { ["shared"] = "Plugin.Feature" }); - var registry = SnapshotRegistry.CombineCanonical(rootRegistry, featureRegistry, rootRegistry); - var owner = new AppOwner(); - var feature = new PluginFeature(); - var attachments = new FeatureAttachments(registry); - attachments.Attach(owner, feature); - Assert.Contains("\"shared\"", SnapshotJson.Write(owner, rootRegistry)); - Assert.Contains("\"shared\"", SnapshotJson.Write(feature, featureRegistry)); - var codec = new FeatureBundleCodec(registry); - string output = codec.Write(owner, attachments); - Assert.DoesNotContain("\"shared\"", output); - var restored = codec.Read(output); - Assert.IsType(Assert.Single(restored.Attachments.All(restored.Owner))); - } - [Fact] public void SavingValidatesTheWholeBundleBeforeReplacingTheDestination() { @@ -349,7 +311,4 @@ private static void Verify(FeatureBundle result) Assert.Equal(3, portfolio.Levels.Count); Assert.True(portfolio.Levels.Contains(NegativeZero) && portfolio.Levels.Contains(+0.0) && portfolio.Levels.Contains(double.NaN)); } - - private sealed class AppOwner; - private sealed class PluginFeature; } diff --git a/conformance/csharp/GetterRoleOwnershipTests.cs b/conformance/csharp/GetterRoleOwnershipTests.cs index 34515b49..f0ccdf97 100644 --- a/conformance/csharp/GetterRoleOwnershipTests.cs +++ b/conformance/csharp/GetterRoleOwnershipTests.cs @@ -54,19 +54,6 @@ Folder Read(string input) => references ? ModelSnapshot.Read(input) } } - [Fact] - public void StrictPlainAllowsAnEmptyRoleButNeedsTypeMetadataForConcreteChildren() - { - var empty = ModelSnapshot.ReadPlain(ModelSnapshot.WritePlain(new Folder())); - Assert.Empty(empty.Items); - Assert.Null(empty.First); - Assert.Null(empty.Selected); - - var (folder, _, _) = MoveChildren(); - Assert.Throws(() => ModelSnapshot.WritePlain(folder)); - Assert.Throws(() => ModelSnapshot.ReadPlain("""{"items":[{"label":"unknown"}]}""")); - } - [Fact] public void AGenericOwnerTransfersASpecializedChildWithASecondaryGetterRole() { @@ -91,7 +78,6 @@ public void AGenericOwnerTransfersASpecializedChildWithASecondaryGetterRole() Assert.Equal("T", byValue.Head!.TaskId); } - private static (Folder Folder, TaskItem Task, NoteItem Note) MoveChildren() { var left = new Folder(); diff --git a/conformance/csharp/GetterRoleSetOwnershipTests.cs b/conformance/csharp/GetterRoleSetOwnershipTests.cs index 75c5b708..b136d4a0 100644 --- a/conformance/csharp/GetterRoleSetOwnershipTests.cs +++ b/conformance/csharp/GetterRoleSetOwnershipTests.cs @@ -7,38 +7,6 @@ namespace Vmf.CSharp.Conformance; public sealed class GetterRoleSetOwnershipTests { - [Fact] - public void OrderedAndUnorderedRoleSetsTransferAndRecognizeProjectedAliases() - { - var source = new RoleSetFolder(); - var destination = new RoleSetFolder(); - var task = RoleSetTask.NewBuilder().WithTaskId("T").Build(); - var note = RoleSetNote.NewBuilder().WithMessage("N").Build(); - var view = destination.AsReadOnly(); - - Assert.True(source.Ordered.Add(task)); - Assert.False(source.Ordered.Add(task)); - Assert.True(destination.Unordered.Add(task)); - Assert.False(destination.Unordered.Add(task)); - Assert.Empty(source.Ordered); - Assert.True(destination.Unordered.Contains(task.AsReadOnly())); - Assert.True(view.Unordered.Contains(task.AsReadOnly())); - - Assert.True(destination.Ordered.Add(task)); - Assert.True(destination.Ordered.Add(note)); - Assert.Empty(view.Unordered); - bool containsOrderedAlias = destination.Ordered.Contains(task.AsReadOnly()); - Assert.True(containsOrderedAlias); - Assert.Equal(0, destination.Ordered.IndexOf(task.AsReadOnly())); - Assert.Same(task.AsReadOnly(), view.Ordered[0]); - destination.Ordered.Move(0, 1); - Assert.Same(note.AsReadOnly(), view.Ordered[0]); - Assert.Same(task.AsReadOnly(), view.Ordered[1]); - Assert.True(destination.Ordered.Remove(task.AsReadOnly())); - Assert.True(destination.Unordered.Add(task)); - Assert.True(destination.Unordered.Remove(task.AsReadOnly())); - Assert.Empty(view.Unordered); - } [Fact] public void IdentityKeyedRoleListsAdmitEqualDistinctKeysAndKeepOwnersAfterRejectedEdits() diff --git a/conformance/csharp/HierarchyTests.cs b/conformance/csharp/HierarchyTests.cs index f10d4317..1d4c93d3 100644 --- a/conformance/csharp/HierarchyTests.cs +++ b/conformance/csharp/HierarchyTests.cs @@ -6,19 +6,6 @@ namespace Vmf.CSharp.Conformance; public class HierarchyTests { - [Fact] - public void MutableTraitViewsShareStorageAndKeyChecks() - { - var catalog = NewCatalog(); - VerifyTraits(catalog); - } - - [Fact] - public void GenericDiamondClosesOneSlotPerLogicalProperty() - { - var model = NewParts(); - VerifyDiamond(model); - } [Fact] public void OpenOwningDiamondKeepsOneTrackedStorageSlotInBothPositions() @@ -120,28 +107,6 @@ static void CheckNamed(string document) } } - [Fact] - public void TwoOpenGenericRolesKeepIndependentTypesAndOneProjection() - { - var choice = new RankedChoice { Rank = 17 }; - var tool = new CalibratedTool { Size = 3, Calibration = 8 }; - var named = RankedDualChoice.NewBuilder().WithSelected(choice).WithBackup(tool).Build(); - DualChoice open = named; - ISecondaryChoice primary = open; - IToolBackup secondary = open; - IReadOnlySecondaryChoice primaryView = named.AsReadOnly(); - IReadOnlyToolBackup secondaryView = named.AsReadOnly(); - Assert.Same(choice, primary.Selected); - Assert.Same(tool, secondary.Backup); - Assert.Same(primaryView, secondaryView); - Assert.Equal(17, primaryView.Selected!.Rank); - Assert.Equal(8, secondaryView.Backup!.Calibration); - secondary.Backup = null; - Assert.Null(open.Backup); - Assert.Null(secondaryView.Backup); - Assert.Same(choice, primary.Selected); - } - [Fact] public void OpenGenericSecondaryReferenceListKeepsNullableAliasedSlots() { diff --git a/conformance/csharp/ImmutableCollectionTests.cs b/conformance/csharp/ImmutableCollectionTests.cs index e6ba14c2..6937bbf3 100644 --- a/conformance/csharp/ImmutableCollectionTests.cs +++ b/conformance/csharp/ImmutableCollectionTests.cs @@ -9,75 +9,6 @@ public class ImmutableCollectionTests { private static readonly double NegativeZero = BitConverter.Int64BitsToDouble(long.MinValue); - [Fact] - public void ImmutableNestedBuildersCaptureTheirSlotsAndBuildEachOccurrenceLazily() - { - var childBuilder = ImmutableBadge.NewBuilder().WithText("staged"); - var nested = new CountingBadgeBuilder(childBuilder); - List?> trail = [nested, null, nested]; - var staged = ExtendedPortfolio.NewBuilder().WithCurrentBuilder(nested).WithTrailBuilders(trail) - .WithPreferredBuilders([nested, nested]).WithPoolBuilders([nested, nested]); - trail.Clear(); - Assert.Equal(0, nested.Calls); - childBuilder.WithText("first"); - var first = staged.Build(); - Assert.Equal(7, nested.Calls); - childBuilder.WithText("second"); - IModelBuilder covariant = staged; - var second = Assert.IsType(covariant.Build()); - Assert.Equal(14, nested.Calls); - Verify(first, "first"); - Verify(second, "second"); - Assert.NotSame(first.Current, second.Current); - - var direct = new ImmutableBadge("direct"); - var replaced = staged.WithCurrent(direct).WithTrail([direct, null, direct]) - .WithPreferred([direct]).WithPool([direct]).Build(); - AssertDirect(replaced, direct); - var imported = staged.WithCurrentBuilder(nested).WithTrailBuilders([nested]) - .WithPreferredBuilders([nested]).WithPoolBuilders([nested]).ApplyFrom(replaced).Build(); - AssertDirect(imported, direct); - Assert.Equal(14, nested.Calls); - Assert.Null(staged.WithCurrentBuilder(null).Build().Current); - - static void Verify(ExtendedPortfolio value, string text) - { - Assert.Equal(text, value.Current!.Text); - Assert.Equal(3, value.Trail.Count); - Assert.Null(value.Trail[1]); - Assert.NotSame(value.Current, value.Trail[0]); - Assert.NotSame(value.Trail[0], value.Trail[2]); - Assert.Equal(text, value.Trail[0]!.Text); - Assert.Equal(text, value.Trail[2]!.Text); - Assert.Equal(2, value.Preferred.Count); - Assert.Equal(2, value.Pool.Count); - Assert.All(value.Preferred, item => Assert.Equal(text, item.Text)); - Assert.All(value.Pool, item => Assert.Equal(text, item.Text)); - } - - static void AssertDirect(ExtendedPortfolio value, ImmutableBadge badge) - { - Assert.Same(badge, value.Current); - Assert.Equal(3, value.Trail.Count); - Assert.Same(badge, value.Trail[0]); - Assert.Null(value.Trail[1]); - Assert.Same(badge, value.Trail[2]); - Assert.Same(badge, Assert.Single(value.Preferred)); - Assert.Same(badge, Assert.Single(value.Pool)); - } - } - - private sealed class CountingBadgeBuilder(ImmutableBadge.Builder source) : IModelBuilder - { - public int Calls { get; private set; } - - public ImmutableBadge Build() - { - Calls++; - return source.Build(); - } - } - [Fact] public void ImmutableBuilderImportsAppendOrReplaceCollections() { diff --git a/conformance/csharp/ImmutableValueTests.cs b/conformance/csharp/ImmutableValueTests.cs index 807769ec..2116778a 100644 --- a/conformance/csharp/ImmutableValueTests.cs +++ b/conformance/csharp/ImmutableValueTests.cs @@ -8,24 +8,6 @@ public class ImmutableValueTests { private static readonly string Fixture = Path.Combine(AppContext.BaseDirectory, "fixtures", "immutable-selection.json"); - [Fact] - public void ImmutableValuesHaveStructuralEqualityAndAnIdentityView() - { - var first = new ValueLabel("A"); - var second = new ValueLabel("A"); - Assert.Equal(first, second); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); - Assert.NotSame(first, second); - var node = new ValueNode(first); - var equalContent = new ValueNode(second); - Assert.NotEqual(node, equalContent); - Assert.True(node.ContentEquals(equalContent)); - Assert.Same(first, first.AsReadOnly()); - Assert.False(typeof(ValueLabel).GetProperty("Text")!.CanWrite); - Assert.Equal("A", ModelSnapshot.ReadPlain( - ModelSnapshot.WritePlain(first)).Text); - } - [Fact] public void ReferenceSnapshotsResolveForwardImmutableAliasesAndPreserveTwins() { diff --git a/conformance/csharp/JournalHistoryTests.cs b/conformance/csharp/JournalHistoryTests.cs index e8ef1e83..ff117605 100644 --- a/conformance/csharp/JournalHistoryTests.cs +++ b/conformance/csharp/JournalHistoryTests.cs @@ -103,24 +103,6 @@ public void RejectsChangedDescendantBindingsBeforeReplayOrRecording(bool changeI Assert.Same(checkpoint, originalChild!.Parent); } - [Fact] - public void OnlyTheSelectedPrefixIsValidatedAndAStaleOverlapIsReported() - { - var earlier = NewArchive(); - var history = NewHistory(); - history.AddSegment("earlier", earlier, Record(earlier, "earlier", 30, - root => root.Anchor = root.Children[0], root => root.Anchor = root.Inset)); - Assert.Equal("right", history.Seek(32).Anchor!.Name); - - var later = history.Seek(31); - var staleChange = new JournalSet("main", "anchor", JournalValue.Reference("right"), JournalValue.FromScalar(null)); - history.AddSegment("later", later, Journal("later", 31, new JournalFrame(32, [staleChange]))); - - Assert.Equal("left", history.Seek(31).Anchor!.Name); - Assert.Throws(() => history.Seek(32)); - Assert.Equal("left", history.Seek(31).Anchor!.Name); - } - [Fact] public void CoversTheLargestSequenceWithoutOverflow() { @@ -138,105 +120,6 @@ public void CoversTheLargestSequenceWithoutOverflow() Assert.Equal("right", history.Seek(long.MaxValue).Anchor!.Name); } - [Fact] - public void LiveCheckpointCopiesKeepOverridesOnlyForManagedCollections() - { - const string id = "managed-defaults"; - const long sequence = 70; - var checkpoint = new CollectionProfile(); - checkpoint.Messages.AddRange(["kept", null]); - DefaultField(checkpoint, "messages").SetDefault(new[] { "unused" }); - DefaultField(checkpoint, "counts").SetDefault(new[] { 2, 3 }); - DefaultField(checkpoint, "levels").SetDefault(new[] { 2.5 }); - DefaultField(checkpoint, "phases").SetDefault(new[] { "prepare", "finish" }); - DefaultField(checkpoint, "options").SetDefault(new Dictionary { ["ready"] = true, ["absent"] = null }); - var binding = new JournalBinding(Model, 1, _ => "profile"); - var empty = new ChangeJournal(Model, 1, "profile", id, sequence, []); - var direct = JournalReplayer.Replay(checkpoint, binding, id, empty, ModelSnapshot.Registry); - VerifyManagedDefaults(direct); - Assert.Equal(new object?[] { "unused" }, - Assert.IsAssignableFrom>(DefaultField(checkpoint, "messages").DefaultValue)); - Assert.Empty(Assert.IsAssignableFrom>(DefaultField(direct, "messages").DefaultValue)); - - var initial = new JournalHistory(binding, ModelSnapshot.Registry); - initial.AddSegment(id, checkpoint, empty); - var working = initial.Seek(sequence); - VerifyManagedDefaults(working); - int shadowInspections = 0; - var recordingBinding = new JournalBinding(Model, 1, candidate => - { - if (!ReferenceEquals(candidate, working)) - { - VerifyManagedDefaults(Assert.IsType(candidate)); - shadowInspections++; - } - return "profile"; - }); - using var recorder = JournalRecorder.Start(working, ModelSnapshot.Registry, recordingBinding, id, sequence); - working.Counts.Add(9); - var journal = recorder.Finish(); - Assert.True(shadowInspections > 0); - Assert.Equal(1, journal.WireVersion); - - var hydrated = ModelSnapshot.Read(ModelSnapshot.Write(checkpoint)); - Assert.True(DefaultField(hydrated, "counts").IsSet); - var plain = JournalRecorder.RecordFrame(hydrated, ModelSnapshot.Registry, binding, id, - sequence, profile => profile.Counts.Add(9)); - Assert.Equal(JournalJson.Write(plain), JournalJson.Write(journal)); - Assert.Equal(JournalYaml.Write(plain), JournalYaml.Write(journal)); - Assert.Equal(JournalXml.Write(plain), JournalXml.Write(journal)); - - var history = new JournalHistory(binding, ModelSnapshot.Registry); - history.AddSegment(id, checkpoint, JournalJson.Read(JournalJson.Write(journal))); - DefaultField(checkpoint, "counts").SetDefault(new[] { 12 }); - var replayed = history.Seek(sequence + 1); - Assert.Equal([2, 3, 9], replayed.Counts); - Assert.True(DefaultField(replayed.AsReadOnly(), "counts").IsSet); - DefaultField(replayed, "counts").Reset(); - Assert.Equal([2, 3], replayed.Counts); - Assert.False(DefaultField(replayed.AsReadOnly(), "counts").IsSet); - replayed.Options.Clear(); - Assert.True(checkpoint.Options.ContainsKey("ready")); - Assert.Equal([2, 3, 9], history.Seek(sequence + 1).Counts); - Assert.Equal([12], checkpoint.Counts); - VerifyManagedDefaults(history.Seek(sequence)); - } - - [Fact] - public void ScalarOverrideKeepsTheLiveValueAndReturnsToItsDeclaredDefaultInReplay() - { - var checkpoint = new DefaultSettings(); - DefaultField(checkpoint, "limit").SetDefault(8); - var binding = new JournalBinding(Model, 1, _ => "settings"); - var journal = new ChangeJournal(Model, 1, "settings", "scalar", 0, []); - var copy = JournalReplayer.Replay(checkpoint, binding, "scalar", journal, ModelSnapshot.Registry); - Assert.Equal(8, copy.Limit); - Assert.Equal(7, DefaultField(copy, "limit").DefaultValue); - Assert.True(DefaultField(copy, "limit").IsSet); - DefaultField(copy, "limit").Reset(); - Assert.Equal(7, copy.Limit); - Assert.Equal(8, checkpoint.Limit); - Assert.False(DefaultField(checkpoint, "limit").IsSet); - } - - private static void VerifyManagedDefaults(CollectionProfile profile) - { - foreach (var view in new object[] { profile, profile.AsReadOnly() }) - { - Assert.Equal(new object?[] { 2, 3 }, Assert.IsAssignableFrom>(DefaultField(view, "counts").DefaultValue)); - Assert.Equal(new object?[] { 2.5 }, Assert.IsAssignableFrom>(DefaultField(view, "levels").DefaultValue)); - Assert.Equal(new object?[] { "prepare", "finish" }, - Assert.IsAssignableFrom>(DefaultField(view, "phases").DefaultValue)); - var options = Assert.IsAssignableFrom>(DefaultField(view, "options").DefaultValue); - Assert.Equal(true, options["ready"]); - Assert.Null(options["absent"]); - foreach (var name in new[] { "levels", "phases", "options" }) Assert.False(DefaultField(view, name).IsSet); - } - Assert.Equal(new string?[] { "kept", null }, profile.Messages); - } - - private static ModelProperty DefaultField(object model, string name) => ModelSnapshot.Reflection.Reflect(model).FindProperty(name)!; - [Theory] [InlineData(499)] [InlineData(500)] diff --git a/conformance/csharp/JournalTests.cs b/conformance/csharp/JournalTests.cs index 4c1655e4..65b940b2 100644 --- a/conformance/csharp/JournalTests.cs +++ b/conformance/csharp/JournalTests.cs @@ -18,41 +18,6 @@ public class JournalTests model => model is ScalarSample ? "scalar-sample" : throw new ArgumentException("Unknown scalar model."), (_, field) => field switch { "description" => "NAME", "optionalDouble" => "probe", _ => field }); - [Fact] - public void RecorderStartLeavesAnExistingNativeOrPortableRecordingIntact() - { - var native = NewSample(); - native.VmfChanges.Start(); - native.Description = "native edit"; - Assert.Throws(() => - { - using var rejected = JournalRecorder.Start(native, ModelSnapshot.Registry, Binding, CheckpointId, 40); - }); - Assert.True(native.VmfChanges.IsRecording); - Assert.Equal("native edit", Assert.Single(native.VmfChanges.History).NewValue); - native.VmfChanges.Stop(); - Assert.Single(native.VmfChanges.Transactions); - - var portable = NewSample(); - using var owner = JournalRecorder.Start(portable, ModelSnapshot.Registry, Binding, CheckpointId, 40); - portable.Description = "portable edit"; - Assert.Throws(() => - { - using var rejected = JournalRecorder.Start(portable, ModelSnapshot.Registry, Binding, CheckpointId, 40); - }); - Assert.True(portable.VmfChanges.IsRecording); - Assert.Equal("portable edit", Assert.Single(portable.VmfChanges.History).NewValue); - var journal = owner.Finish(); - Assert.Equal("portable edit", Assert.IsType( - Assert.Single(Assert.Single(journal.Transactions).Operations)).After.Text); - Assert.False(portable.VmfChanges.IsRecording); - - var reopened = JournalRecorder.RecordFrame(portable, ModelSnapshot.Registry, Binding, - CheckpointId, 41, sample => sample.Description = "next recording"); - Assert.Equal("next recording", Assert.IsType( - Assert.Single(Assert.Single(reopened.Transactions).Operations)).After.Text); - } - [Fact] public void RecorderStartLeavesManualVersioningAndEarlierHistoryIntact() { @@ -178,34 +143,6 @@ public void PublishFrameRejectsNestedLifecycleCallsAndContinuesWhenObserverCatch Assert.Equal(2, recorder.Finish().Transactions.Count); } - [Fact] - public void PublishFramePropagatesUncaughtNestedFailureAndRetainsTheNativeGroup() - { - var sample = NewSample(); - using var recorder = JournalRecorder.Start(sample, ModelSnapshot.Registry, Binding, CheckpointId, 40); - Exception? nested = null; - using var listener = sample.VmfChanges.Transactions.AddListener(_ => - { - try - { - recorder.PublishFrame(); - } - catch (InvalidOperationException error) - { - nested = error; - throw; - } - }); - sample.Description = "published"; - - var failure = Assert.Throws(() => recorder.PublishFrame()); - Assert.Same(nested, failure); - Assert.Equal("published", sample.Description); - Assert.False(sample.VmfChanges.IsRecording); - Assert.Single(sample.VmfChanges.History); - Assert.Single(Assert.Single(sample.VmfChanges.Transactions).Changes); - } - [Fact] public void NativePublicationRetainsItsGroupWhenThePortableCaptureFails() { @@ -325,54 +262,6 @@ public void ReaderValidatesEnvelopeAndCanonicalTaggedValues() Assert.Throws(() => JournalValue.FromScalar("\uD800")); } - [Fact] - public void RecorderCapturesDescendantEditsAndKeepsStableIdsOnReplay() - { - var owner = new ArchiveOwner(); - var leaf = new ArchiveOwnedLeaf { Label = "initial", Owner = owner }; - var baseline = ModelSnapshot.Write(owner); - var binding = new JournalBinding("conformance.descendant-journal", 1, model => model switch - { - ArchiveOwner => "owner", - ArchiveOwnedLeaf => "leaf", - _ => throw new ArgumentException("Unknown checkpoint model.") - }); - - using var recorder = JournalRecorder.Start(owner, ModelSnapshot.Registry, binding, "baseline", 4); - leaf.Label = "changed"; - var journal = recorder.Finish(); - var edit = Assert.Single(Assert.Single(journal.Transactions).Operations); - Assert.Equal("leaf", edit.Target); - Assert.Equal("label", edit.Property); - - var fresh = ModelSnapshot.Read(baseline); - var restored = JournalReplayer.Replay(fresh, binding, "baseline", journal, ModelSnapshot.Registry); - var restoredLeaf = Assert.IsType(Assert.Single(restored.Nodes)); - Assert.Equal("changed", restoredLeaf.Label); - Assert.Same(restored, restoredLeaf.Owner); - Assert.Equal("initial", Assert.IsType(Assert.Single(fresh.Nodes)).Label); - } - - [Fact] - public void JournalPropertyUsesTheModelNameWhenTheJsonKeyWasRenamed() - { - var batch = new ScalarBatch { Title = "A" }; - var entry = new ScalarEntry { StatusLabel = "X-12" }; - batch.Entries.Add(entry); - var baseline = ModelSnapshot.Write(batch); - using var document = JsonDocument.Parse(baseline); - Assert.Equal("X-12", document.RootElement.GetProperty("entries")[0].GetProperty("status_label").GetString()); - - var binding = new JournalBinding("conformance.renamed-field", 1, model => model is ScalarBatch ? "batch" : "entry"); - using var recorder = JournalRecorder.Start(batch, ModelSnapshot.Registry, binding, "baseline", 0); - entry.StatusLabel = "X-13"; - var journal = recorder.Finish(); - Assert.Equal("statusLabel", Assert.Single(Assert.Single(journal.Transactions).Operations).Property); - var restored = JournalReplayer.Replay(ModelSnapshot.Read(baseline), binding, "baseline", - journal, ModelSnapshot.Registry); - Assert.Equal("X-13", Assert.Single(restored.Entries).StatusLabel); - } - [Fact] public void NativeTransactionPublicationPreservesUngroupedPrefixAndExplicitFrames() { @@ -394,39 +283,6 @@ public void NativeTransactionPublicationPreservesUngroupedPrefixAndExplicitFrame Assert.Equal(9, replayed.OptionalInt); } - [Fact] - public void FailedRecordCallbackKeepsEditsButDoesNotPublishPendingFrame() - { - var working = NewSample(); - var failure = new InvalidOperationException("failed after editing"); - var thrown = Assert.Throws(() => - JournalRecorder.RecordFrame(working, ModelSnapshot.Registry, Binding, CheckpointId, 40, - model => - { - model.Description = "applied"; - throw failure; - })); - Assert.Same(failure, thrown); - Assert.Equal("applied", working.Description); - Assert.False(working.VmfChanges.IsRecording); - Assert.Single(working.VmfChanges.History); - Assert.Empty(working.VmfChanges.Transactions); - } - - [Fact] - public void DisposeKeepsAppliedEditsAndOmitsTheUnpublishedFrame() - { - var working = NewSample(); - using (JournalRecorder.Start(working, ModelSnapshot.Registry, Binding, CheckpointId, 40)) - { - working.Description = "edited"; - } - Assert.False(working.VmfChanges.IsRecording); - Assert.Equal("edited", working.Description); - Assert.Equal("edited", Assert.Single(working.VmfChanges.History).NewValue); - Assert.Empty(working.VmfChanges.Transactions); - } - [Fact] public void RecorderRejectsChangedIdsWithoutRevertingTheWorkingModel() { diff --git a/conformance/csharp/KeyedGetterRoleOwnershipTests.cs b/conformance/csharp/KeyedGetterRoleOwnershipTests.cs index 2ce178b5..6be53ec0 100644 --- a/conformance/csharp/KeyedGetterRoleOwnershipTests.cs +++ b/conformance/csharp/KeyedGetterRoleOwnershipTests.cs @@ -6,42 +6,6 @@ namespace Vmf.CSharp.Conformance; public sealed class KeyedGetterRoleOwnershipTests { - [Fact] - public void LookupFollowsTransfersAndKeyChangesThroughMutableAndProjectedOwners() - { - var source = new KeyedFolder(); - var destination = new KeyedFolder(); - var task = KeyedTask.NewBuilder().WithKey("task").WithTaskId("T").Build(); - var note = KeyedNote.NewBuilder().WithKey("note").WithMessage("M").Build(); - var duplicate = KeyedNote.NewBuilder().WithKey("task").Build(); - source.Entries.Add(task); - destination.Entries.Add(note); - var other = new KeyedFolder(); - other.Entries.Add(duplicate); - var view = destination.AsReadOnly(); - Assert.Same(task, source.FindEntriesByKey("task")); - destination.Entries.Add(task); - Assert.Null(source.FindEntriesByKey("task")); - Assert.Same(task, destination.FindEntriesByKey("task")); - Assert.Same(task.AsReadOnly(), view.FindEntriesByKey("task")); - Assert.Throws(() => destination.Entries.Add(duplicate)); - Assert.Same(duplicate, other.FindEntriesByKey("task")); - Assert.Throws(() => task.Key = "note"); - Assert.Throws(() => task.Key = null); - Assert.Equal("task", task.Key); - - task.Key = "renamed"; - Assert.Null(view.FindEntriesByKey("task")); - Assert.Same(task.AsReadOnly(), view.FindEntriesByKey("renamed")); - ModelSnapshot.Reflection.Reflect(task).FindProperty("key")!.Reset(); - Assert.Same(task, destination.FindEntriesByKey("reset")); - Assert.Null(destination.FindEntriesByKey("renamed")); - Assert.Throws(() => ModelSnapshot.Reflection.Reflect(note).FindProperty("key")!.Reset()); - Assert.Same(note, destination.FindEntriesByKey("note")); - Assert.True(destination.Entries.Remove(note)); - ModelSnapshot.Reflection.Reflect(note).FindProperty("key")!.Reset(); - Assert.Equal("reset", note.Key); - } [Fact] public void AReadOnlyAliasCanFindAndRemoveItsKeyedEntry() diff --git a/conformance/csharp/KeyedTests.cs b/conformance/csharp/KeyedTests.cs index a467c39a..36e01dcd 100644 --- a/conformance/csharp/KeyedTests.cs +++ b/conformance/csharp/KeyedTests.cs @@ -146,52 +146,6 @@ private static KeyedInventory JournalCheckpoint() => KeyedInventory.NewBuilder() new KeyedItem { Sku = "right", Quantity = 3 }]) .WithParts([new KeyedPart { Name = "key" }]).Build(); - [Fact] - public void KeyedListReportsPositionsAndCanonicalIdentitiesFromBothViews() - { - var inventory = JournalCheckpoint(); - var products = inventory.Products; - var view = inventory.AsReadOnly().Products; - var oldItem = products[1]; - var replacement = new KeyedItem { Sku = "replacement", Quantity = 7 }; - int mutableEvents = 0; - int viewEvents = 0; - using (products.AddListener(edit => - { - mutableEvents++; - Assert.Same(products, edit.Source); - var removed = Assert.Single(edit.Removed); - var added = Assert.Single(edit.Added); - Assert.Equal(1, removed.Index); - Assert.Equal(1, added.Index); - Assert.Same(oldItem, removed.Value); - Assert.Same(replacement, added.Value); - Assert.Null(inventory.FindProductsBySku("middle")); - Assert.Same(replacement, inventory.FindProductsBySku("replacement")); - })) - using (view.AddListener(edit => - { - viewEvents++; - Assert.Same(view, edit.Source); - var removed = Assert.Single(edit.Removed); - var added = Assert.Single(edit.Added); - Assert.Equal(1, removed.Index); - Assert.Equal(1, added.Index); - Assert.Same(oldItem.AsReadOnly(), removed.Value); - Assert.Same(replacement.AsReadOnly(), added.Value); - Assert.Same(replacement.AsReadOnly(), view[1]); - })) - { - Assert.ThrowsAny(() => products[1] = new KeyedItem { Sku = "left" }); - Assert.Equal(0, mutableEvents); - Assert.Equal(0, viewEvents); - products[1] = replacement; - } - products.RemoveAt(1); - Assert.Equal(1, mutableEvents); - Assert.Equal(1, viewEvents); - } - [Fact] public void ScalarKeysAreLiveAcrossInheritedSettersAndReadOnlyViews() { @@ -229,33 +183,6 @@ public void KeyedBuilderRejectsDuplicateKeysWithoutReplacingItsStageOrMovingChil Assert.Empty(existingOwner.Products); } - [Fact] - public void LazyScalarKeysAreCheckedAtBuildAndImportsMoveOnlyTheDirectEntries() - { - var item = StockKeyed.Item.NewBuilder().WithSku("A"); - var other = StockKeyed.Item.NewBuilder().WithSku("A"); - var stage = StockKeyed.Catalog.NewBuilder().WithItemsBuilders([item, other]); - var existing = item.Build(); - var target = StockKeyed.Catalog.NewBuilder().WithItems([existing]).Build(); - stage.ApplyTo(target); - Assert.Same(existing, Assert.Single(target.Items)); - stage.AppendCollections(false).ApplyTo(target); - Assert.Empty(target.Items); - Assert.ThrowsAny(() => stage.Build()); - - other.WithSku("B"); - var first = stage.Build(); - var second = stage.Build(); - Assert.Equal(new[] { "A", "B" }, first.Items.Select(entry => entry.Sku)); - Assert.NotSame(first.FindItemsBySku("B"), second.FindItemsBySku("B")); - - stage.ApplyFrom(first); - var entry = first.Items[0]; - var imported = stage.Build(); - Assert.Same(entry, imported.FindItemsBySku("A")); - Assert.Empty(first.Items); - } - [Fact] public void LazyOrderedIdentityKeysResolveAndTransferTheActualEntries() { @@ -291,36 +218,6 @@ public void LazyOrderedIdentityKeysResolveAndTransferTheActualEntries() Assert.Empty(source.Parts); } - [Fact] - public void ReparentPreflightsKeysAndPendingKeyMutationsAgainstTheDestination() - { - var source = KeyedInventory.NewBuilder() - .WithProducts([KeyedItem.NewBuilder().WithSku("A").Build(), KeyedItem.NewBuilder().WithSku("B").Build()]).Build(); - var item = source.Products[0]; - var destination = KeyedInventory.NewBuilder().WithProducts( - [KeyedItem.NewBuilder().WithSku("B").Build()]).Build(); - Assert.ThrowsAny(() => destination.Products.AddRange(source.Products)); - Assert.Equal(2, source.Products.Count); - Assert.Single(destination.Products); - - int observed = 0; - using var watch = source.VmfChanges.AddPropertyListener("products", _ => - { - observed++; - Assert.Same(item, destination.FindProductsBySku("A")); - Assert.ThrowsAny(() => item.Sku = "B"); - Assert.ThrowsAny(() => item.Sku = null); - Assert.Equal("A", item.Sku); - item.Sku = "C"; - Assert.Same(item, destination.FindProductsBySku("C")); - }); - Assert.True(destination.Products.Add(item)); - Assert.Equal(1, observed); - Assert.Same(item, destination.FindProductsBySku("C")); - Assert.Null(source.FindProductsBySku("C")); - Assert.Equal("B", Assert.Single(source.Products).Sku); - } - [Fact] public void ReferenceKeysUseModelIdentityAndAcceptReadOnlyAliases() { diff --git a/conformance/csharp/KeyedUnorderedOwnershipTests.cs b/conformance/csharp/KeyedUnorderedOwnershipTests.cs index ef5ca847..6c9564f6 100644 --- a/conformance/csharp/KeyedUnorderedOwnershipTests.cs +++ b/conformance/csharp/KeyedUnorderedOwnershipTests.cs @@ -8,63 +8,6 @@ namespace Vmf.CSharp.Conformance; public sealed class KeyedUnorderedOwnershipTests { - [Fact] - public void LookupFollowsKeyChangesAndRejectsCollidingTransfers() - { - var first = Key("same"); - var second = Key("same"); - var next = Key("next"); - Assert.Equal(first, second); - var task = RoleSetTask.NewBuilder().WithToken(first).Build(); - var note = RoleSetNote.NewBuilder().WithToken(second).Build(); - var duplicate = RoleSetNote.NewBuilder().WithToken(first).Build(); - var src = UnorderedKeyedFolder.NewBuilder().WithItems([task]).Build(); - var target = UnorderedKeyedFolder.NewBuilder().WithItems([note]).Build(); - var previous = RoleSetFolder.NewBuilder().WithUnordered([duplicate]).Build(); - var view = target.AsReadOnly(); - int departures = 0; - using var observer = src.VmfChanges.AddPropertyListener("items", change => - { - Assert.Equal(ModelChangeKind.ReferenceSet, change.Kind); - Assert.Null(src.FindItemsByToken(first)); - Assert.Same(task, target.FindItemsByToken(first)); - Assert.Throws(() => task.Token = second); - departures++; - }); - - Assert.True(target.Items.Add(task)); - Assert.Equal(1, departures); - Assert.False(target.Items.Add(task)); - Assert.Empty(src.Items); - Assert.Same(task, target.FindItemsByToken(first)); - Assert.Same(note, target.FindItemsByToken(second)); - Assert.Same(note.AsReadOnly(), view.FindItemsByToken(second.AsReadOnly())); - Assert.True(view.Items.Contains(task.AsReadOnly())); - Assert.Throws(() => target.Items.Add(duplicate)); - Assert.Same(duplicate, Assert.Single(previous.Unordered)); - Assert.Throws(() => task.Token = second); - Assert.Throws(() => task.Token = null); - Assert.Same(first, task.Token); - task.Token = next; - Assert.Null(target.FindItemsByToken(first)); - Assert.Same(task.AsReadOnly(), view.FindItemsByToken(next.AsReadOnly())); - Assert.True(target.Items.Remove(task.AsReadOnly())); - Assert.Null(view.FindItemsByToken(next.AsReadOnly())); - } - - [Fact] - public void NativeBuilderRejectsCollidingKeysWhileStaging() - { - var key = Key("same"); - var first = RoleSetTask.NewBuilder().WithToken(key).Build(); - var second = RoleSetNote.NewBuilder().WithToken(key).Build(); - var left = UnorderedKeyedFolder.NewBuilder().WithItems([first]).Build(); - var right = UnorderedKeyedFolder.NewBuilder().WithItems([second]).Build(); - - Assert.Throws(() => UnorderedKeyedFolder.NewBuilder().WithItems([first, second])); - Assert.Same(first, left.FindItemsByToken(key)); - Assert.Same(second, right.FindItemsByToken(key)); - } [Fact] public void ApplyToChecksTargetKeysBeforeChangingMembership() @@ -148,16 +91,6 @@ public void ExactTypePlainJsonRestoresScalarKeysAndRejectsDuplicates() """{"items":[{"key":"same"},{"key":"same"}]}""")); } - [Fact] - public void ReferencesAreRequiredForPopulatedIdentityKeysAndDuplicateResolvedKeysFail() - { - var folder = BuildSnapshot(references: true); - Assert.Throws(() => ModelSnapshot.WriteWithoutReferences(folder)); - var document = JsonNode.Parse(ModelSnapshot.Write(folder))!; - document["items"]![1]!["token"] = document["items"]![0]!["token"]!.DeepClone(); - Assert.Throws(() => ModelSnapshot.Read(document.ToJsonString())); - } - private static RoleKey Key(string code) => RoleKey.NewBuilder().WithCode(code).Build(); private static UnorderedKeyedFolder BuildSnapshot(bool references) diff --git a/conformance/csharp/ListPredicateTests.cs b/conformance/csharp/ListPredicateTests.cs index 4e83a89e..33dde8e7 100644 --- a/conformance/csharp/ListPredicateTests.cs +++ b/conformance/csharp/ListPredicateTests.cs @@ -15,23 +15,6 @@ public class ListPredicateTests _ => throw new ArgumentException("Expected a predicate fixture model.", nameof(model)) }); - [Fact] - public void PredicateFailureDoesNotPublishOrRemoveAnySlots() - { - var profile = Profile(); - var events = new List>(); - using var subscribed = profile.Messages.AddListener(events.Add); - using var recorder = JournalRecorder.Start(profile, ModelSnapshot.Registry, Binding, Checkpoint, 0); - Assert.Throws(() => profile.Messages.RemoveWhere(value => value is null - ? throw new InvalidOperationException("predicate failed") - : true)); - Assert.Equal(0, profile.Messages.RemoveWhere(_ => false)); - Assert.Equal(new string?[] { "same", null, "same", "held", "cut" }, profile.Messages.AsEnumerable()); - Assert.Empty(events); - Assert.Empty(profile.VmfChanges.History); - Assert.Empty(recorder.Finish().Transactions); - } - [Fact] public void CheckedUniquePredicateUndoRestoresTheOriginalSparsePositionsInOneEdit() { diff --git a/conformance/csharp/ListReplacementTests.cs b/conformance/csharp/ListReplacementTests.cs index 9e2fadbc..aebd4926 100644 --- a/conformance/csharp/ListReplacementTests.cs +++ b/conformance/csharp/ListReplacementTests.cs @@ -38,32 +38,6 @@ public void TransformAndCheckedValidationFailBeforeChangingAnySlots() Assert.Equal(["a", "b", "c"], profile.Phases.AsEnumerable()); } - [Fact] - public void OrdinaryReferenceReplacementKeepsNullsAndAliasesThroughNativeUndoAndRedo() - { - var node = new ArchiveNode { Name = "head" }; - var alias = new ArchiveNode { Name = "alias" }; - node.Trail.AddRange([alias, null, alias, node]); - var order = new List(); - using var project = node.AsReadOnly().Trail.AddListener(edit => order.Add("view:" + Indices(edit))); - using var raw = node.Trail.AddListener(edit => order.Add("mutable:" + Indices(edit))); - - node.VmfChanges.Start(); - node.Trail.ReplaceAll(item => ReferenceEquals(item, alias) ? node : item); - var change = Assert.IsType(Assert.Single(node.VmfChanges.History)); - node.VmfChanges.Stop(); - Assert.Equal(["view:0,1,2,3", "mutable:0,1,2,3"], order); - Assert.Collection(node.Trail, item => Assert.Same(node, item), Assert.Null, - item => Assert.Same(node, item), item => Assert.Same(node, item)); - Assert.True(change.Undo()); - Assert.Same(alias, node.Trail[0]); - Assert.Same(alias, node.Trail[2]); - Assert.True(change.Redo()); - Assert.Same(node, node.Trail[0]); - Assert.Same(node, node.Trail[2]); - Assert.Null(node.Trail[1]); - } - [Fact] public void ScalarReplacementAndIdentityTransformExchangeOneFullV1EditEach() { diff --git a/conformance/csharp/ModelMergeAliasTests.cs b/conformance/csharp/ModelMergeAliasTests.cs deleted file mode 100644 index 6131ae1b..00000000 --- a/conformance/csharp/ModelMergeAliasTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Eu.Mihosoft.Vmf.Conformance.Values; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public class ModelMergeAliasTests -{ - [Theory] - [InlineData(false)] - [InlineData(true)] - public void MergeCopiesDetachedReferencesOnceAcrossFieldsAndRebindsTheirCycle(bool projected) - { - var template = new ArchiveNode { Name = "template" }; - var overlay = new ArchiveNode { Name = "overlay" }; - var shared = new ArchiveNode { Name = "shared" }; - overlay.Anchor = shared; - overlay.Trail.AddRange([shared, null, shared]); - overlay.Peers.Add(shared); - shared.Anchor = overlay; - - var reflection = ModelSnapshot.Reflection; - var merged = projected - ? reflection.Merge(template.AsReadOnly(), overlay.AsReadOnly()) - : reflection.Merge(template, overlay).AsReadOnly(); - var copied = Assert.IsAssignableFrom(merged.Anchor); - Assert.NotSame(shared.AsReadOnly(), copied); - Assert.Equal("shared", copied.Name); - Assert.Same(merged, copied.Anchor); - Assert.Equal(new IReadOnlyArchiveNode?[] { copied, null, copied }, merged.Trail); - Assert.Same(copied, Assert.Single(merged.Peers)); - - shared.Name = "changed after merge"; - Assert.Equal("shared", copied.Name); - Assert.Same(overlay, shared.Anchor); - Assert.Same(shared, overlay.Anchor); - Assert.Same(shared, Assert.Single(overlay.Peers)); - Assert.Null(template.Anchor); - Assert.Empty(template.Trail); - Assert.Empty(template.Peers); - } -} diff --git a/conformance/csharp/ModelPatchAliasTests.cs b/conformance/csharp/ModelPatchAliasTests.cs deleted file mode 100644 index 74c9a818..00000000 --- a/conformance/csharp/ModelPatchAliasTests.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Eu.Mihosoft.Vmf.Conformance.Values; -using Vmf.Runtime; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class ModelPatchAliasTests -{ - [Fact] - public void SwappingOwningFieldsPreservesBothIdentitiesAndAllowsUndo() - { - var source = new ArchiveNode { Name = "root" }; - var left = new ArchiveNode { Name = "left" }; - var right = new ArchiveNode { Name = "right" }; - source.Children.Add(left); - source.Inset = right; - source.Anchor = left; - var desired = ModelSnapshot.Reflection.DeepCopy(source); - desired.Children.Add(desired.Inset!); - desired.Inset = desired.Children[0]; - - var patch = ModelSnapshot.Reflection.Diff(source, desired); - Assert.DoesNotContain(patch.Changes, change => change.PropertyName == "anchor"); - Assert.Same(source, left.Parent); - Assert.Same(source, right.InsetOf); - patch.Apply(source, ModelPatchApplyMode.RequireBeforeValues); - Assert.Same(left, source.Inset); - Assert.Same(right, Assert.Single(source.Children)); - Assert.Same(left, source.Anchor); - Assert.Same(source, left.InsetOf); - Assert.Same(source, right.Parent); - - patch.Undo(source); - Assert.Same(left, Assert.Single(source.Children)); - Assert.Same(right, source.Inset); - Assert.Same(left, source.Anchor); - Assert.Same(source, left.Parent); - Assert.Same(source, right.InsetOf); - } -} diff --git a/conformance/csharp/ModelPatchCopyReferenceTests.cs b/conformance/csharp/ModelPatchCopyReferenceTests.cs deleted file mode 100644 index a1e96a00..00000000 --- a/conformance/csharp/ModelPatchCopyReferenceTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -using Eu.Mihosoft.Vmf.Conformance.Values; -using Vmf.Runtime; -using Xunit; -using Equality = Eu.Mihosoft.Vmf.Conformance.Equality; - -namespace Vmf.CSharp.Conformance; - -public sealed class ModelPatchCopyReferenceTests -{ - [Fact] - public void NewSubtreeOutboundReferencesUseTheRetainedSibling() - { - var source = new ArchiveNode { Name = "root" }; - var retained = new ArchiveNode { Name = "retained" }; - source.Children.Add(retained); - var desired = ModelSnapshot.Reflection.DeepCopy(source); - var reference = Assert.Single(desired.Children); - var leaf = new ArchiveNode { Name = "new leaf" }; - leaf.Trail.AddRange([reference, null, reference]); - var branch = new ArchiveNode { Name = "new branch", Anchor = reference, Inset = leaf }; - desired.Inset = branch; - desired.Anchor = branch; - - var attachments = new List(); - using var subscription = source.VmfChanges.AddPropertyListener("inset", _ => - { - if (source.Inset is { } attached) - attachments.Add(ReferenceEquals(attached.Anchor, retained)); - }); - var patch = ModelSnapshot.Reflection.Diff(source, desired); - Assert.Null(source.Inset); - Assert.Same(retained, Assert.Single(source.Children)); - Assert.Empty(attachments); - - patch.Apply(source); - var copy = Assert.IsType(source.Inset); - Assert.NotSame(branch, copy); - Assert.Same(copy, source.Anchor); - Assert.Same(retained, copy.Anchor); - Assert.Equal(new ArchiveNode?[] { retained, null, retained }, copy.Inset!.Trail); - Assert.Equal(new[] { true }, attachments); - Assert.Same(reference, branch.Anchor); - Assert.Same(reference, leaf.Trail[0]); - - patch.Undo(source); - Assert.Null(source.Inset); - Assert.Null(source.Anchor); - Assert.Same(retained, Assert.Single(source.Children)); - patch.Apply(source); - Assert.Same(copy, source.Inset); - Assert.Same(retained, copy.Anchor); - Assert.Same(retained, copy.Inset.Trail[0]); - } - - [Fact] - public void IgnoredEqualityFieldStillProducesAnEditInAnOwningOrderedSet() - { - var source = new Equality.EqualityContainer(); - var child = new Equality.EqualityNode { Name = "child", Note = "before" }; - source.Children.Add(child); - var desired = Equality.ModelSnapshot.Reflection.DeepCopy(source); - desired.Children[0].Note = "after"; - - Assert.True(Equality.ModelSnapshot.Reflection.ContentEquals(source, desired)); - var patch = Equality.ModelSnapshot.Reflection.Diff(source, desired); - var edit = Assert.Single(patch.Changes); - Assert.Equal("note", edit.PropertyName); - Assert.Same(child, edit.Object); - - patch.Apply(source); - Assert.Same(child, Assert.Single(source.Children)); - Assert.Equal("after", child.Note); - - patch.Undo(source); - Assert.Same(child, Assert.Single(source.Children)); - Assert.Equal("before", child.Note); - } -} diff --git a/conformance/csharp/ModelPatchImmutableTests.cs b/conformance/csharp/ModelPatchImmutableTests.cs deleted file mode 100644 index 65f7cd07..00000000 --- a/conformance/csharp/ModelPatchImmutableTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Eu.Mihosoft.Vmf.Conformance.Values; -using Vmf.Runtime; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class ModelPatchImmutableTests -{ - [Fact] - public void ImmutableDiffReplacesReferencesAndPreservesAliases() - { - var previous = new ValueLabel("previous"); - var selected = new ValueLabel("selected"); - var source = new ValueSelection { Current = previous, Second = previous }; - source.Selected.Add(previous); - var desired = new ValueSelection { Current = selected, Second = selected }; - desired.Selected.Add(selected); - - var patch = ModelSnapshot.Reflection.Diff(source, desired); - Assert.Equal(3, patch.Changes.Count); - Assert.All(patch.Changes, change => Assert.Same(source, change.Object)); - patch.Apply(source); - Assert.Same(selected, source.Current); - Assert.Same(selected, source.Second); - Assert.Same(selected, Assert.Single(source.Selected)); - - patch.Undo(source); - Assert.Same(previous, source.Current); - Assert.Same(previous, source.Second); - Assert.Same(previous, Assert.Single(source.Selected)); - - var sameContents = new ValueLabel("previous"); - Assert.Equal(previous, sameContents); - Assert.NotSame(previous, sameContents); - desired.Current = sameContents; - desired.Second = previous; - desired.Selected.Clear(); - desired.Selected.Add(previous); - - var converging = ModelSnapshot.Reflection.Diff(source, desired); - Assert.Equal("current", Assert.Single(converging.Changes).PropertyName); - converging.Apply(source); - Assert.Same(sameContents, source.Current); - Assert.Same(previous, source.Second); - - source.Current = new ValueLabel("previous"); - Assert.Throws(() => converging.Undo(source)); - } -} diff --git a/conformance/csharp/ModelPatchTests.cs b/conformance/csharp/ModelPatchTests.cs index cd2b5161..50a6ff2c 100644 --- a/conformance/csharp/ModelPatchTests.cs +++ b/conformance/csharp/ModelPatchTests.cs @@ -193,26 +193,6 @@ public void MapWritesRestoreCapturedKeyOrderAndKeepLiveStorage() Assert.Equal(["second", "first"], options.Keys); } - [Fact] - public void AddedBranchesKeepMapOrderEvenWhenTheMappingsMatchConstructorDefaults() - { - var child = new Defaults.ManagedSamples(); - child.Options.Clear(); - child.Options.Add("known", 11); - child.Options.Add("present", null); - var source = new Defaults.DefaultCollections(); - var desired = new Defaults.DefaultCollections { Mutable = child }; - var patch = Defaults.ModelSnapshot.Reflection.Diff(source, desired); - - patch.Apply(source); - - var imported = Assert.IsType(source.Mutable); - Assert.NotSame(child, imported); - Assert.Same(child, desired.Mutable); - Assert.Equal(["known", "present"], imported.Options.Keys); - Assert.Null(imported.Options["present"]); - } - [Fact] public void RejectsIndependentOrReadonlyRootsAndDetachedAffectedObjectsBeforeWriting() { @@ -276,35 +256,6 @@ public void OwningAndNonowningReferencesShareCanonicalCounterpartsAndUndo() Assert.Empty(source.Favorites); } - [Fact] - public void RedirectsOrdinaryReferencesWithoutRenamingOrDetachingTheOriginalChildren() - { - var source = Node("head"); - var left = Node("left"); - var right = Node("right"); - source.Children.Add(left); - source.Inset = right; - source.Anchor = left; - source.Trail.AddRange([left, null]); - var desired = Values.Reflection.DeepCopy(source); - desired.Anchor = desired.Inset; - desired.Trail[0] = desired.Inset; - desired.Trail.Add(desired.Inset); - - var patch = Values.Reflection.Diff(source, desired); - Assert.Equal(["anchor", "trail"], patch.Changes.Select(change => change.PropertyName)); - patch.Apply(source); - Assert.Same(left, Assert.Single(source.Children)); - Assert.Same(right, source.Inset); - Assert.Same(right, source.Anchor); - Assert.Equal(new ArchiveNode?[] { right, null, right }, source.Trail); - Assert.Equal("left", left.Name); - - patch.Undo(source); - Assert.Same(left, source.Anchor); - Assert.Equal(new ArchiveNode?[] { left, null }, source.Trail); - } - [Fact] public void NewBranchIsFullyOwnedBeforeTheRootAttachmentIsObserved() { @@ -478,31 +429,6 @@ public void RejectsAFaultyFactoryBeforeItCanRewriteAnUnmatchedSourceInstance() Assert.Equal("desired", desiredChild.Name); } - [Fact] - public void RemovingAnOwningSubtreeKeepsItsOriginalChildrenAvailableForUndo() - { - var source = Node("root"); - var holder = Node("holder"); - var child = Node("child"); - source.Inset = holder; - holder.Children.Add(child); - var desired = Values.Reflection.DeepCopy(source); - desired.Children.Add(desired.Inset!.Children[0]); - desired.Inset = null; - - var patch = Values.Reflection.Diff(source, desired); - patch.Apply(source); - Assert.Null(source.Inset); - Assert.NotSame(child, Assert.Single(source.Children)); - Assert.Same(child, Assert.Single(holder.Children)); - Assert.Same(holder, child.Parent); - - patch.Undo(source); - Assert.Empty(source.Children); - Assert.Same(holder, source.Inset); - Assert.Same(child, Assert.Single(holder.Children)); - } - [Fact] public void MatchesScalarAndReferenceKeyedChildrenBeforeComparingTheirFields() { @@ -538,77 +464,6 @@ public void MatchesScalarAndReferenceKeyedChildrenBeforeComparingTheirFields() Assert.Equal(1, product.Quantity); } - [Fact] - public void MergeKeepsDefaultsAndCopiesBothInputsWhileCombiningCollections() - { - var template = new DefaultSettings { Name = "template", Limit = 9, Note = "template note" }; - var overlay = new DefaultSettings(); - Assert.Equal("template", Values.Reflection.Merge(template, overlay).Name); - overlay.Name = null; - var explicitNull = Values.Reflection.Merge(template, overlay); - Assert.Null(explicitNull.Name); - Assert.Equal(9, explicitNull.Limit); - Assert.Equal("template note", explicitNull.Note); - - var first = new CollectionProfile(); - first.Options.Add("old", null); - first.Levels.Add(1.0); - first.Messages.Add("old"); - var second = new CollectionProfile(); - second.Options.Add("new", false); - second.Levels.Add(2.0); - second.Messages.Add("new"); - var collections = Values.Reflection.Merge(first, second); - Assert.Equal(["old", "new"], collections.Messages); - Assert.Equal([2.0], collections.Levels); - Assert.True(collections.Options.TryGetValue("new", out var value)); - Assert.Equal(false, value); - Assert.Single(collections.Options); - Assert.True(Values.Reflection.Merge(first, new CollectionProfile()).Options.ContainsKey("old")); - - var archive = Node("template"); - var added = Node("overlay"); - var child = Node("child"); - added.Children.Add(child); - added.Anchor = child; - child.Anchor = added; - var combined = Values.Reflection.Merge(archive, added); - var copied = Assert.Single(combined.Children); - Assert.NotSame(child, copied); - Assert.Same(copied, combined.Anchor); - Assert.Same(combined, copied.Anchor); - Assert.Same(child, Assert.Single(added.Children)); - Assert.Empty(archive.Children); - } - - [Fact] - public void MergeAppliesEditsToAnIndependentReadOnlyTemplateProjection() - { - var template = Node("template"); - var originalChild = Node("child"); - template.Children.Add(originalChild); - template.Anchor = originalChild; - originalChild.Anchor = template; - var overlay = Node("edited"); - var view = template.AsReadOnly(); - - var merged = Values.Reflection.Merge(view, overlay.AsReadOnly()); - Assert.NotSame(view, merged); - Assert.Equal("edited", merged.Name); - var child = Assert.Single(merged.Children); - Assert.NotSame(originalChild.AsReadOnly(), child); - Assert.Same(child, merged.Anchor); - Assert.Same(merged, child!.Anchor); - Assert.Same(merged, child.Parent); - var field = Values.Reflection.Reflect(merged).FindProperty("name")!; - Assert.False(field.CanWrite); - Assert.Throws(() => field.Set("not allowed")); - Assert.Equal("template", template.Name); - Assert.Same(originalChild, Assert.Single(template.Children)); - Assert.Same(template, originalChild.Anchor); - Assert.Equal("edited", overlay.Name); - } - [Fact] public void MergeRebindsOverlayRootReferencesInDirectAndOwnedFields() { diff --git a/conformance/csharp/ModelPatchUndoIdentityTests.cs b/conformance/csharp/ModelPatchUndoIdentityTests.cs index b6606060..b894bbc7 100644 --- a/conformance/csharp/ModelPatchUndoIdentityTests.cs +++ b/conformance/csharp/ModelPatchUndoIdentityTests.cs @@ -19,29 +19,6 @@ public void SingularModelUndoRejectsEqualContentReplacements() CheckLink(owner, ownerDesired, () => owner.Child, value => owner.Child = value, "child"); } - [Fact] - public void ScalarAndExternalUndoAcceptEqualValues() - { - var text = new EqualityNode { Name = "before" }; - var scalarPatch = ModelSnapshot.Reflection.Diff(text, new EqualityNode { Name = "after" }); - scalarPatch.Apply(text); - string assigned = text.Name!; - text.Name = "other"; - text.Name = new string(assigned.ToCharArray()); - Assert.NotSame(assigned, text.Name); - scalarPatch.Undo(text); - Assert.Equal("before", text.Name); - - var external = new External.ExternalValueEntry(); - string id = "8df6dcb5-21de-42b4-868e-e4e4032eddc5"; - var externalPatch = External.ModelSnapshot.Reflection.Diff(external, new External.ExternalValueEntry { SourceId = Guid.Parse(id) }); - externalPatch.Apply(external); - external.SourceId = null; - external.SourceId = Guid.Parse(id); - externalPatch.Undo(external); - Assert.Null(external.SourceId); - } - private static void CheckLink(object source, object desired, Func current, Action replace, string property) { diff --git a/conformance/csharp/ModelTypeCatalogTests.cs b/conformance/csharp/ModelTypeCatalogTests.cs index 07759c63..0e122242 100644 --- a/conformance/csharp/ModelTypeCatalogTests.cs +++ b/conformance/csharp/ModelTypeCatalogTests.cs @@ -8,26 +8,6 @@ namespace Vmf.CSharp.Conformance; public class ModelTypeCatalogTests { - [Fact] - public void InspectEffectiveFieldsWithoutCreatingAnInstance() - { - var catalog = Values.ModelSnapshot.TypeCatalog; - var type = catalog.Find(typeof(Values.DefaultSettings))!; - Assert.Equal("eu.mihosoft.vmf.conformance.values.DefaultSettings", type.Name); - Assert.Equal(new[] { "baseline", "entries", "flag", "limit", "mode", "name", "note", "ratio", "sequence", - "stages", "unsetValue" }, type.Properties.Select(field => field.Name)); - var name = type.FindProperty("name")!; - Assert.EndsWith(".DefaultBase", name.DeclaringType, StringComparison.Ordinal); - Assert.Equal("display_name", name.WireName); - Assert.Equal("idle\nready", name.DeclaredDefault?.GetString()); - Assert.Equal(new[] { "label", "text" }, name.Annotations.Where(annotation => annotation.Key == "role") - .Select(annotation => annotation.Value)); - var inventory = catalog.Find(typeof(Values.KeyedInventory))!; - Assert.Equal("sku", inventory.FindProperty("products")?.KeyPropertyName); - Assert.Null(catalog.Find(typeof(Values.ArchiveNode))!.FindProperty("parent")?.WireName); - Assert.True(catalog.Find(typeof(Values.ValueLabel))!.IsImmutable); - Assert.Same(type, catalog.TypeOf(new Values.DefaultSettings().AsReadOnly())); - } [Fact] public void GenericApplicationsSubstituteThroughIntermediateTypes() @@ -47,20 +27,4 @@ public void GenericApplicationsSubstituteThroughIntermediateTypes() Assert.False(catalog.IsSubtypeOf(longs.Declaration, closedRoot)); Assert.False(catalog.IsSubtypeOf(closedRoot, root.Declaration)); } - - [Fact] - public void SecondaryTraitsAndAClosedDiamondShareTheSameDeclarations() - { - var catalog = Hierarchy.ModelSnapshot.TypeCatalog; - var diamond = catalog.Find(typeof(Hierarchy.PartsCatalog))!; - var root = catalog.Find(typeof(Hierarchy.PartGroup<>))!; - var part = catalog.Find(typeof(Hierarchy.ConcretePart))!; - var closedRoot = new ModelTypeUse(ModelValueKind.Model, root.Name, arguments: [part.Declaration]); - Assert.True(catalog.IsSubtypeOf(diamond.Declaration, closedRoot)); - Assert.Equal(2, diamond.DirectSupertypes.Count); - Assert.Single(diamond.Properties, property => property.Name == "parts"); - Assert.Equal(part.Name, diamond.FindProperty("parts")?.ValueType.Name); - Assert.Contains(catalog.TypesAssignableTo(typeof(Hierarchy.IRatedItem)), - type => type.RuntimeType == typeof(Hierarchy.CatalogItem)); - } } diff --git a/conformance/csharp/ModelVersionTests.cs b/conformance/csharp/ModelVersionTests.cs index 32d2f6ad..5f6f9c43 100644 --- a/conformance/csharp/ModelVersionTests.cs +++ b/conformance/csharp/ModelVersionTests.cs @@ -57,50 +57,6 @@ public void RecordingAndManualVersioningShareACounterWithoutSharingHistoryLifeti changes.Stop(); } - [Fact] - public void VersionTakesTheTimestampAtItsOwnListenerTurnDuringReentrantDelivery() - { - var model = new EqualityContainer { Name = "initial" }; - var changes = model.VmfChanges; - var observations = new List(); - using var earlier = changes.AddRecursiveListener(change => - { - observations.Add($"before-{change.NewValue}={changes.ModelVersion.VersionNumber}"); - if (Equals("outer", change.NewValue)) model.Name = "nested"; - }); - changes.Start(); - using var later = changes.AddRecursiveListener(change => - { - Assert.Equal(change.Timestamp, changes.ModelVersion.Timestamp); - observations.Add($"after-{change.NewValue}={changes.ModelVersion.VersionNumber}"); - }); - model.Name = "outer"; - Assert.Equal(["before-outer=0", "before-nested=0", "after-nested=1", "after-outer=2"], observations); - Assert.Equal(changes.History[0].Timestamp, changes.ModelVersion.Timestamp); - Assert.True(changes.History[0].Timestamp < changes.History[1].Timestamp); - changes.Stop(); - } - - [Fact] - public void VersioningFollowsContainmentAndContinuesWhenAnEarlierObserverThrows() - { - var child = new ArchiveNode { Name = "owned" }; - var archive = new ArchiveRoot { Head = child }; - var changes = archive.VmfChanges; - var failure = new InvalidOperationException("listener failure"); - using var failing = changes.AddPropertyListener("name", _ => throw failure, ModelChangeScope.Recursive); - changes.EnableModelVersioning(); - Assert.Same(failure, Assert.Throws(() => child.Name = "owned edit")); - Assert.Equal(1, changes.ModelVersion.VersionNumber); - var detached = new ArchiveNode { Name = "outside" }; - child.Anchor = detached; - Assert.Equal(2, changes.ModelVersion.VersionNumber); - detached.Name = "external edit"; - Assert.Equal(2, changes.ModelVersion.VersionNumber); - Assert.Empty(changes.History); - changes.DisableModelVersioning(); - } - [Fact] public void ReadOnlyViewHasIndependentHistoryWithProjectedSourceAndModelPayloads() { @@ -148,27 +104,6 @@ public void ReadOnlyViewHasIndependentHistoryWithProjectedSourceAndModelPayloads Assert.False(changes.IsModelVersioningEnabled); } - [Fact] - public void ReadOnlyInverseChangesAdvanceVersionWithoutEnteringHistory() - { - var station = new Station(); - var view = station.AsReadOnly(); - var changes = view.VmfChanges; - var workshop = new Workshop(); - var seen = new List(); - using var subscription = changes.AddPropertyListener("workshop", seen.Add); - changes.Start(); - workshop.Stations.Add(station); - workshop.Stations.Remove(station); - Assert.Equal(2, changes.ModelVersion.VersionNumber); - Assert.Empty(changes.History); - Assert.Equal(2, seen.Count); - Assert.All(seen, change => Assert.Same(view, change.Source)); - Assert.Same(workshop.AsReadOnly(), seen[0].NewValue); - Assert.Same(workshop.AsReadOnly(), seen[1].OldValue); - changes.Stop(); - } - [Fact] public void GetterOnlyTraitAndImmutableModelsUseTheSafeViewWithoutExposingMutableHistory() { diff --git a/conformance/csharp/NamedRoleContainmentTests.cs b/conformance/csharp/NamedRoleContainmentTests.cs index f9abc7b8..f4e7f12d 100644 --- a/conformance/csharp/NamedRoleContainmentTests.cs +++ b/conformance/csharp/NamedRoleContainmentTests.cs @@ -5,41 +5,6 @@ namespace Vmf.CSharp.Conformance; public sealed class NamedRoleContainmentTests { - [Fact] - public void NamedInversesTransferTheSameMutableRoleBetweenAllOwnershipShapes() - { - var left = new NamedRoleFolder(); - var right = new NamedRoleFolder(); - var note = NamedOwnedNote.NewBuilder().WithLabel("note").Build(); - var task = NamedOwnedTask.NewBuilder().WithTaskNumber(71).Build(); - left.Single = note; - Assert.Same(left, note.SingleOwner); - Assert.Same(left.AsReadOnly(), left.AsReadOnly().Single!.SingleOwner); - - note.OrderedOwner = right; - Assert.Null(left.Single); - Assert.Null(note.SingleOwner); - Assert.Same(note, Assert.Single(right.Ordered)); - - right.Ordinary.Add(note); - Assert.Empty(right.Ordered); - Assert.Null(note.OrderedOwner); - Assert.Same(right, note.OrdinaryOwner); - - note.UnorderedOwner = left; - Assert.Empty(right.Ordinary); - Assert.Null(note.OrdinaryOwner); - Assert.Same(left, note.UnorderedOwner); - Assert.True(left.Unordered.Contains(note.AsReadOnly())); - - task.SingleOwner = right; - Assert.Same(task, right.Single); - Assert.Same(right, task.SingleOwner); - task.SingleOwner = null; - Assert.Null(right.Single); - note.UnorderedOwner = null; - Assert.Empty(left.Unordered); - } [Theory] [InlineData("json", false)] diff --git a/conformance/csharp/NativePropertyChangedTests.cs b/conformance/csharp/NativePropertyChangedTests.cs index 0cb428e0..f8f8cc3f 100644 --- a/conformance/csharp/NativePropertyChangedTests.cs +++ b/conformance/csharp/NativePropertyChangedTests.cs @@ -8,31 +8,6 @@ namespace Vmf.CSharp.Conformance; public sealed class NativePropertyChangedTests { - [Fact] - public void NativeAndProjectedEventsUseThePublicNameAndTheirOwnSender() - { - var model = new Partner(); - var view = model.AsReadOnly(); - var writable = (INotifyPropertyChanged)model; - var projected = (INotifyPropertyChanged)view; - var actual = new List(); - var readOnly = new List(); - writable.PropertyChanged += (sender, args) => - { - Assert.Same(model, sender); - actual.Add(args.PropertyName); - }; - projected.PropertyChanged += (sender, args) => - { - Assert.Same(view, sender); - readOnly.Add(args.PropertyName); - }; - model.PartnerReference = new Partner(); - model.Name = "new"; - - Assert.Equal([nameof(Partner.PartnerReference), nameof(Partner.Name)], actual); - Assert.Equal(actual, readOnly); - } [Fact] public void InheritedRoleMembersReportTheClrNameInsteadOfTheWireAlias() @@ -101,22 +76,4 @@ public void CombinedDuplicateHandlersUseClrRemovalAndReleaseTheirRawRelay() model.Children[0]!.Name = "recursive only"; Assert.Empty(trace); } - - [Fact] - public void MulticastDispatchKeepsTheInvocationSnapshot() - { - var model = new ArchiveNode(); - var notifier = (INotifyPropertyChanged)model; - var trace = new List(); - PropertyChangedEventHandler later = (_, _) => trace.Add("later"); - notifier.PropertyChanged += (_, _) => - { - trace.Add("first"); - notifier.PropertyChanged -= later; - }; - notifier.PropertyChanged += later; - model.Name = "one"; - model.Name = "two"; - Assert.Equal(["first", "later", "first"], trace); - } } diff --git a/conformance/csharp/ObservationTests.cs b/conformance/csharp/ObservationTests.cs index 2dfe4966..7f3e49b2 100644 --- a/conformance/csharp/ObservationTests.cs +++ b/conformance/csharp/ObservationTests.cs @@ -147,138 +147,6 @@ private static void VerifyHistoryPositions(ScalarSample sample, I stop(); } - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ClearingHistoryRemovesTransactionsAfterHistoryObserversRun(bool readOnly) - { - var sample = new ScalarSample(); - if (readOnly) - { - var changes = sample.AsReadOnly().VmfChanges; - VerifyReentrantHistoryClear(sample, changes.History, changes.Transactions, changes.Start, changes.Stop, - changes.Clear, () => changes.PublishTransaction()); - } - else - { - var changes = sample.VmfChanges; - VerifyReentrantHistoryClear(sample, changes.History, changes.Transactions, changes.Start, changes.Stop, - changes.Clear, () => changes.PublishTransaction()); - } - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ThrowingHistoryObserverLeavesTransactionsForTheNextClear(bool readOnly) - { - var sample = new ScalarSample(); - if (readOnly) - { - var changes = sample.AsReadOnly().VmfChanges; - VerifyFailedHistoryClear(sample, changes.History, changes.Transactions, changes.Start, changes.Stop, - changes.Clear, () => changes.PublishTransaction()); - } - else - { - var changes = sample.VmfChanges; - VerifyFailedHistoryClear(sample, changes.History, changes.Transactions, changes.Start, changes.Stop, - changes.Clear, () => changes.PublishTransaction()); - } - } - - private static void VerifyReentrantHistoryClear(ScalarSample sample, ModelHistory history, - ModelHistory transactions, Action start, Action stop, Action clear, Action publish) - { - start(); - sample.Description = "old group"; - publish(); - - var observed = new List(); - using var historyListener = history.AddListener(change => - { - if (change.Removed.Count == 0) return; - observed.Add($"clear edits:{history.Count}/{transactions.Count}"); - sample.OptionalInt = 88; - publish(); - }); - using var transactionListener = transactions.AddListener(change => - { - observed.Add($"groups:+{change.Added.Count}/-{change.Removed.Count}; current={transactions.Count}"); - }); - - clear(); - Assert.Equal(["clear edits:0/1", "groups:+1/-0; current=2", "groups:+0/-2; current=0"], observed); - Assert.Single(history); - Assert.Empty(transactions); - Assert.Equal(88, sample.OptionalInt); - stop(); - Assert.Empty(transactions); - } - - private static void VerifyFailedHistoryClear(ScalarSample sample, ModelHistory history, - ModelHistory transactions, Action start, Action stop, Action clear, Action publish) - { - start(); - sample.Description = "old group"; - publish(); - - int removedGroups = 0; - using var transactionListener = transactions.AddListener(change => removedGroups += change.Removed.Count); - var failure = new InvalidOperationException("history listener"); - using (history.AddListener(change => { if (change.Removed.Count > 0) throw failure; })) - { - Assert.Same(failure, Assert.Throws(clear)); - } - Assert.Empty(history); - Assert.Single(transactions); - Assert.Equal(0, removedGroups); - Assert.Equal("old group", sample.Description); - - clear(); - Assert.Empty(transactions); - Assert.Equal(1, removedGroups); - stop(); - } - - [Fact] - public void ScalarListenersFollowCurrentContainmentAndTheirScope() - { - var root = new ArchiveNode(); - var child = new ArchiveNode(); - var external = new ArchiveNode(); - root.Children.Add(child); - root.Trail.Add(external); - - var local = new List(); - var names = new List(); - var filtered = new List(); - using var watchLocal = root.VmfChanges.AddLocalListener(change => - { - if (change.PropertyName == "name") local.Add(change.NewValue as string); - }); - using var watchNames = root.VmfChanges.AddPropertyListener("name", change => names.Add(change.NewValue as string), - ModelChangeScope.Recursive); - using var watchFiltered = root.VmfChanges.AddFilteredListener( - change => ReferenceEquals(change.Source, child) && change.NewValue is "reattached", - change => filtered.Add(change.NewValue as string), ModelChangeScope.Recursive); - - root.Name = "root"; - child.Name = "attached"; - child.Name = "attached"; - external.Name = "external"; - root.Children.Remove(child); - child.Name = "detached"; - root.Inset = child; - child.Name = "reattached"; - watchNames.Dispose(); - child.Name = "unsubscribed"; - - Assert.Equal(["root"], local); - Assert.Equal(["root", "attached", "reattached"], names); - Assert.Equal(["reattached"], filtered); - } - [Fact] public void ModelReferencesEmitWhenAnEqualValuedInstanceIsReplaced() { @@ -304,31 +172,6 @@ public void ModelReferencesEmitWhenAnEqualValuedInstanceIsReplaced() Assert.ThrowsAny(() => change.Apply(new ValueSelection())); } - [Fact] - public void InheritedGenericPropertyUsesTheConcreteObjectsStream() - { - var catalog = new Catalog(); - Shelf shelf = catalog; - var thermometer = new Thermometer { Sku = "T-1", Unit = "C" }; - shelf.Products.Add(thermometer); - Assert.Same(shelf.VmfChanges, catalog.VmfChanges); - var local = new List(); - var recursive = new List(); - using var watchLocal = shelf.VmfChanges.AddLocalListener(local.Add); - using var watchRecursive = catalog.VmfChanges.AddRecursiveListener(recursive.Add); - - shelf.Featured = thermometer; - thermometer.Unit = "K"; - var reference = Assert.Single(local); - Assert.Equal("featured", reference.PropertyName); - Assert.Same(catalog, reference.Source); - Assert.Same(thermometer, reference.NewValue); - Assert.Equal(2, recursive.Count); - Assert.Same(reference, recursive[0]); - Assert.Equal("unit", recursive[1].PropertyName); - Assert.Same(thermometer, recursive[1].Source); - } - [Fact] public void PrimitiveAndBoxedFloatSettersRetainJavaNoOpRules() { @@ -413,123 +256,6 @@ public void ReentrantScalarEditsDeliverDepthFirstAndRetainUndoOrder() Assert.Equal(2, group.Changes.Count); } - [Fact] - public void DirectReferenceHistoryRecordsInitiatingEditBeforeNestedEdit() - { - var selection = new ValueSelection(); - var first = new ValueLabel("first"); - var second = new ValueLabel("second"); - var changes = selection.VmfChanges; - var delivered = new List(); - using var initiating = changes.AddLocalListener(change => - { - delivered.Add("first " + change.PropertyName); - if (change.PropertyName == "current") - { - selection.Second = second; - Assert.Equal("second", Assert.Single(changes.History).PropertyName); - } - }); - using var following = changes.AddLocalListener(change => delivered.Add("second " + change.PropertyName)); - - changes.Start(); - selection.Current = first; - changes.Stop(); - Assert.Equal(["first current", "first second", "second second", "second current"], delivered); - // The triggering edit is recorded before the edits its listeners made (portable contract H4). - Assert.Equal(["current", "second"], changes.History.Select(change => change.PropertyName)); - Assert.True(changes.History[0].Timestamp < changes.History[1].Timestamp); - } - - [Fact] - public void ThrowingListenerDoesNotSkipDeliveryOrUndoAppliedEdit() - { - var root = new ArchiveNode(); - var changes = root.VmfChanges; - var expected = new InvalidOperationException("listener failure"); - var later = new ArgumentException("second listener failure"); - var observed = new List(); - using var throwing = changes.AddLocalListener(_ => throw expected); - using var secondThrowing = changes.AddLocalListener(_ => throw later); - using var watch = changes.AddLocalListener(observed.Add); - - changes.Start(); - var actual = Assert.Throws(() => root.Name = "applied"); - Assert.Same(expected, actual); - Assert.Equal("applied", root.Name); - Assert.Same(Assert.Single(changes.History), Assert.Single(observed)); - Assert.Same(later, Assert.Single(ModelChanges.GetSuppressedObserverExceptions(actual))); - throwing.Dispose(); - secondThrowing.Dispose(); - root.Name = "next"; - changes.Stop(); - Assert.Equal(["applied", "next"], Assert.Single(changes.Transactions).Changes.Select(c => c.NewValue as string)); - } - - [Fact] - public void NestedPublicationCommitsEachRangeExactlyOnce() - { - var model = new ArchiveNode(); - var changes = model.VmfChanges; - var delivered = new List(); - changes.Start(); - using var first = changes.Transactions.AddListener(update => - { - Assert.Same(changes.Transactions, update.Source); - string? name = Assert.Single(Assert.Single(update.Added).Changes).NewValue as string; - delivered.Add("first " + name); - if (name == "outer") - { - Assert.Null(changes.PublishTransaction()); - model.Name = "nested"; - Assert.NotNull(changes.PublishTransaction()); - model.Name = "next"; - } - }); - using var second = changes.Transactions.AddListener(update => - delivered.Add("second " + Assert.Single(Assert.Single(update.Added).Changes).NewValue)); - - model.Name = "outer"; - changes.PublishTransaction(); - Assert.Equal(["first outer", "first nested", "second nested", "second outer"], delivered); - changes.PublishTransaction(); - changes.Stop(); - Assert.Equal(["first outer", "first nested", "second nested", "second outer", "first next", "second next"], delivered); - Assert.Equal(["outer", "nested", "next"], changes.Transactions.Select(group => group.Changes[0].NewValue as string)); - Assert.False(changes.IsRecording); - } - - [Fact] - public void ADispatchUsesTheListenersRegisteredWhenItStarted() - { - var model = new ArchiveNode(); - var changes = model.VmfChanges; - var notifications = new List(); - IDisposable? second = null; - IDisposable? late = null; - using var first = changes.AddLocalListener(change => - { - notifications.Add("first " + change.NewValue); - if (change.NewValue is "initial") - { - second?.Dispose(); - late = changes.AddLocalListener(next => notifications.Add("late " + next.NewValue)); - } - }); - try - { - second = changes.AddLocalListener(change => notifications.Add("second " + change.NewValue)); - model.Name = "initial"; - model.Name = "next"; - Assert.Equal(["first initial", "second initial", "first next", "late next"], notifications); - } - finally - { - second?.Dispose(); - late?.Dispose(); - } - } - [Fact] public void FailedStopStillClosesRecordingAndRetainsPublishedTransaction() { diff --git a/conformance/csharp/ObserverOrderTests.cs b/conformance/csharp/ObserverOrderTests.cs index d089a543..72ead0e8 100644 --- a/conformance/csharp/ObserverOrderTests.cs +++ b/conformance/csharp/ObserverOrderTests.cs @@ -8,207 +8,6 @@ namespace Vmf.CSharp.Conformance; public class ObserverOrderTests { - [Theory] - [InlineData(true, true)] - [InlineData(false, true)] - [InlineData(true, false)] - [InlineData(false, false)] - public void ChangedObjectListenersPrecedeAncestorsWhateverTheRegistrationOrder(bool ancestorFirst, bool attachedFirst) - { - var root = new ArchiveNode(); - var child = new ArchiveNode(); - if (attachedFirst) root.Children.Add(child); - var trace = new List(); - using var first = ancestorFirst ? SubscribeToAncestor() : SubscribeToChild(); - using var second = ancestorFirst ? SubscribeToChild() : SubscribeToAncestor(); - if (!attachedFirst) root.Children.Add(child); - - // The changed object's listeners come first, then its ancestors' (portable contract E8), whatever the order - // in which they were added. - string[] expected = ["child", "root"]; - child.Name = "edit"; - Assert.Equal(expected, trace); - trace.Clear(); - child.Trail.Add(new ArchiveNode()); - Assert.Equal(expected, trace); - - IDisposable SubscribeToAncestor() => root.VmfChanges.AddFilteredListener(IsObserved, _ => trace.Add("root"), - ModelChangeScope.Recursive); - IDisposable SubscribeToChild() => child.VmfChanges.AddFilteredListener(IsObserved, _ => trace.Add("child")); - static bool IsObserved(ModelChange change) => change.PropertyName is "name" or "trail"; - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void ListenersOfOneObjectRunInRegistrationOrderAcrossScopes(bool localFirst) - { - var root = new ArchiveNode(); - var trace = new List(); - using var first = Add(localFirst, 1); - using var second = Add(!localFirst, 1); - using var third = Add(localFirst, 2); - using var fourth = Add(!localFirst, 2); - - root.Name = "edit"; - - // The listeners of one object run in the order they were added, local or recursive (portable contract E7). - string[] expected = localFirst - ? ["local 1", "recursive 1", "local 2", "recursive 2"] - : ["recursive 1", "local 1", "recursive 2", "local 2"]; - Assert.Equal(expected, trace); - - IDisposable Add(bool local, int index) => root.VmfChanges.AddListener( - _ => trace.Add($"{(local ? "local" : "recursive")} {index}"), - local ? ModelChangeScope.Local : ModelChangeScope.Recursive); - } - - [Theory] - [InlineData(false, false)] - [InlineData(true, false)] - [InlineData(true, true)] - public void LaterGroupReadsSubscriptionsAtItsTurn(bool initiallyActive, bool replaceOld) - { - var root = new ArchiveNode(); - var child = new ArchiveNode(); - root.Children.Add(child); - var trace = new List(); - IDisposable? late = null; - IDisposable? old = null; - using var ancestor = ObserveName(root, "root", trace, value => - { - if (value != "outer") return; - if (replaceOld) old!.Dispose(); - late = child.VmfChanges.AddLocalListener(change => trace.Add($"late {change.NewValue}")); - child.Name = "nested"; - }); - using var oldRegistration = old = initiallyActive - ? child.VmfChanges.AddLocalListener(change => trace.Add($"old {change.NewValue}")) - : null; - - try - { - child.Name = "outer"; - child.Name = "again"; - - // The child's listeners run before the root's (portable contract E8); an edit made by a listener is - // delivered at once (E9); a listener added during a delivery misses the change being delivered. - string[] expected = (initiallyActive, replaceOld) switch - { - (false, false) => ["root outer", "late nested", "root nested", "late again", "root again"], - (true, false) => ["old outer", "root outer", "old nested", "late nested", "root nested", "old again", - "late again", "root again"], - _ => ["old outer", "root outer", "late nested", "root nested", "late again", "root again"], - }; - Assert.Equal(expected, trace); - } - finally - { - late?.Dispose(); - } - } - - [Fact] - public void ReparentingReattachesRecursiveGroupsInTheirNewOrder() - { - var root = new ArchiveNode(); - var left = new ArchiveNode(); - var right = new ArchiveNode(); - var child = new ArchiveNode(); - root.Children.AddRange([left, right]); - left.Children.Add(child); - var trace = new List(); - using var rootNames = ObserveName(root, "root", trace); - using var leftNames = ObserveName(left, "left", trace); - using var rightNames = ObserveName(right, "right", trace); - using var childName = child.VmfChanges.AddPropertyListener("name", change => trace.Add($"child {change.NewValue}")); - using var destinationList = right.VmfChanges.AddPropertyListener("children", _ => child.Name = "during"); - - child.Name = "before"; - right.Children.Add(child); - child.Name = "after"; - - // The changed object's listeners come first, then its ancestors' (portable contract E8). Whether the new - // ancestors already observe an edit that a listener makes while the move is delivered is still open: - // compare without their "during" entries. - trace.RemoveAll(entry => entry is "root during" or "right during"); - Assert.Equal(["child before", "left before", "root before", "child during", "child after", "right after", - "root after"], trace); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ListAndSlotCaptureGroupsAtTheirOwnDispatchBoundary(bool singular) - { - var owner = new ArchiveNode(); - var child = new ArchiveNode(); - string ownerProperty = singular ? "inset" : "children"; - string inverseProperty = singular ? "insetOf" : "parent"; - var trace = new List(); - IDisposable? ownerEdits = null; - IDisposable? childNames = null; - using var inverse = child.VmfChanges.AddPropertyListener(inverseProperty, change => - { - if (!ReferenceEquals(change.NewValue, owner)) return; - trace.Add("inverse delivered"); - ownerEdits = owner.VmfChanges.AddPropertyListener(ownerProperty, _ => trace.Add("owner delivered")); - childNames = ObserveName(owner, "name", trace); - child.Name = "inverse"; - }); - - try - { - if (singular) owner.Inset = child; - else owner.Children.Add(child); - child.Name = "after"; - if (!singular) owner.Children.Remove(child); - - string[] expected = singular - ? ["inverse delivered", "owner delivered", "name after"] - : ["inverse delivered", "name inverse", "name after", "owner delivered"]; - Assert.Equal(expected, trace); - } - finally - { - ownerEdits?.Dispose(); - childNames?.Dispose(); - } - } - - [Fact] - public void ReentrantCrossScopeCallbacksRecordTheTriggeringEditFirst() - { - var root = new ArchiveNode { Name = "root" }; - var child = new ArchiveNode { Name = "initial" }; - root.Children.Add(child); - string checkpoint = ModelSnapshot.Write(root); - var trace = new List(); - using var local = child.VmfChanges.AddPropertyListener("name", change => - { - trace.Add($"child {change.NewValue}"); - if (change.NewValue is "outer") child.Name = "nested"; - }); - var binding = new JournalBinding("conformance.observer-order", 1, - model => (model as ArchiveNode)?.Parent is null ? "root" : "child"); - using var recorder = JournalRecorder.Start(root, ModelSnapshot.Registry, binding, "initial", 0); - using var ancestor = ObserveName(root, "root", trace); - - child.Name = "outer"; - var history = root.VmfChanges.History; - Assert.Equal(["child outer", "child nested", "root nested", "root outer"], trace); - // The triggering edit is recorded before the edits its listeners made (portable contract H4). - Assert.Equal(["outer", "nested"], history.Select(change => change.NewValue)); - var journal = JournalJson.Read(JournalJson.Write(recorder.Finish())); - var operations = Assert.Single(journal.Transactions).Operations.Cast().ToArray(); - Assert.Equal([("initial", "outer"), ("outer", "nested")], - operations.Select(edit => (edit.Before.Text, edit.After.Text))); - - var fresh = ModelSnapshot.Read(checkpoint); - var replayed = JournalReplayer.Replay(fresh, binding, "initial", journal, ModelSnapshot.Registry); - Assert.Equal("initial", Assert.Single(fresh.Children).Name); - Assert.Equal("nested", Assert.Single(replayed.Children).Name); - } public enum RecordingAction { Start, Stop, Restart, Clear } @@ -272,117 +71,6 @@ void ChangeRecording(ModelChange change) .Select(change => Assert.IsType(change.NewValue)).Order(StringComparer.Ordinal)); } - [Fact] - public void RestartInsideTheFirstOfTwoRelaysDoesNotRecordTheOuterEditAgain() - { - var node = new ArchiveNode { Name = "initial" }; - var recording = node.VmfChanges; - using var local = recording.AddLocalListener(change => - { - if (change.NewValue is not "outer") return; - ApplyRecordingAction(recording, RecordingAction.Restart); - node.Name = "nested"; - Assert.Empty(recording.History); - }); - using var recursive = recording.AddRecursiveListener(_ => { }); - recording.Start(); - node.Name = "outer"; - Assert.Equal(["nested"], RecordedValues(recording)); - recording.Stop(); - } - - [Fact] - public void StartingAPortableRecorderInACallbackKeepsItsPostCommitCheckpoint() - { - var root = new ArchiveNode { Name = "root" }; - var child = new ArchiveNode { Name = "initial" }; - root.Children.Add(child); - var binding = new JournalBinding("conformance.observer-order", 1, - model => ((ArchiveNode)model).Parent is null ? "root" : "child"); - JournalRecorder? late = null; - string? checkpoint = null; - using var local = child.VmfChanges.AddPropertyListener("name", change => - { - if (change.NewValue is not "outer") return; - checkpoint = ModelSnapshot.Write(root); - late = JournalRecorder.Start(root, ModelSnapshot.Registry, binding, "after-outer", 0); - child.Name = "nested"; - }); - using var ancestor = root.VmfChanges.AddRecursiveListener(_ => { }); - - child.Name = "outer"; - - using var recorder = Assert.IsType>(late); - Assert.Equal(["nested"], RecordedValues(root.VmfChanges)); - var journal = JournalJson.Read(JournalJson.Write(recorder.Finish())); - var edit = Assert.IsType(Assert.Single(Assert.Single(journal.Transactions).Operations)); - Assert.Equal(("outer", "nested"), (edit.Before.Text, edit.After.Text)); - var fresh = ModelSnapshot.Read(Assert.IsType(checkpoint)); - var replayed = JournalReplayer.Replay(fresh, binding, "after-outer", journal, ModelSnapshot.Registry); - Assert.Equal("outer", Assert.Single(fresh.Children).Name); - Assert.Equal("nested", Assert.Single(replayed.Children).Name); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void StartingAPortableRecorderInAModelPropertyCallbackKeepsItsPostCommitCheckpoint(bool owning) - { - var root = new ArchiveNode { Name = "root" }; - var editor = new ArchiveNode { Name = "editor" }; - var outer = new ArchiveNode { Name = "outer" }; - var nested = new ArchiveNode { Name = "nested" }; - var property = owning ? "inset" : "anchor"; - root.Children.AddRange(owning ? [editor, nested] : [editor, outer, nested]); - var binding = new JournalBinding("conformance.observer.reference-start", 1, model => ((ArchiveNode)model).Name!); - JournalRecorder? late = null; - string? checkpoint = null; - using var local = editor.VmfChanges.AddPropertyListener(property, change => - { - if (!ReferenceEquals(change.NewValue, outer)) return; - checkpoint = ModelSnapshot.Write(root); - late = JournalRecorder.Start(root, ModelSnapshot.Registry, binding, "after-outer", 0); - editor.Anchor = nested; - }); - var live = new List(); - using var ancestor = root.VmfChanges.AddPropertyListener(property, change => live.Add(change.NewValue), - ModelChangeScope.Recursive); - - if (owning) editor.Inset = outer; - else editor.Anchor = outer; - using var recorder = Assert.IsType>(late); - Assert.Equal(owning ? new[] { outer } : [nested, outer], live); - Assert.Same(nested, Assert.Single(root.VmfChanges.History).NewValue); - var journal = recorder.Finish(); - var formats = new (Func Write, Func Read)[] - { - (JournalJson.Write, JournalJson.Read), - (JournalYaml.Write, JournalYaml.Read), - (JournalXml.Write, JournalXml.Read), - }; - foreach (var (write, read) in formats) - { - var restored = read(write(journal)); - Assert.Equal(1, restored.WireVersion); - var edit = Assert.IsType(Assert.Single(Assert.Single(restored.Transactions).Operations)); - Assert.Equal("anchor", edit.Property); - Assert.Equal(owning ? ("NULL", null) : ("REFERENCE", "outer"), (edit.Before.Kind, edit.Before.Text)); - Assert.Equal(("REFERENCE", "nested"), (edit.After.Kind, edit.After.Text)); - var fresh = ModelSnapshot.Read(Assert.IsType(checkpoint)); - var replayed = JournalReplayer.Replay(fresh, binding, "after-outer", restored, ModelSnapshot.Registry); - var freshEditor = fresh.Children[0]; - var replayEditor = replayed.Children[0]; - if (owning) - { - Assert.Null(freshEditor.Anchor); - Assert.Same(freshEditor, Assert.IsType(freshEditor.Inset).InsetOf); - Assert.Same(replayEditor, Assert.IsType(replayEditor.Inset).InsetOf); - } - else Assert.Same(fresh.Children[1], freshEditor.Anchor); - Assert.Same(replayed.Children[owning ? 1 : 2], replayEditor.Anchor); - } - } - private static void ApplyRecordingAction(ModelChanges recording, RecordingAction action) { switch (action) @@ -406,48 +94,6 @@ private static void ApplyRecordingAction(ModelChanges recording, RecordingAction private static IEnumerable RecordedValues(ModelChanges recording) => recording.History.Select(change => Assert.IsType(change.NewValue)); - [Theory] - [InlineData(false, false)] - [InlineData(false, true)] - [InlineData(true, false)] - [InlineData(true, true)] - public void ListenerEditsAreRecordedAfterTheirCauseSoUndoRestoresTheStart(bool ancestorFirst, bool separateSlot) - { - var root = new ArchiveNode { Name = "root" }; - var child = new ArchiveNode { Name = "initial" }; - var target = separateSlot ? new ArchiveNode { Name = "other" } : child; - root.Children.Add(child); - if (separateSlot) root.Children.Add(target); - - var recording = root.VmfChanges; - if (ancestorFirst) recording.Start(); - using (child.VmfChanges.AddPropertyListener("name", change => - { - if (change.NewValue is not "outer") return; - // The child's own listener runs before the recording ancestor's group (portable contract E8). - Assert.Empty(recording.History); - target.Name = "nested"; - })) - { - if (!ancestorFirst) recording.Start(); - child.Name = "outer"; - } - - recording.Stop(); - var native = Assert.Single(recording.Transactions); - // A listener's edit is recorded after the edit that triggered it (portable contract H4), so undoing the - // transaction restores the state before it. - Assert.Equal(["outer", "nested"], native.Changes.Select(change => change.NewValue)); - Assert.True(native.CanUndo); - Assert.True(native.Undo()); - Assert.Equal("initial", child.Name); - Assert.Equal(separateSlot ? "other" : child.Name, target.Name); - Assert.True(native.CanRedo); - Assert.True(native.Redo()); - Assert.Equal(separateSlot ? "outer" : "nested", child.Name); - Assert.Equal("nested", target.Name); - } - [Fact] public void APortableFrameCannotPublishWhileAScalarEditAwaitsItsRecordingRelay() { @@ -474,114 +120,4 @@ public void APortableFrameCannotPublishWhileAScalarEditAwaitsItsRecordingRelay() Assert.False(root.VmfChanges.IsRecording); Assert.Throws(() => recorder.Finish()); } - - [Theory] - [InlineData("values")] - [InlineData("doubles")] - public void AManagedCollectionCommitPrecedesTheScalarEditItTriggers(string property) - { - var working = new SummaryValues(); - var checkpoint = new SummaryValues(); - var binding = new JournalBinding("conformance.observer-mixed", 1, _ => "root"); - using var listener = working.VmfChanges.AddPropertyListener(property, _ => working.Magnitude = 1.5f); - using var recorder = JournalRecorder.Start(working, SummarySnapshot.Registry, binding, "base", 0); - if (property == "values") working.Values.Put("x", 1); - else working.Doubles.Add(1.0); - - Assert.Equal([property, "magnitude"], working.VmfChanges.History.Select(edit => edit.PropertyName)); - var journal = recorder.Finish(); - Assert.Equal([property, "magnitude"], Assert.Single(journal.Transactions).Operations.Select(edit => edit.Property)); - var replayed = JournalReplayer.Replay(checkpoint, binding, "base", journal, SummarySnapshot.Registry); - Assert.Equal(1.5f, replayed.Magnitude); - if (property == "values") Assert.Equal(1, replayed.Values["x"]); - else Assert.Contains(1.0, replayed.Doubles); - } - - [Fact] - public void ReentrantDirectReferenceRecordingReplaysAgainstTheCheckpointGraph() - { - var root = new ArchiveNode { Name = "root" }; - var editor = new ArchiveNode { Name = "editor" }; - var initial = new ArchiveNode { Name = "initial" }; - var outer = new ArchiveNode { Name = "outer" }; - var nested = new ArchiveNode { Name = "nested" }; - root.Children.AddRange([editor, initial, outer, nested]); - editor.Anchor = initial; - string checkpoint = ModelSnapshot.Write(root); - var binding = new JournalBinding("conformance.observer.direct-reference", 1, - model => Assert.IsType(model).Name!); - var edits = new List(); - using var local = editor.VmfChanges.AddPropertyListener("anchor", change => - { - var target = Assert.IsType(change.NewValue); - edits.Add(target.Name!); - if (ReferenceEquals(target, outer)) editor.Anchor = nested; - }); - using var recorder = JournalRecorder.Start(root, ModelSnapshot.Registry, binding, "initial", 0); - - editor.Anchor = outer; - Assert.Equal(["outer", "nested"], edits); - // The triggering edit is recorded before the edits its listeners made (portable contract H4). - Assert.Collection(root.VmfChanges.History, - change => Assert.Same(outer, change.NewValue), - change => Assert.Same(nested, change.NewValue)); - var journal = JournalJson.Read(JournalJson.Write(recorder.Finish())); - var fresh = ModelSnapshot.Read(checkpoint); - var replayed = JournalReplayer.Replay(fresh, binding, "initial", journal, ModelSnapshot.Registry); - Assert.Same(fresh.Children[1], fresh.Children[0].Anchor); - Assert.Same(replayed.Children[3], replayed.Children[0].Anchor); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void CallbackInitializationSurvivesJournalCreationAlongsideRecordedEdits(bool owns) - { - var working = new ArchiveNode { Name = "root" }; - var existing = new ArchiveNode { Name = "existing" }; - var introduced = new ArchiveNode { Name = "introduced" }; - working.Children.Add(existing); - var checkpoint = ModelSnapshot.Read(ModelSnapshot.Write(working)); - var binding = new JournalBinding("conformance.observer.created-reference", 1, value => ((ArchiveNode)value).Name!) - .WithObjectTypes(_ => "node", (_, id) => new ArchiveNode { Name = id }); - var field = owns ? "inset" : "anchor"; - using var listener = working.VmfChanges.AddPropertyListener(field, change => - { - if (ReferenceEquals(change.NewValue, introduced)) - { - introduced.Anchor = existing; - existing.Anchor = working; - } - }); - using var recorder = JournalRecorder.Start(working, ModelSnapshot.Registry, binding, "initial", 0); - if (owns) - { - working.Inset = introduced; - } - else - { - working.Anchor = introduced; - working.Children.Add(introduced); - } - - var journal = JournalJson.Read(JournalJson.Write(recorder.Finish())); - var replayed = JournalReplayer.Replay(checkpoint, binding, "initial", journal, ModelSnapshot.Registry); - Assert.Equal(owns ? 1 : 2, replayed.Children.Count); - var known = Assert.IsType(replayed.Children[0]); - var fresh = Assert.IsType(owns ? replayed.Inset : replayed.Anchor); - Assert.Same(known, fresh.Anchor); - Assert.Same(replayed, known.Anchor); - if (owns) Assert.Same(replayed, fresh.InsetOf); - else Assert.Same(fresh, replayed.Children[1]); - Assert.Null(checkpoint.Anchor); - Assert.Null(checkpoint.Inset); - } - - private static IDisposable ObserveName(ArchiveNode owner, string prefix, List trace, Action? seen = null) => - owner.VmfChanges.AddPropertyListener("name", change => - { - var name = Assert.IsType(change.NewValue); - trace.Add($"{prefix} {name}"); - seen?.Invoke(name); - }, ModelChangeScope.Recursive); } diff --git a/conformance/csharp/PositionalJournalTests.cs b/conformance/csharp/PositionalJournalTests.cs index 91695438..03870160 100644 --- a/conformance/csharp/PositionalJournalTests.cs +++ b/conformance/csharp/PositionalJournalTests.cs @@ -230,25 +230,6 @@ public void ReplaysExistingContainedObjectsAcrossListAndSlotEdits() Assert.Single(Assert.IsType(original.Head).Children); } - [Fact] - public void ReplaysOrderedScalarSetMovesAndNullableScalarSlots() - { - var working = new CollectionProfile(); - working.Phases.AddRange(["one", "two"]); - var baseline = ModelSnapshot.WritePlain(working); - var binding = new JournalBinding("conformance.positional-scalars", 1, _ => "root"); - - using var recorder = JournalRecorder.Start( - working, ModelSnapshot.Registry, binding, "start", 0); - working.Phases.Move(1, 0); - working.Messages.AddRange(["note", null, "note"]); - var journal = JournalJson.Read(JournalJson.Write(recorder.Finish())); - var replayed = JournalReplayer.Replay(ModelSnapshot.ReadPlain(baseline), - binding, "start", journal, ModelSnapshot.Registry); - Assert.Equal(["two", "one"], replayed.Phases); - Assert.Equal(new string?[] { "note", null, "note" }, replayed.Messages); - } - [Fact] public void JournalRejectsInvalidPositionsAndUnknownReferences() { diff --git a/conformance/csharp/ProjectedListLifetimeTests.cs b/conformance/csharp/ProjectedListLifetimeTests.cs index 1cc9a67a..b7f14e8c 100644 --- a/conformance/csharp/ProjectedListLifetimeTests.cs +++ b/conformance/csharp/ProjectedListLifetimeTests.cs @@ -7,23 +7,6 @@ namespace Vmf.CSharp.Conformance; public sealed class ProjectedListLifetimeTests { - [Fact] - public void DormantWrappersCanBeCollectedWhileTheSourceRemainsLive() - { - var source = new CollectionProfile().Messages; - var dormant = CreateDormantWrapper(source); - CollectUnreferencedObjects(); - Assert.False(IsAlive(dormant)); - - source.Add("cleanup"); - var received = new List(); - using var listener = new ReadOnlyList(source, static value => value) - .AddListener(edit => received.Add(Assert.Single(edit.Added).Value)); - source.Add("after cleanup"); - - Assert.Equal(new[] { "after cleanup" }, received); - GC.KeepAlive(source); - } [Fact] public void SubscriptionsKeepTheirProjectedSourceUntilDisposed() @@ -45,41 +28,10 @@ public void SubscriptionsKeepTheirProjectedSourceUntilDisposed() GC.KeepAlive(subscription); } - [Fact] - public void IgnoringTheSubscriptionHandleKeepsTheListenerActive() - { - var source = new CollectionProfile().Messages; - var received = new List(); - var projection = SubscribeWithoutKeepingTheHandle(source, received); - CollectUnreferencedObjects(); - Assert.True(IsAlive(projection)); - - source.Add("observed"); - - Assert.Equal(new[] { "observed" }, received); - GC.KeepAlive(source); - } - [MethodImpl(MethodImplOptions.NoInlining)] private static bool IsAlive(WeakReference> projection) => projection.TryGetTarget(out _); - [MethodImpl(MethodImplOptions.NoInlining)] - private static WeakReference> SubscribeWithoutKeepingTheHandle( - IReadOnlyList source, List received) - { - var projection = new ReadOnlyList(source, static value => value); - _ = projection.AddListener(edit => received.Add(Assert.Single(edit.Added).Value)); - return new(projection); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static WeakReference> CreateDormantWrapper(IReadOnlyList source) - { - var projection = new ReadOnlyList(source, static value => value); - return new(projection); - } - [MethodImpl(MethodImplOptions.NoInlining)] private static (WeakReference>, IDisposable) CreateObservedWrapper( IReadOnlyList source, List received) diff --git a/conformance/csharp/ProjectedListObservationTests.cs b/conformance/csharp/ProjectedListObservationTests.cs deleted file mode 100644 index 0117210b..00000000 --- a/conformance/csharp/ProjectedListObservationTests.cs +++ /dev/null @@ -1,154 +0,0 @@ -using Eu.Mihosoft.Vmf.Conformance.Ordinarycontainment; -using Eu.Mihosoft.Vmf.Conformance.Values; -using Vmf.Runtime; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class ProjectedListObservationTests -{ - [Fact] - public void OrdinaryScalarListsRelayAtProjectionMaterialization() => - Verify(() => - { - var owner = new CollectionProfile(); - return new Fixture(owner.Messages, () => owner.AsReadOnly(), () => owner.AsReadOnly().Messages, - value => owner.Messages.Add(value), value => value, value => value); - }); - - [Fact] - public void OrdinaryReferenceListsRelayAtProjectionMaterialization() => - Verify(() => - { - var owner = new ArchiveNode(); - return new Fixture(owner.Trail, () => owner.AsReadOnly(), - () => owner.AsReadOnly().Trail, value => owner.Trail.Add(new ArchiveNode { Name = value }), - value => value?.Name, value => value?.Name); - }); - - [Fact] - public void OrdinaryContainmentListsRelayAtProjectionMaterialization() => - Verify(() => - { - var owner = new LegacyContainer(); - return new Fixture(owner.Children, () => owner.AsReadOnly(), - () => owner.AsReadOnly().Children, value => owner.Children.Add(new LegacyChild { Name = value }), - value => value?.Name, value => value?.Name); - }); - - [Fact] - public void AModeledCallbackChangingTheProjectionKeepsTheCapturedListenersEligible() - { - var owner = new CollectionProfile(); - var source = owner.Messages; - var view = owner.AsReadOnly().Messages; - var projected = new List(); - using var original = view.AddListener(edit => projected.Add("old:" + edit.Added[0].Value)); - IDisposable? replacement = null; - using var modeled = owner.VmfChanges.AddLocalListener(edit => - { - if (edit.PropertyName != "messages" || source.Count != 1) return; - original.Dispose(); - replacement = view.AddListener(delta => projected.Add("new:" + delta.Added[0].Value)); - }); - - source.Add("outer"); - using var cleanup = replacement; - source.Add("future"); - - Assert.Equal(["old:outer", "new:future"], projected); - } - - private static void Verify(Func> create) - { - VerifyMaterialization(create()); - VerifySubscriptionReentry(create(), initiallyObserved: false); - VerifySubscriptionReentry(create(), initiallyObserved: true); - VerifyActiveProjectionSnapshot(create()); - } - - private static void VerifyMaterialization(Fixture fixture) - { - var events = new List(); - using var beforeView = fixture.Source.AddListener(_ => events.Add("before view")); - fixture.MaterializeModel(); - using var beforeList = fixture.Source.AddListener(_ => events.Add("before list")); - var view = fixture.View(); - fixture.Add("unobserved"); - Expect(events, "before view", "before list"); - using var afterList = fixture.Source.AddListener(_ => events.Add("after list")); - using var first = view.AddListener(change => - { - Assert.Same(view, change.Source); - events.Add("first projected"); - }); - using var last = fixture.Source.AddListener(_ => events.Add("last mutable")); - using var second = view.AddListener(_ => events.Add("second projected")); - fixture.Add("started"); - Expect(events, "before view", "before list", "first projected", "second projected", "after list", "last mutable"); - first.Dispose(); - second.Dispose(); - fixture.Add("unobserved again"); - Expect(events, "before view", "before list", "after list", "last mutable"); - using var restart = view.AddListener(_ => events.Add("restarted")); - fixture.Add("again"); - Expect(events, "before view", "before list", "restarted", "after list", "last mutable"); - } - - private static void VerifySubscriptionReentry(Fixture fixture, bool initiallyObserved) - { - var events = new List(); - IDisposable? old = null; - IDisposable? addedProjected = null; - IDisposable? addedMutable = null; - using var early = fixture.Source.AddListener(change => - { - var key = fixture.SourceKey(change.Added[0].Value); - events.Add("early:" + key); - if (key != "outer") return; - old?.Dispose(); - addedProjected = fixture.View().AddListener(edit => events.Add("new:" + fixture.ViewKey(edit.Added[0].Value))); - addedMutable = fixture.Source.AddListener(edit => events.Add("new mutable:" + fixture.SourceKey(edit.Added[0].Value))); - fixture.Add("nested"); - }); - var view = fixture.View(); - using var original = old = initiallyObserved - ? view.AddListener(edit => events.Add("old:" + fixture.ViewKey(edit.Added[0].Value))) : null; - using var late = fixture.Source.AddListener(edit => events.Add("late:" + fixture.SourceKey(edit.Added[0].Value))); - fixture.Add("outer"); - using var cleanupProjected = addedProjected; - using var cleanupMutable = addedMutable; - Expect(events, "early:outer", "early:nested", "new:nested", "late:nested", "new mutable:nested", "new:outer", "late:outer"); - } - - private static void VerifyActiveProjectionSnapshot(Fixture fixture) - { - var events = new List(); - var view = fixture.View(); - IDisposable? old = null; - IDisposable? added = null; - using var first = view.AddListener(change => - { - var key = fixture.ViewKey(change.Added[0].Value); - events.Add("first:" + key); - if (key != "outer") return; - old!.Dispose(); - added = view.AddListener(edit => events.Add("new:" + fixture.ViewKey(edit.Added[0].Value))); - fixture.Add("nested"); - }); - using var original = old = view.AddListener(edit => events.Add("old:" + fixture.ViewKey(edit.Added[0].Value))); - using var late = fixture.Source.AddListener(edit => events.Add("late:" + fixture.SourceKey(edit.Added[0].Value))); - fixture.Add("outer"); - using var cleanup = added; - Expect(events, "first:outer", "first:nested", "new:nested", "late:nested", "old:outer", "late:outer"); - } - - private static void Expect(List events, params string[] expected) - { - Assert.Equal(expected, events); - events.Clear(); - } - - private sealed record Fixture(IReadOnlyList Source, Action MaterializeModel, - Func> View, Action Add, Func SourceKey, Func ViewKey); -} diff --git a/conformance/csharp/ReadOnlyReplayCompatibilityTests.cs b/conformance/csharp/ReadOnlyReplayCompatibilityTests.cs index 0f7ebd7e..36e5e755 100644 --- a/conformance/csharp/ReadOnlyReplayCompatibilityTests.cs +++ b/conformance/csharp/ReadOnlyReplayCompatibilityTests.cs @@ -38,37 +38,6 @@ public void AForeignMarkerlessImmutableValueRemainsAModelPayload() Assert.Same(host, target.Payload); } - [Fact] - public void CapturedValuesAndPositionsStayApplicableAfterTheSourceAndHistoryChange() - { - var source = new CollectionProfile(); - var target = new CollectionProfile(); - target.Messages.Add("existing"); - var view = source.AsReadOnly(); - var history = view.VmfChanges; - history.Start(); - source.Messages.Add("captured"); - source.Options.Put("occupied", null); - var list = history.History[0]; - var map = history.History[1]; - - source.Messages[0] = "later"; - source.Options.Put("occupied", true); - history.Clear(); - history.Stop(); - - Assert.Same(view, list.Source); - Assert.Same(view, map.Source); - Assert.Empty(history.History); - list.Apply(target); - map.Apply(target); - Assert.Equal(["captured", "existing"], target.Messages); - Assert.True(target.Options.ContainsKey("occupied")); - Assert.Null(target.Options["occupied"]); - Assert.Equal(["later"], source.Messages); - Assert.True(source.Options["occupied"]); - } - private class LegacyValue { public ReadOnlyModelChanges VmfChanges => throw new InvalidOperationException("Metadata must not invoke the getter."); diff --git a/conformance/csharp/ReadOnlyTests.cs b/conformance/csharp/ReadOnlyTests.cs deleted file mode 100644 index 7a3cf3f7..00000000 --- a/conformance/csharp/ReadOnlyTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Eu.Mihosoft.Vmf.Example.Workshops; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public class ReadOnlyTests -{ - [Fact] - public void ViewsAreLiveStableAndDoNotExposeMutators() - { - var left = new Workshop(); - var right = new Workshop(); - var station = new Station { Name = "initial" }; - left.Stations.Add(station); - left.Favorites.Add(station); - - IReadOnlyWorkshop view = left.AsReadOnly(); - var stations = view.Stations; - IReadOnlyStation readStation = stations[0]; - Assert.Same(view, left.AsReadOnly()); - Assert.Same(readStation, station.AsReadOnly()); - Assert.Same(view, readStation.Workshop); - Assert.Same(readStation, Assert.Single(view.Favorites)); - Assert.False(stations is IList); - Assert.False(readStation.GetType().GetProperty("Name")?.CanWrite); - Assert.False(readStation.GetType().GetProperty("Workshop")?.CanWrite); - - station.Name = "renamed"; - Assert.Equal("renamed", readStation.Name); - station.Workshop = right; - Assert.Empty(view.Stations); - Assert.Empty(stations); - Assert.Same(readStation, Assert.Single(view.Favorites)); - Assert.Same(right.AsReadOnly(), readStation.Workshop); - - var site = new WorkshopSite(); - site.Workshops.Add(left); - site.Workshops.Add(right); - var restored = ModelSnapshot.Read(ModelSnapshot.Write(site.AsReadOnly())); - Assert.Same(restored.Workshops[1].Stations[0], Assert.Single(restored.Workshops[0].Favorites)); - } - - [Fact] - public void GenericViewRetainsTheConcreteReadOnlyType() - { - var catalog = new Catalog(); - var thermometer = new Thermometer { Sku = "T-1", Unit = "C" }; - catalog.Products.Add(thermometer); - catalog.Featured = thermometer; - - IReadOnlyShelf view = catalog.AsReadOnly(); - IReadOnlyInstrument featured = Assert.IsAssignableFrom(view.Featured); - Assert.Same(featured, view.Products[0]); - Assert.IsAssignableFrom(featured); - thermometer.Sku = "T-2"; - Assert.Equal("T-2", view.Products[0].Sku); - } -} diff --git a/conformance/csharp/ReciprocalListObservationTests.cs b/conformance/csharp/ReciprocalListObservationTests.cs deleted file mode 100644 index 941ef238..00000000 --- a/conformance/csharp/ReciprocalListObservationTests.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Eu.Mihosoft.Vmftest.Referenceends; -using Vmf.Runtime; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class ReciprocalListObservationTests -{ - [Theory] - [InlineData(false)] - [InlineData(true)] - public void OrdersSourceRelaysAndRecordsOnlyPrimaryEdits(bool viaOpposite) - { - var member = new Member(); - var team = new Team(); - var teams = member.Teams; - var changes = member.VmfChanges; - var trace = new List(); - using var direct = teams.AddListener(_ => trace.Add(team.Members.Contains(member) ? "linked" : "unlinked")); - using var projected = member.AsReadOnly().Teams.AddListener(_ => trace.Add("projected")); - using var local = changes.AddLocalListener(_ => trace.Add($"local:{changes.History.Count}")); - using var opposite = team.VmfChanges.AddLocalListener(_ => trace.Add("opposite")); - using var later = teams.AddListener(_ => trace.Add($"late:{changes.History.Count}")); - using var recursive = changes.AddRecursiveListener(_ => trace.Add($"recursive:{changes.History.Count}")); - changes.Start(); - if (viaOpposite) team.Members.Add(member); - else teams.Add(team); - changes.Stop(); - - // The object's local and recursive listeners receive a change together, in the order they were added - // (portable contract E7); raw list observers keep their own registration order around them. - Assert.Equal(viaOpposite - ? ["linked", "projected", "local:0", "recursive:0", "late:0", "opposite"] - : new[] { "opposite", "linked", "projected", "local:0", "recursive:0", "late:1" }, trace); - Assert.Equal(viaOpposite ? 0 : 1, changes.History.Count); - Assert.Same(team, Assert.Single(teams)); - } - - [Theory] - [InlineData("none", new[] { "inverse" })] - [InlineData("direct", new[] { "inverse", "old-direct" })] - [InlineData("dormant", new[] { "inverse", "projected" })] - [InlineData("model", new[] { "inverse", "old-model", "new-model" })] - [InlineData("replace", new[] { "inverse", "old-direct" })] - public void CapturesSourceRelaysBeforeInverseCallbacks(string kind, string[] expected) - { - var member = new Member(); - var team = new Team(); - var teams = member.Teams; - var trace = new List(); - using var first = kind switch - { - "direct" or "replace" => teams.AddListener(_ => trace.Add("old-direct")), - "model" => member.VmfChanges.AddLocalListener(_ => trace.Add("old-model")), - _ => null, - }; - if (kind == "dormant") _ = member.AsReadOnly().Teams; - var added = new List(); - using var inverse = team.VmfChanges.AddLocalListener(_ => - { - trace.Add("inverse"); - if (kind == "replace") first!.Dispose(); - added.Add(teams.AddListener(_ => trace.Add("new-direct"))); - added.Add(member.VmfChanges.AddLocalListener(_ => trace.Add("new-model"))); - added.Add(member.AsReadOnly().Teams.AddListener(_ => trace.Add("projected"))); - }); - try - { - teams.Add(team); - Assert.Equal(expected, trace); - trace.Clear(); - teams.Add(new Team()); - Assert.Contains("new-direct", trace); - Assert.Contains("new-model", trace); - Assert.Contains("projected", trace); - } - finally - { - foreach (var subscription in added) subscription.Dispose(); - } - } -} diff --git a/conformance/csharp/ReciprocalTests.cs b/conformance/csharp/ReciprocalTests.cs index 33260463..da65ce1a 100644 --- a/conformance/csharp/ReciprocalTests.cs +++ b/conformance/csharp/ReciprocalTests.cs @@ -291,24 +291,6 @@ private static ReciprocalGraph PrimaryListCheckpoint() return graph; } - [Theory] - [InlineData(false)] - [InlineData(true)] - public void CheckpointCopyKeepsRepeatedNullableReciprocalSlots(bool reverse) - { - var graph = ReciprocalCheckpoint(reverse); - var a = Node(graph, "a"); - var b = Node(graph, "b"); - a.Groups.AddRange([b, null, b]); - - var copy = ModelSnapshot.Reflection.DeepCopy(graph); - - Assert.NotSame(a, Node(copy, "a")); - Assert.NotSame(b, Node(copy, "b")); - VerifyReciprocalSlots(copy, 3); - VerifyReciprocalSlots(graph, 3); - } - [Theory] [InlineData("direct", false)] [InlineData("inverse", false)] @@ -596,23 +578,6 @@ public void SnapshotsAndReciprocalMembershipJournalInteroperateWithJava() File.WriteAllText(Path.Combine(exchange, "csharp-journal.json"), journalWire); } - [Fact] - public void DeepCopyPreservesBothEndpointsAndRepeatedNullSlotsAsAnIndependentGraph() - { - var original = Checkpoint(); - original.Nodes[0].Groups.AddRange([original.Nodes[2], null, original.Nodes[2], original.Nodes[3]]); - var copied = ModelSnapshot.Reflection.DeepCopy(original); - CheckSnapshot(copied); - Assert.NotSame(original, copied); - for (int index = 0; index < original.Nodes.Count; index++) - { - Assert.NotSame(original.Nodes[index], copied.Nodes[index]); - } - Assert.True(copied.Nodes[2].Members.Remove(copied.Nodes[0])); - Assert.Equal([null, copied.Nodes[3]], copied.Nodes[0].Groups); - Assert.Equal([original.Nodes[2], null, original.Nodes[2], original.Nodes[3]], original.Nodes[0].Groups); - } - private static ReciprocalGraph Checkpoint() { var a = new Endpoint { Id = "a" }; var b = new Endpoint { Id = "b" }; diff --git a/conformance/csharp/ReferenceCursorTests.cs b/conformance/csharp/ReferenceCursorTests.cs index 5678977d..d7e25495 100644 --- a/conformance/csharp/ReferenceCursorTests.cs +++ b/conformance/csharp/ReferenceCursorTests.cs @@ -31,50 +31,6 @@ public void GraphCursorDefaultsToUniqueNodesAndAllowsExplicitAliasSelection() Assert.False(containmentCursor.TryPeek(out _)); } - [Theory] - [InlineData(ModelTraversalStrategy.UniqueProperty)] - [InlineData(ModelTraversalStrategy.UniqueNode)] - public void SelectsExactReferenceSlotsAndPreservesTheOriginalBranchesPendingChildren(ModelTraversalStrategy strategy) - { - var descendant = new ArchiveNode(); - var original = new ArchiveNode { Anchor = descendant }; - var root = new ArchiveNode { Anchor = original }; - var tail = new ArchiveNode(); - var replacement = new ArchiveNode(); - var inserted = new ArchiveNode(); - root.Trail.AddRange([original, null, tail]); - - using var cursor = ModelSnapshot.Reflection.OpenGraphCursor(root, strategy); - Move(cursor, root); - Move(cursor, original); - Assert.True(cursor.CanReplace); - Assert.False(cursor.CanInsertAfter); - Assert.True(cursor.TryPeek(out var next)); - Assert.Same(descendant, next); - cursor.ReplaceCurrent(replacement); - Assert.Same(replacement, root.Anchor); - Assert.Same(original, root.Trail[0]); - Assert.Same(original, cursor.Current); - Move(cursor, descendant); - - if (strategy == ModelTraversalStrategy.UniqueProperty) - { - Move(cursor, original); - Assert.True(cursor.CanInsertAfter); - cursor.ReplaceCurrent(tail); - cursor.InsertAfterCurrent(inserted); - cursor.InsertAfterCurrent(replacement); - Assert.Equal(new ArchiveNode?[] { tail, inserted, replacement, null, tail }, root.Trail); - Assert.False(cursor.CanReplace); - Assert.Throws(() => cursor.ReplaceCurrent(original)); - } - - Move(cursor, tail); - cursor.ReplaceCurrent(null); - Assert.Null(root.Trail[^1]); - Assert.False(cursor.MoveNext()); - } - [Fact] public void DetectsStructuralListChangesEvenIfItsSlotIdentityReturnsAndRequiresAWritableRoot() { diff --git a/conformance/csharp/ReferenceListObservationTests.cs b/conformance/csharp/ReferenceListObservationTests.cs index 1a082ca4..10a50f26 100644 --- a/conformance/csharp/ReferenceListObservationTests.cs +++ b/conformance/csharp/ReferenceListObservationTests.cs @@ -8,43 +8,6 @@ namespace Vmf.CSharp.Conformance; public sealed class ReferenceListObservationTests { - [Fact] - public void OrdinaryReferenceListProjectsAliasedAndNullValuesAndHonorsDisposal() - { - var owner = new ArchiveNode(); - var item = new ArchiveNode { Name = "item" }; - var replacement = new ArchiveNode { Name = "replacement" }; - var list = owner.Trail; - var view = owner.AsReadOnly().Trail; - var mutable = new List>(); - var projected = new List>(); - using var watchList = list.AddListener(mutable.Add); - using var watchView = view.AddListener(projected.Add); - - list.AddRange([item, null, item]); - list[1] = replacement; - Assert.Equal(2, mutable.Count); - Assert.Equal(2, projected.Count); - Assert.All(mutable, edit => Assert.Same(list, edit.Source)); - Assert.All(projected, edit => Assert.Same(view, edit.Source)); - Assert.Equal([0, 1, 2], projected[0].Added.Select(entry => entry.Index)); - Assert.Same(item, mutable[0].Added[0].Value); - Assert.Same(item.AsReadOnly(), projected[0].Added[0].Value); - Assert.Null(projected[0].Added[1].Value); - Assert.Same(projected[0].Added[0].Value, projected[0].Added[2].Value); - Assert.Equal(new ModelListEntry(1, null), Assert.Single(projected[1].Removed)); - var substitution = Assert.Single(projected[1].Added); - Assert.Equal(1, substitution.Index); - Assert.Same(replacement.AsReadOnly(), substitution.Value); - - watchView.Dispose(); - list.RemoveAt(2); - watchList.Dispose(); - list.Clear(); - Assert.Equal(3, mutable.Count); - Assert.Equal(2, projected.Count); - Assert.Same(item.AsReadOnly(), projected[0].Added[2].Value); - } [Fact] public void ReciprocalReferenceListProjectsOneSparseInverseRemoval() @@ -61,85 +24,6 @@ public void ReciprocalReferenceListProjectsOneSparseInverseRemoval() Assert.Empty(group.Members); } - [Fact] - public void OrdinaryContainmentTransferPublishesSparseRemovalAndLiveProjection() - { - var source = new LegacyContainer(); - var destination = new LegacyContainer(); - var child = new LegacyChild(); - var retained = new LegacyChild(); - var list = source.Children; - list.AddRange([child, retained, null]); - list[2] = child; - var view = source.AsReadOnly().Children; - var additions = new List>(); - var target = destination.AsReadOnly().Children; - using var watchTarget = target.AddListener(additions.Add); - - VerifySparseRemoval(list, view, child, child.AsReadOnly(), () => destination.Children.Add(child)); - - Assert.Same(retained, Assert.Single(list)); - Assert.Same(destination, child.Owner); - var captured = Assert.Single(additions); - Assert.Same(target, captured.Source); - Assert.Equal(0, Assert.Single(captured.Added).Index); - Assert.Same(child.AsReadOnly(), captured.Added[0].Value); - Assert.Same(destination.AsReadOnly(), target[0]!.Owner); - } - - [Fact] - public void FailingProjectionListenerDoesNotInterruptTransferAndCanBeDisposed() - { - var source = new LegacyContainer(); - var destination = new LegacyContainer(); - var child = new LegacyChild(); - var list = source.Children; - list.AddRange([child, null, null]); - list[2] = child; - var view = source.AsReadOnly().Children; - var expected = new InvalidOperationException("first projected listener"); - var events = new List(); - using (view.AddListener(_ => throw expected)) - using (view.AddListener(_ => events.Add("projected"))) - using (list.AddListener(_ => events.Add("source"))) - using (destination.Children.AddListener(_ => events.Add("destination"))) - { - Assert.Same(expected, Assert.Throws(() => destination.Children.Add(child))); - } - Assert.Equal(["projected", "source", "destination"], events); - Assert.Same(destination, child.Owner); - - source.Children.Add(child); - Assert.Equal(3, events.Count); - Assert.Same(source, child.Owner); - } - - [Fact] - public void RepeatingDisposalLeavesTheOtherRegistrationOfTheSameCallback() - { - var owner = new ArchiveNode(); - VerifyIndependentHandles(owner.Trail, () => owner.Trail.Add(new ArchiveNode())); - VerifyIndependentHandles(owner.AsReadOnly().Trail, () => owner.Trail.Add(new ArchiveNode())); - var parent = new LegacyContainer(); - VerifyIndependentHandles(parent.Children, () => parent.Children.Add(new LegacyChild())); - VerifyIndependentHandles(parent.AsReadOnly().Children, () => parent.Children.Add(new LegacyChild())); - } - - private static void VerifyIndependentHandles(IReadOnlyList list, Action edit) - { - var calls = 0; - Action> callback = _ => calls++; - using var first = list.AddListener(callback); - using var second = list.AddListener(callback); - first.Dispose(); - first.Dispose(); - edit(); - Assert.Equal(1, calls); - second.Dispose(); - edit(); - Assert.Equal(1, calls); - } - private static void VerifySparseRemoval(IReadOnlyList list, IReadOnlyList view, T value, TView projectedValue, Action edit) where T : class? diff --git a/conformance/csharp/ReflectionAnnotationTests.cs b/conformance/csharp/ReflectionAnnotationTests.cs index 07aa877e..e719191b 100644 --- a/conformance/csharp/ReflectionAnnotationTests.cs +++ b/conformance/csharp/ReflectionAnnotationTests.cs @@ -26,17 +26,4 @@ public void RepeatedAnnotationsPreserveOrderThroughInheritanceAndProjection() .Add(new ModelAnnotation("role", "invalid"))); } } - - [Fact] - public void GeneratedAnnotationsReflectRelationshipAndImmutableKinds() - { - var archive = ModelSnapshot.Reflection.Reflect(new ArchiveNode()); - Assert.Equal("container:children", archive.FindProperty("parent")! - .AnnotationByKey("vmf:property:containment-info")?.Value); - Assert.Equal("", archive.FindProperty("anchor")!.AnnotationByKey("vmf:property:reference-opposite")?.Value); - var inventory = ModelSnapshot.Reflection.Reflect(new KeyedInventory()); - Assert.Equal("sku", inventory.FindProperty("products")!.AnnotationByKey("vmf:collection:key")?.Value); - var label = ModelSnapshot.Reflection.Reflect(ValueLabel.NewBuilder().Build()); - Assert.NotNull(label.AnnotationByKey("vmf:type:immutable")); - } } diff --git a/conformance/csharp/ReflectionDefaultTests.cs b/conformance/csharp/ReflectionDefaultTests.cs index a39b975f..ae755c13 100644 --- a/conformance/csharp/ReflectionDefaultTests.cs +++ b/conformance/csharp/ReflectionDefaultTests.cs @@ -36,30 +36,6 @@ public void PrimitiveDefaultsHaveTheDeclaredTypeAndResetTheLiveValue() } } - [Fact] - public void DeclaredDefaultsRestoreClearedAndInheritedValues() - { - var model = DefaultSettings.NewBuilder().WithName(null).WithLimit(null).Build(); - var reflection = ModelSnapshot.Reflection.Reflect(model); - var name = reflection.FindProperty("name")!; - var limit = reflection.FindProperty("limit")!; - Assert.Equal("idle\nready", name.DefaultValue); - Assert.Equal(7, limit.DefaultValue); - Assert.True(name.IsSet); - Assert.True(limit.IsSet); - var edits = new List(); - using var subscription = model.VmfChanges.AddLocalListener(edit => edits.Add(edit.PropertyName)); - name.Reset(); - limit.Reset(); - Assert.Equal("idle\nready", model.Name); - Assert.Equal(7, model.Limit); - Assert.False(name.IsSet); - Assert.False(limit.IsSet); - Assert.Equal(["name", "limit"], edits); - Assert.Equal(long.MinValue, - BitConverter.DoubleToInt64Bits(Assert.IsType(reflection.FindProperty("baseline")!.DefaultValue))); - } - [Fact] public void ResetManagedFieldsUsesTheirLiveStorage() { diff --git a/conformance/csharp/ReflectionTests.cs b/conformance/csharp/ReflectionTests.cs index 88f3df73..b27c851a 100644 --- a/conformance/csharp/ReflectionTests.cs +++ b/conformance/csharp/ReflectionTests.cs @@ -41,36 +41,6 @@ public void InheritedLogicalPropertiesUseJavaOrderAndRemainLiveInReadOnlyViews() Assert.Throws(() => readOnlyName.Set("invalid")); } - [Fact] - public void MetadataDescribesManagedCollectionsAndKeepsTheirReadonlyAccessors() - { - var profile = new CollectionProfile(); - var limits = Required(Reflection.Reflect(profile), "limits"); - Assert.Equal(SnapshotPropertyKind.ScalarMap, limits.Kind); - Assert.Equal(typeof(string), limits.KeyType); - Assert.Equal(typeof(long?), limits.ValueType); - Assert.Equal(1, limits.LowerBound); - Assert.Equal(3, limits.UpperBound); - Assert.True(limits.IsUnique); - Assert.True(limits.IsCollection); - Assert.Same(profile.Limits, limits.Get()); - - var readOnlyLimits = Required(Reflection.Reflect(profile.AsReadOnly()), "limits"); - var projected = Assert.IsAssignableFrom>(readOnlyLimits.Get()); - Assert.IsNotType>(projected); - profile.Limits.Add("current", null); - Assert.True(projected.ContainsKey("current")); - - var products = Required(Reflection.Reflect(new KeyedInventory()), "products"); - Assert.True(products.IsContainment); - Assert.True(products.IsOrdered); - Assert.False(products.IsUnique); - Assert.Equal(-1, products.UpperBound); - Assert.Equal("sku", products.KeyPropertyName); - Assert.Equal("items", products.WireName); - Assert.Equal("eu.mihosoft.vmf.conformance.values.KeyedInventoryBase", products.DeclaringType); - } - [Fact] public void InverseFieldsReflectBothViewsButAreNeverTraversalEdges() { diff --git a/conformance/csharp/RetainedContainmentCursorTests.cs b/conformance/csharp/RetainedContainmentCursorTests.cs index d31f0182..23a86187 100644 --- a/conformance/csharp/RetainedContainmentCursorTests.cs +++ b/conformance/csharp/RetainedContainmentCursorTests.cs @@ -56,62 +56,6 @@ public void MoreEditsKeepTheSelectedSlotAndShiftTheRetainedSlot() Assert.False(cursor.MoveNext()); } - [Theory] - [InlineData(false)] - [InlineData(true)] - public void RemovingOrReparentingAReboundAliasMakesItsDescendantSelectionStale(bool reparent) - { - var (root, branch, _) = Graph(twoRetainedSlots: true); - var leaf = branch.Left!; - using var cursor = AtFirstSlot(root, branch); - cursor.ReplaceCurrent(new BinaryExpression()); - Move(cursor, leaf); - Assert.True(cursor.CanReplace); - - if (reparent) - { - var destination = new BinaryExpression(); - destination.Arguments.Add(branch); - Assert.Same(destination, branch.Parent); - Assert.DoesNotContain(root.Arguments, child => ReferenceEquals(child, branch)); - } - else - { - root.Arguments.RemoveAt(1); - Assert.Same(branch, root.Arguments[1]); - Assert.Same(root, branch.Parent); - } - - Assert.Same(leaf, cursor.Current); - Assert.False(cursor.CanReplace); - Assert.Throws(() => cursor.ReplaceCurrent(null)); - Assert.Throws(() => cursor.TryPeek(out _)); - Assert.Throws(() => cursor.MoveNext()); - Assert.Same(leaf, branch.Left); - } - - [Fact] - public void ReattachingAnAncestorInvalidatesADescendantOfTheReboundAlias() - { - var (owner, branch, _) = Graph(); - var root = new BinaryExpression { Left = owner }; - using var cursor = ModelSnapshot.Reflection.OpenContainmentCursor(root); - Move(cursor, root); - Move(cursor, owner); - Move(cursor, branch); - cursor.ReplaceCurrent(new BinaryExpression()); - var leaf = branch.Left!; - Move(cursor, leaf); - Assert.True(cursor.CanReplace); - - root.Left = null; - root.Left = owner; - Assert.Same(branch, owner.Arguments[1]); - Assert.False(cursor.CanReplace); - Assert.Throws(() => cursor.ReplaceCurrent(null)); - Assert.Same(leaf, branch.Left); - } - private static (BinaryExpression Root, BinaryExpression Branch, NumberExpression Sibling) Graph(bool twoRetainedSlots = false) { var branch = new BinaryExpression diff --git a/conformance/csharp/ScalarCollectionApplyTests.cs b/conformance/csharp/ScalarCollectionApplyTests.cs index 66129db5..7fe59913 100644 --- a/conformance/csharp/ScalarCollectionApplyTests.cs +++ b/conformance/csharp/ScalarCollectionApplyTests.cs @@ -58,21 +58,6 @@ public void WritablePeerRecordsItsOwnValuesAndReplaysBothProducers() } } - [Fact] - public void WritablePeerCanBelongToAnotherGeneratedModelRegistry() - { - var (map, set) = SourceEdits(); - var peer = new OtherModel.JoinedCollections(); - peer.Limits["keep"] = 99; - peer.Levels.Add(0.0); - map.Apply(peer); - set.Apply(peer); - Assert.Equal(20L, peer.Limits["keep"]); - Assert.True(peer.Limits.TryGetValue("optional", out var optional)); - Assert.Null(optional); - Assert.True(peer.Levels.Contains(0.0) && peer.Levels.Contains(NegativeZero) && peer.Levels.Contains(double.NaN)); - } - [Fact] public void IncompatibleWritableTypesBoundsAndReadOnlyTargetsAreRejectedBeforeChanges() { diff --git a/conformance/csharp/ScalarMapObservationTests.cs b/conformance/csharp/ScalarMapObservationTests.cs index 8cbb52f9..8a9931e3 100644 --- a/conformance/csharp/ScalarMapObservationTests.cs +++ b/conformance/csharp/ScalarMapObservationTests.cs @@ -46,21 +46,6 @@ public void MutationsExposeTypedEntriesAndStableProjectedSource() Assert.Equal(7L, batch.Added["existing"]); } - [Fact] - public void TypedEntrySnapshotsUseTheManagedKeyComparer() - { - var profile = new CollectionProfile(); - var events = new List>(); - using var listener = profile.Markers.AddListener(events.Add); - profile.Markers.PutAll([new(0.0, 'p'), new(-0.0, 'n'), new(double.NaN, null)]); - var added = Assert.Single(events).Added; - Assert.Equal(3, added.Count); - Assert.Equal('p', added[0.0]); - Assert.Equal('n', added[-0.0]); - Assert.True(added.TryGetValue(BitConverter.Int64BitsToDouble(0x7ff8000000000001L), out var nan)); - Assert.Null(nan); - } - [Fact] public void FailingMapListenerKeepsHistoryAndV1Replay() { diff --git a/conformance/csharp/ScalarSetObservationTests.cs b/conformance/csharp/ScalarSetObservationTests.cs deleted file mode 100644 index 3efe95d9..00000000 --- a/conformance/csharp/ScalarSetObservationTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Eu.Mihosoft.Vmf.Conformance.Values; -using Vmf.Runtime; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class ScalarSetObservationTests -{ - [Fact] - public void GeneratedScalarSetObserversPreserveSourceMembershipAndSnapshot() - { - var profile = new CollectionProfile(); - var levels = profile.Levels; - var view = profile.AsReadOnly().Levels; - var mutable = new List>(); - var projected = new List>(); - using var watchView = view.AddListener(projected.Add); - using var watchLevels = levels.AddListener(mutable.Add); - - Assert.True(levels.AddRange([0.0, -0.0, double.NaN, BitConverter.Int64BitsToDouble(0x7ff8000000000001L)])); - Assert.False(levels.Add(double.NaN)); - Assert.Same(levels, Assert.Single(mutable).Source); - var change = Assert.Single(projected); - Assert.Same(view, change.Source); - Assert.Empty(change.Removed); - Assert.Equal(3, change.Added.Count); - Assert.True(change.Added.Contains(0.0)); - Assert.True(change.Added.Contains(-0.0)); - Assert.True(change.Added.Contains(double.NaN)); - - watchView.Dispose(); - Assert.True(levels.Remove(0.0)); - watchLevels.Dispose(); - levels.Clear(); - Assert.Equal(2, mutable.Count); - Assert.Single(projected); - Assert.Equal(3, change.Added.Count); - Assert.Empty(mutable[1].Added); - Assert.Single(mutable[1].Removed); - Assert.True(mutable[1].Removed.Contains(0.0)); - Assert.False(mutable[1].Removed.Contains(-0.0)); - } - - [Fact] - public void SetViewObserverFailureIsReportedAfterTheModelAndLaterListeners() - { - var profile = new CollectionProfile(); - var levels = profile.Levels; - var view = profile.AsReadOnly().Levels; - var expected = new InvalidOperationException("read-only set listener"); - var order = new List(); - using var first = view.AddListener(_ => - { - order.Add("failing view"); - throw expected; - }); - using var next = view.AddListener(_ => order.Add("view")); - using var source = levels.AddListener(_ => order.Add("mutable")); - var changes = profile.VmfChanges; - using var owner = changes.AddPropertyListener("levels", _ => order.Add("owner")); - changes.Start(); - Assert.Same(expected, Assert.Throws(() => levels.Add(1.0))); - changes.Stop(); - Assert.Equal(["mutable", "owner", "failing view", "view"], order); - Assert.Contains(1.0, levels); - Assert.Equal("levels", Assert.Single(changes.History).PropertyName); - } -} diff --git a/conformance/csharp/ScalarTests.cs b/conformance/csharp/ScalarTests.cs index f270cfb1..5630b7a4 100644 --- a/conformance/csharp/ScalarTests.cs +++ b/conformance/csharp/ScalarTests.cs @@ -9,29 +9,6 @@ public class ScalarTests { private static readonly string Fixtures = Path.Combine(AppContext.BaseDirectory, "fixtures"); - [Fact] - public void NativeScalarDefaultsMatchJava() - { - var sample = ModelSnapshot.ReadPlain("{}"); - Assert.False(sample.Active); - Assert.Equal((sbyte)0, sample.ByteValue); - Assert.Equal((short)0, sample.ShortValue); - Assert.Equal(0, sample.IntValue); - Assert.Equal(0L, sample.LongValue); - Assert.Equal('\0', sample.CharValue); - Assert.Equal(0f, sample.FloatValue); - Assert.Equal(0d, sample.DoubleValue); - Assert.Null(sample.OptionalActive); - Assert.Null(sample.OptionalByte); - Assert.Null(sample.OptionalShort); - Assert.Null(sample.OptionalInt); - Assert.Null(sample.OptionalLong); - Assert.Null(sample.OptionalChar); - Assert.Null(sample.OptionalFloat); - Assert.Null(sample.OptionalDouble); - Assert.Null(sample.Description); - } - [Fact] public void ExtremeScalarValuesRoundTripInBothProfiles() { diff --git a/conformance/csharp/ShallowCopyTests.cs b/conformance/csharp/ShallowCopyTests.cs index f04151dd..ac6e3a7d 100644 --- a/conformance/csharp/ShallowCopyTests.cs +++ b/conformance/csharp/ShallowCopyTests.cs @@ -83,40 +83,6 @@ public void RawCallbackCanActivateTheShallowOwnersModeledRelayOnAnExistingProjec } } - [Fact] - public void SharesMaterializedOrdinaryListsAndCopiesManagedStorage() - { - var source = new CollectionProfile(); - source.Messages.Add("before"); - source.Readings.Add(1.0); - source.Phases.Add("phase"); - source.Counts.Add(1); - source.Levels.Add(1.0); - source.Options.Add("present", null); - var copy = Values.Reflection.ShallowCopy(source); - Assert.NotSame(source, copy); - Assert.Same(source.Messages, copy.Messages); - Assert.Same(source.Readings, copy.Readings); - Assert.NotSame(source.Phases, copy.Phases); - Assert.NotSame(source.Counts, copy.Counts); - Assert.NotSame(source.Levels, copy.Levels); - Assert.NotSame(source.Options, copy.Options); - - copy.Messages.Add(null); - source.Readings.Add(2.0); - copy.Phases.Clear(); - copy.Counts.Add(2); - copy.Levels.Clear(); - copy.Options.Add("other", true); - Assert.Equal(new string?[] { "before", null }, source.Messages); - Assert.Equal(new double?[] { 1.0, 2.0 }, copy.Readings); - Assert.Equal(["phase"], source.Phases); - Assert.Equal([1], source.Counts); - Assert.Equal([1.0], source.Levels); - Assert.Equal("present", Assert.Single(source.Options).Key); - Assert.Null(copy.Options["present"]); - } - [Fact] public void OrdinaryListsStayIndependentUntilMaterializedByAccessOrObservation() { @@ -142,35 +108,6 @@ public void OrdinaryListsStayIndependentUntilMaterializedByAccessOrObservation() Assert.Empty(sharedView.Trail); } - [Fact] - public void SharedCollectionDispatchUsesEachOwnerAndActualRegistrationOrder() - { - var source = new CollectionProfile(); - source.Messages.Add("before"); - var copy = Values.Reflection.ShallowCopy(source); - var trace = new List(); - using var sourceLocal = source.VmfChanges.AddLocalListener(change => - { - Assert.Same(source, change.Source); - trace.Add("source local"); - }); - using var copyRecursive = copy.VmfChanges.AddRecursiveListener(change => - { - Assert.Same(copy, change.Source); - trace.Add("copy recursive"); - }); - using var sourceRecursive = source.VmfChanges.AddRecursiveListener(change => - { - Assert.Same(source, change.Source); - trace.Add("source recursive"); - }); - - copy.Messages.Add("edit"); - // The source's listeners run together, in the order they were added (portable contract E7); the copy shares - // the list but is not an ancestor, so its place relative to the source is not specified. - Assert.Equal(["source local", "source recursive", "copy recursive"], trace); - } - [Fact] public void RecursiveHistoryRecordsBothLogicalOwnersWithoutCopyingPriorHistory() { @@ -213,71 +150,6 @@ public void SharedListHistoryReplaysIntoBothListsOfAFreshCheckpoint() Assert.All(replayed.Children, child => Assert.Equal(new ArchiveNode?[] { null, null }, child.Trail)); } - [Fact] - public void CopiesInheritedValuesAndReferenceAliasesWhileDetachingTheNewRoot() - { - var settings = new DefaultSettings { Name = "name", Limit = 9, Note = "detail" }; - DefaultBase copy = Values.Reflection.ShallowCopy(settings); - Assert.Equal("name", copy.Name); - Assert.Equal(9, copy.Limit); - Assert.Equal("detail", Assert.IsType(copy).Note); - - var original = new ArchiveNode { Name = "original" }; - var member = new ArchiveNode { Name = "member" }; - original.Anchor = original; - original.Trail.AddRange([member, null, member]); - original.Peers.Add(member); - original.Featured.Add(member); - var shallow = Values.Reflection.ShallowCopy(original); - Assert.Same(original, shallow.Anchor); - Assert.Same(original.Trail, shallow.Trail); - Assert.NotSame(original.Peers, shallow.Peers); - Assert.NotSame(original.Featured, shallow.Featured); - Assert.Same(member, Assert.Single(shallow.Peers)); - Assert.Same(member, Assert.Single(shallow.Featured)); - var view = Values.Reflection.ShallowCopy(original.AsReadOnly()); - Assert.Same(original.AsReadOnly(), view.Anchor); - Assert.Same(member.AsReadOnly(), view.Trail[0]); - - var label = new ValueLabel("same"); - var withValue = new ValueSelection { Current = label }; - Assert.Same(label, Values.Reflection.ShallowCopy(withValue).Current); - Assert.Same(label, Values.Reflection.ShallowCopy(label)); - - var workshop = new Workshop(); - var station = new Station { Name = "station" }; - workshop.Stations.Add(station); - var detached = Workshops.Reflection.ShallowCopy(station); - Assert.Equal("station", detached.Name); - Assert.Same(workshop, station.Workshop); - Assert.Null(detached.Workshop); - } - - [Fact] - public void ProtectsExistingContainmentAndAllowsEmptyOwningCollections() - { - var workshop = new Workshop(); - var empty = Workshops.Reflection.ShallowCopy(workshop); - Assert.NotSame(workshop.Stations, empty.Stations); - var station = new Station { Name = "station" }; - workshop.Stations.Add(station); - Assert.Throws(() => Workshops.Reflection.ShallowCopy(workshop)); - Assert.Same(workshop, station.Workshop); - - var root = new ArchiveNode { Inset = new ArchiveNode() }; - var child = root.Inset; - Assert.Throws(() => Values.Reflection.ShallowCopy(root)); - Assert.Same(child, root.Inset); - Assert.Same(root, child!.InsetOf); - - var inventory = new KeyedInventory(); - var independent = Values.Reflection.ShallowCopy(inventory); - Assert.NotSame(inventory.Products, independent.Products); - inventory.Products.Add(new KeyedItem { Sku = "one" }); - Assert.Empty(independent.Products); - Assert.Throws(() => Values.Reflection.ShallowCopy(inventory)); - } - [Fact] public void ReusesTargetsOnlyWhenTheOppositeCanAccommodateBothOwners() { diff --git a/conformance/csharp/ShipmentTests.cs b/conformance/csharp/ShipmentTests.cs index ad93a9f3..a15502b7 100644 --- a/conformance/csharp/ShipmentTests.cs +++ b/conformance/csharp/ShipmentTests.cs @@ -14,44 +14,6 @@ public sealed class ShipmentTests _ => throw new ArgumentException("Unexpected shipment model.", nameof(value)), }); - [Fact] - public void OpenRolesShareOneProjectionAndKeepIndependentOwningSlots() - { - var source = NewShipment(); - Shipment open = source; - ParcelDeck parcels = open; - IParcelSelection selection = open; - IInspectionDeck inspections = open; - Assert.Same(source.Parcels, parcels.Parcels); - Assert.Same(source.Inspections, inspections.Inspections); - Assert.Same(source.Parcels[0], selection.Selected); - Assert.Same(selection.Selected, selection.History[0]); - Assert.Same(source.Inspections[0], inspections.LatestInspection); - - IReadOnlyShipment view = source.AsReadOnly(); - Assert.Same(view, selection.AsReadOnly()); - Assert.Same(view, inspections.AsReadOnly()); - Assert.Same(view.Parcels[0], view.Selected); - Assert.Same(view.Selected, view.History[0]); - Assert.Same(view.Inspections[0], view.LatestInspection); - var copy = ModelSnapshot.Reflection.DeepCopy(source); - Assert.NotSame(source.Parcels[0], copy.Parcels[0]); - Assert.NotSame(source.Inspections[0], copy.Inspections[0]); - Assert.Same(copy.Parcels[0], copy.Selected); - Assert.Same(copy.Parcels[0], copy.History[0]); - Assert.Same(copy.Inspections[0], copy.LatestInspection); - Assert.Equal(typeof(TrackedParcel), ModelSnapshot.Reflection.Reflect(copy).FindProperty("parcels")!.ValueType); - Assert.Equal(typeof(ParcelInspection), ModelSnapshot.Reflection.Reflect(copy).FindProperty("inspections")!.ValueType); - - IInspectionDeck destination = new DepotShipment(); - var moved = source.Inspections[1]; - destination.Inspections.Add(moved); - Assert.Same(moved, Assert.Single(destination.Inspections)); - Assert.Single(inspections.Inspections); - Assert.Single(view.Inspections); - Assert.Single(parcels.Parcels); - } - [Theory] [InlineData("json")] [InlineData("yaml")] diff --git a/conformance/csharp/SnapshotSchemaTests.cs b/conformance/csharp/SnapshotSchemaTests.cs index cd4a9db2..f5492696 100644 --- a/conformance/csharp/SnapshotSchemaTests.cs +++ b/conformance/csharp/SnapshotSchemaTests.cs @@ -525,17 +525,6 @@ public void NamedConstraintsPreserveLexicalBoundsAndTypeAssertions() Assert.Single(Assert.IsType(root["allOf"])); } - [Fact] - public void ClosedGenericsUseResolvedValueAndMapKeyShapes() - { - var integers = JsonNode.Parse(SnapshotSchema.Generate(NumericModels.Registry, SnapshotSchemaProfile.Plain))!; - var floating = JsonNode.Parse(SnapshotSchema.Generate(NumericModels.Registry, SnapshotSchemaProfile.Plain))!; - AssertBounds(Properties(integers)["current"]!, long.MinValue, long.MaxValue); - Assert.NotNull(Properties(floating)["current"]!["anyOf"]); - AssertBounds(Properties(Properties(integers)["byNumber"]!["items"]!)["key"]!, long.MinValue, long.MaxValue); - Assert.NotNull(Properties(Properties(floating)["byNumber"]!["items"]!)["key"]!["anyOf"]); - } - [Fact] public void GeneratedExternalUuidSchemaUsesStringsAndRetainsNullableListSlots() { @@ -611,26 +600,6 @@ public void RegistriesEscapeAliasPointersAndCombineSchemaAssertionsWithReference Assert.Equal("child", Assert.Single(Assert.IsType(schema["required"]))!.GetValue()); } - [Theory] - [InlineData("{broken default", null, null)] - [InlineData(null, "{broken annotation", null)] - [InlineData(null, null, "{broken assertion")] - public void InvalidSchemaMetadataOnlyFailsWhenSchemaIsRequested(string? defaultJson, string? annotationsJson, - string? assertionsJson) - { - var registry = new SnapshotRegistry([ - new SnapshotType("Example.Root", typeof(ExampleRoot), () => new ExampleRoot(), [ - new("child", SnapshotPropertyKind.Containment, typeof(ExampleChild), owner => ((ExampleRoot)owner).Child, - set: (owner, child) => ((ExampleRoot)owner).Child = (ExampleChild?)child, - schema: new SnapshotSchemaProperty(defaultJson: defaultJson, annotationsJson: annotationsJson, - assertionsJson: assertionsJson)), - ]), - new SnapshotType("Example.Child", typeof(ExampleChild), () => new ExampleChild(), []), - ]); - Assert.Null(SnapshotJson.ReadPlain("{}", registry).Child); - Assert.ThrowsAny(() => SnapshotSchema.Generate(registry)); - } - private static void Compare(string name, SnapshotRegistry registry, SnapshotSchemaProfile profile, string snapshot, Action common, Action? nativeOnly = null, IReadOnlyDictionary>? typeConstraints = null, string? generatedSchema = null) where T : class diff --git a/conformance/csharp/StockApplicationAliasTests.cs b/conformance/csharp/StockApplicationAliasTests.cs index e1e8ddce..6a93f8ec 100644 --- a/conformance/csharp/StockApplicationAliasTests.cs +++ b/conformance/csharp/StockApplicationAliasTests.cs @@ -79,28 +79,6 @@ void Verify(Simple.MyModel restored) } } - [Fact] - public void PlainXmlKeepsHostCodecsAndAcceptsEarlierRootNames() - { - var registry = External.ModelSnapshot.Registry.WithTypeAliases(new Dictionary - { - ["external-new"] = "eu.mihosoft.vmf.jackson.test.external_types01.ExternalTypeModel01", - }); - var owner = new External.ExternalTypeModel01 { EnumValue = External.ExternalEnum.SECOND }; - - foreach (string root in new[] { "external-new", "external-type-model-01" }) - { - string wire = SnapshotXml.WritePlain(owner, registry, root); - Assert.Equal(root, XDocument.Parse(wire).Root!.Name.LocalName); - Assert.DoesNotContain("vmf-type", wire); - Assert.Equal(External.ExternalEnum.SECOND, SnapshotXml.ReadPlain(wire, registry).EnumValue); - if (root == "external-new") - { - Assert.Throws(() => External.ModelSnapshot.ReadPlainXml(wire)); - } - } - } - [Fact] public void ConflictingNamesStayRejectedAndFeatureBundlesUseQualifiedNames() { diff --git a/conformance/csharp/StockCollectionContractTests.cs b/conformance/csharp/StockCollectionContractTests.cs index 7e6381f5..060da9f4 100644 --- a/conformance/csharp/StockCollectionContractTests.cs +++ b/conformance/csharp/StockCollectionContractTests.cs @@ -32,40 +32,6 @@ public void BoundedOrdinaryBuilderTransfersOwningSlotsAndValidatesOnlyActualMemb Assert.Equal("/items", Assert.Single(target.Validate()).ModelPath); } - [Fact] - public void RemovingAnEqualChildNotifiesAndDetachesTheFirstMatchingSlot() - { - var catalog = new Catalog(); - var first = new Item { Name = "same" }; - var second = new Item { Name = "same" }; - var detachedEqual = new Item { Name = "same" }; - Assert.Equal(first, second); - Assert.NotSame(first, second); - catalog.Items.AddRange([first, second]); - bool containsDetachedEqual = catalog.Items.Contains(detachedEqual); - Assert.True(containsDetachedEqual); - Assert.Equal(0, ((IList)catalog.Items).IndexOf(detachedEqual)); - - var observed = new List>(); - using var listener = catalog.Items.AddListener(observed.Add); - catalog.VmfChanges.Start(); - Assert.True(catalog.Items.Remove(second)); - catalog.VmfChanges.Stop(); - - Assert.Null(first.Catalog); - Assert.Same(second, Assert.Single(catalog.Items)); - Assert.Same(catalog, second.Catalog); - var removal = Assert.Single(Assert.Single(observed).Removed); - Assert.Equal(0, removal.Index); - Assert.Same(first, removal.Value); - var change = Assert.IsType(Assert.Single(catalog.VmfChanges.History)); - Assert.Same(first, Assert.Single(change.Removed).Value); - Assert.True(change.Undo()); - Assert.Same(first, catalog.Items[0]); - Assert.Same(second, catalog.Items[1]); - Assert.Same(catalog, first.Catalog); - } - [Fact] public void OwnershipAndReciprocalTransferSelectTheExactInstanceAmongEqualValues() { diff --git a/conformance/csharp/StockCollectionDefaultTests.cs b/conformance/csharp/StockCollectionDefaultTests.cs index 0a52b9a8..80d153ab 100644 --- a/conformance/csharp/StockCollectionDefaultTests.cs +++ b/conformance/csharp/StockCollectionDefaultTests.cs @@ -28,22 +28,4 @@ public void InheritedModelUsesItsOwnMapDefaultAcrossConstructionAndReset() var empty = ManagedSettings.NewBuilder().WithPorts([]).Build(); Assert.Empty(Maps.ReadPlain(Maps.WritePlain(empty)).Ports); } - - [Fact] - public void UnchangedJavaSetAndOrderedSetDeclarationsUseTheirLiteralDefaults() - { - var sampled = new DefaultGroups(); - Assert.Equal("x", Assert.Single(sampled.Tags)); - Assert.Equal(["a", "b"], sampled.Stages); - var state = Membership.Reflection.Reflect(sampled); - sampled.Tags.Clear(); - sampled.Stages.Clear(); - var explicitEmpty = Membership.ReadPlain(Membership.WritePlain(sampled)); - Assert.Empty(explicitEmpty.Tags); - Assert.Empty(explicitEmpty.Stages); - state.FindProperty("tags")!.Reset(); - state.FindProperty("stages")!.Reset(); - Assert.Equal("x", Assert.Single(sampled.Tags)); - Assert.Equal(["a", "b"], sampled.Stages); - } } diff --git a/conformance/csharp/StockManagedBuilderTests.cs b/conformance/csharp/StockManagedBuilderTests.cs index 0135968d..be625df7 100644 --- a/conformance/csharp/StockManagedBuilderTests.cs +++ b/conformance/csharp/StockManagedBuilderTests.cs @@ -37,46 +37,6 @@ public void ImportsThroughTheManagedMapBaseAndOverridesWithoutSharingStorage() Assert.Equal(80, Assert.Single(model.Ports).Value); } - [Fact] - public void ReplacementKeepsOrderPresenceAndTheJavaMapEditSequence() - { - var model = new Maps.ManagedSettings(); - var scores = model.Scores; - scores.PutAll([new("drop-a", 1.0), new("drop-b", 2.0), new("keep", 3.0)]); - var view = model.AsReadOnly().Scores; - var changes = new List>(); - using var listener = view.AddListener(changes.Add); - var builder = Maps.ManagedSettings.NewBuilder() - .WithScores([new("keep", 3.0), new("nil", null), new("tail", 4.0)]); - - builder.AppendCollections(false).ApplyTo(model); - Assert.Same(scores, model.Scores); - Assert.Equal(["keep", "nil", "tail"], scores.Keys); - Assert.True(scores.TryGetValue("nil", out var value)); - Assert.Null(value); - Assert.Collection(changes, - change => - { - Assert.Equal("drop-a", Assert.Single(change.Removed).Key); - Assert.Empty(change.Added); - }, - change => - { - Assert.Equal("drop-b", Assert.Single(change.Removed).Key); - Assert.Empty(change.Added); - }, - change => - { - Assert.Empty(change.Removed); - Assert.Equal(["nil", "tail"], change.Added.Keys); - }); - Assert.All(changes, change => Assert.Same(view, change.Source)); - - changes.Clear(); - builder.AppendCollections(true).ApplyTo(model); - Assert.Empty(changes); - } - [Fact] public void CheckedAppendFiltersDuplicatesAndRejectsOverflowBeforeEditing() { diff --git a/conformance/csharp/StockMiniClangTests.cs b/conformance/csharp/StockMiniClangTests.cs index 16783f38..1fcdd868 100644 --- a/conformance/csharp/StockMiniClangTests.cs +++ b/conformance/csharp/StockMiniClangTests.cs @@ -24,18 +24,6 @@ public void OriginalTypedLiteralAndWritablePayloadUseTheirDeclaredStorage(string Assert.Equal("fixture", Assert.IsAssignableFrom(restored.Payload)["origin"]); } - [Fact] - public void OriginalArrayRoleContractsShareTheListAndCanCallInheritedBehavior() - { - var array = new ArrayDeclStatement(); - var declaration = Assert.IsAssignableFrom(array); - var sizes = Assert.IsAssignableFrom(array); - Assert.Same(declaration.ArraySizes, sizes.ArraySizes); - declaration.ArraySizes.AddRange(["4", null, "4"]); - Assert.Equal(new string?[] { "4", null, "4" }, sizes.ArraySizes); - Assert.Null(new BlockStatement().ParentScopes()); - } - private static (Func Write, Func Read) Codecs(string format) => format switch { "xml" => (ModelSnapshot.WritePlainXml, ModelSnapshot.ReadPlainXml), diff --git a/conformance/csharp/StockModelMergeTests.cs b/conformance/csharp/StockModelMergeTests.cs index 97dcba63..2f9482c2 100644 --- a/conformance/csharp/StockModelMergeTests.cs +++ b/conformance/csharp/StockModelMergeTests.cs @@ -6,48 +6,6 @@ namespace Vmf.CSharp.Conformance; public class StockModelMergeTests { - [Fact] - public void MergesStockSecondaryBaseFieldsIntoTheConcreteTemplate() - { - var template = new Core.TypeC { Name = "template", PropA1 = 17, PropB1 = 2.5 }; - var incoming = new Core.TypeA { PropA2 = "reference" }; - var overlay = new Core.TypeB { PropB1 = 25, PropB2 = incoming }; - var reflection = Core.ModelSnapshot.Reflection; - - var merged = Assert.IsType(reflection.Merge(template, overlay)); - Assert.NotSame(template, merged); - Assert.Equal("template", merged.Name); - Assert.Equal(17, merged.PropA1); - Assert.Equal(25, merged.PropB1); - Assert.NotSame(incoming, merged.PropB2); - Assert.Equal("reference", merged.PropB2?.PropA2); - Assert.Equal(2.5, template.PropB1); - Assert.Null(template.PropB2); - Assert.Same(incoming, overlay.PropB2); - Assert.Throws(() => reflection.Diff(template, overlay)); - } - - [Fact] - public void IgnoresOverlayOnlyFieldsAndRetainsDefaultsOnTheTemplate() - { - var template = new Core.TypeA { PropA1 = 7, PropA2 = "retained" }; - var overlay = new Core.TypeC { Name = "other type", PropA1 = 17, PropB1 = 2.5 }; - var reflection = Core.ModelSnapshot.Reflection; - - var narrow = Assert.IsType(reflection.Merge(template, overlay)); - Assert.NotSame(template, narrow); - Assert.Equal(17, narrow.PropA1); - Assert.Equal("retained", narrow.PropA2); - Assert.Equal(7, template.PropA1); - - var fallback = new Core.TypeB(); - var field = reflection.Reflect(fallback).FindProperty("propB1")!; - field.SetDefault(42.0); - Assert.False(field.IsSet); - var merged = Assert.IsType(reflection.Merge(overlay, fallback)); - Assert.Equal(2.5, merged.PropB1); - Assert.Equal(42, fallback.PropB1); - } [Fact] public void AReferencedOverlayRootRetainsItsOwnConcreteTypeAndCycle() diff --git a/conformance/csharp/StockModelRegistryTests.cs b/conformance/csharp/StockModelRegistryTests.cs index 421ee617..29390088 100644 --- a/conformance/csharp/StockModelRegistryTests.cs +++ b/conformance/csharp/StockModelRegistryTests.cs @@ -55,20 +55,6 @@ public void RetainsTheFirstDescriptorAndRejectsConflictingDeclarationIdentity() Assert.Empty(ModelTypeCatalog.Compose().Types); } - [Fact] - public void PreservesOpenGenericAndInterfaceOnlyDeclarations() - { - var core = Core.ModelSnapshot.TypeCatalog; - var generic = Numeric.ModelSnapshot.TypeCatalog; - var composed = ModelTypeCatalog.Compose(core, ModelTypeCatalog.Compose(generic, core)); - var number = generic.Find(typeof(Numeric.NumericSeries<>))!; - var doubles = composed.Find(typeof(Numeric.DoubleSeries))!; - Assert.True(number.IsInterfaceOnly); - Assert.Same(number, composed.Find(typeof(Numeric.NumericSeries))); - Assert.True(composed.IsSubtypeOf(doubles.Declaration, number.Declaration)); - Assert.Equal(core.Types.Count + generic.Types.Count, composed.Types.Count); - } - private static ModelTypeMetadata Metadata(string name, Type runtimeType) => new(name, name, runtimeType, interfaceOnly: false, immutable: false, typeParameters: [], directSupertypes: [], properties: [], annotations: []); diff --git a/conformance/csharp/StockModelSharedDiffTests.cs b/conformance/csharp/StockModelSharedDiffTests.cs index 9977c499..d1ceeb8c 100644 --- a/conformance/csharp/StockModelSharedDiffTests.cs +++ b/conformance/csharp/StockModelSharedDiffTests.cs @@ -9,46 +9,6 @@ namespace Vmf.CSharp.Conformance; [Collection(Collections.CollectionDefaultBindings.TestCollection)] public sealed class StockModelSharedDiffTests { - [Fact] - public void DiffsSharedStockPropertiesAndPreservesAnImportedAliasAndCycle() - { - var source = new Core.TypeC { Name = "retained", PropA1 = 17, PropB1 = 2.5 }; - var incoming = new Core.TypeC { Name = "imported", PropA2 = "reference" }; - incoming.Prop = incoming; - var desired = new Core.TypeB { PropB1 = 25, Prop = incoming, PropB2 = incoming }; - var reflection = Core.ModelSnapshot.Reflection; - - var patch = reflection.DiffSharedProperties(source, desired.AsReadOnly()); - Assert.Equal(new[] { "prop", "propB1", "propB2" }, patch.Changes.Select(edit => edit.PropertyName).Order()); - Assert.Same(source, patch.Source); - Assert.Null(source.Prop); - Assert.Throws(() => patch.Apply(reflection.DeepCopy(source))); - patch.Apply(source); - Assert.Equal("retained", source.Name); - Assert.Equal(17, source.PropA1); - Assert.Equal(25, source.PropB1); - var copied = Assert.IsType(source.PropB2); - Assert.NotSame(incoming, copied); - Assert.Same(copied, source.Prop); - Assert.Same(copied, copied.Prop); - Assert.Equal("imported", copied.Name); - Assert.Equal("reference", copied.PropA2); - - desired.PropB2 = null; - var clearing = reflection.DiffSharedProperties(source, desired); - Assert.Equal("propB2", Assert.Single(clearing.Changes).PropertyName); - clearing.Apply(source); - Assert.Null(source.PropB2); - Assert.Same(copied, source.Prop); - clearing.Undo(source); - Assert.Same(copied, source.PropB2); - patch.Undo(source); - Assert.Equal(2.5, source.PropB1); - Assert.Null(source.Prop); - Assert.Null(source.PropB2); - Assert.Same(incoming, desired.Prop); - Assert.Same(incoming, incoming.Prop); - } [Fact] public void DiffsSharedSingularReferenceContentIntoAnExistingMutableTarget() @@ -68,37 +28,6 @@ public void DiffsSharedSingularReferenceContentIntoAnExistingMutableTarget() Assert.Equal("before", existing.PropA2); } - [Fact] - public void DiffsFrozenCollectionsIntoMutableLiveStorageAndUndoesPresentNull() - { - var source = new Collections.ManagedSamples(); - var numbers = source.Numbers; - var options = source.Options; - numbers.Clear(); - numbers.AddRange([3, 3]); - options.Clear(); - options["before"] = null; - var desired = new Collections.FrozenSamples(numbers: [8], labels: ["frozen"], codes: [9L], - options: new Dictionary { ["after"] = 11 }); - - var patch = Collections.ModelSnapshot.Reflection.DiffSharedProperties(source, desired); - Assert.Equal(new[] { "codes", "labels", "numbers", "options" }, - patch.Changes.Select(edit => edit.PropertyName).Order()); - patch.Apply(source); - Assert.Same(numbers, source.Numbers); - Assert.Same(options, source.Options); - Assert.Equal(new[] { 8 }, numbers); - Assert.Equal(new[] { "frozen" }, source.Labels); - Assert.Equal(9L, Assert.Single(source.Codes)); - Assert.Equal(11, options["after"]); - - patch.Undo(source); - Assert.Equal(new[] { 3, 3 }, numbers); - Assert.True(options.ContainsKey("before")); - Assert.Null(options["before"]); - Assert.False(options.ContainsKey("after")); - } - [Fact] public void RejectsAnUnassignableRootBackReferenceBeforeProducingAPatch() { diff --git a/conformance/csharp/StockPropertyInheritanceTests.cs b/conformance/csharp/StockPropertyInheritanceTests.cs index 2d55bc1c..407221d1 100644 --- a/conformance/csharp/StockPropertyInheritanceTests.cs +++ b/conformance/csharp/StockPropertyInheritanceTests.cs @@ -6,21 +6,6 @@ namespace Vmf.CSharp.Conformance; public class StockPropertyInheritanceTests { - [Fact] - public void InheritedPrimitiveDefaultsUseTheDeclaredTypeOnBothViews() - { - var point = LocationXY.NewBuilder().WithY(4).Build(); - foreach (object model in new object[] { point, point.AsReadOnly() }) - { - var reflection = ModelSnapshot.Reflection.Reflect(model); - var x = reflection.FindProperty("x")!; - var y = reflection.FindProperty("y")!; - Assert.Equal(0d, Assert.IsType(x.DefaultValue)); - Assert.Equal(0d, Assert.IsType(y.DefaultValue)); - Assert.False(x.IsSet); - Assert.True(y.IsSet); - } - } [Fact] public void StockCovariantLocationBranchesUseOneLiveSlot() diff --git a/conformance/csharp/StockPropertyOrderTests.cs b/conformance/csharp/StockPropertyOrderTests.cs index 5cc1229a..25c1522c 100644 --- a/conformance/csharp/StockPropertyOrderTests.cs +++ b/conformance/csharp/StockPropertyOrderTests.cs @@ -46,44 +46,6 @@ public void AbstractAndConcreteGettersExposeTheSameScalarAndChanges() .Properties.Select(property => property.Name).ToArray()); } - [Theory] - [InlineData("json")] - [InlineData("yaml")] - [InlineData("xml")] - public void StockNarrowedValueUsesScalarSnapshotsAndV1Journals(string format) - { - var baseline = Inherited.NewBuilder().WithValue(7).Build(); - foreach (bool references in new[] { false, true }) - { - var codec = SnapshotCodec(format, references); - Assert.Equal(7, codec.Read(codec.Write(baseline)).Value); - } - - var recorded = JournalRecorder.RecordFrame(new Inherited { Value = 7 }, - ModelSnapshot.Registry, Binding, CheckpointId, 0, reading => - { - reading.Value = 14; - reading.Value = null; - reading.Value = -24; - }); - (Func Write, Func Read) storage = format switch - { - "json" => (JournalJson.Write, JournalJson.Read), - "yaml" => (JournalYaml.Write, JournalYaml.Read), - "xml" => (JournalXml.Write, JournalXml.Read), - _ => throw new ArgumentOutOfRangeException(nameof(format)), - }; - var edits = storage.Read(storage.Write(recorded)); - Assert.Equal(1, edits.WireVersion); - Assert.True(JsonNode.DeepEquals(JsonNode.Parse(JournalJson.Write(recorded)), JsonNode.Parse(JournalJson.Write(edits)))); - - var snapshot = SnapshotCodec(format, references: true); - var checkpoint = snapshot.Read(snapshot.Write(baseline)); - var replayed = JournalReplayer.Replay(checkpoint, Binding, CheckpointId, edits, ModelSnapshot.Registry); - Assert.Equal(7, checkpoint.Value); - Assert.Equal(-24, replayed.Value); - } - private static (Func Write, Func Read) SnapshotCodec(string format, bool references) => (format, references) switch { diff --git a/conformance/csharp/StockReciprocalBuilderTests.cs b/conformance/csharp/StockReciprocalBuilderTests.cs deleted file mode 100644 index 086ba1c3..00000000 --- a/conformance/csharp/StockReciprocalBuilderTests.cs +++ /dev/null @@ -1,182 +0,0 @@ -using Eu.Mihosoft.Vmftest.Cross_ref; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class StockReciprocalBuilderTests -{ - [Fact] - public void ScalarImportStagesTheReferenceAndApplyUsesTheExistingTakeover() - { - var source = new EntityOneA(); - var target = new EntityOneA(); - var selected = new EntityTwoA(); - var displaced = new EntityTwoA(); - source.Ref = selected; - target.Ref = displaced; - var trace = new List(); - using var previous = source.VmfChanges.AddPropertyListener("ref", _ => trace.Add("previous owner")); - using var oldInverse = displaced.VmfChanges.AddPropertyListener("ref", _ => trace.Add("old inverse")); - using var destination = target.VmfChanges.AddPropertyListener("ref", _ => trace.Add("destination")); - using var newInverse = selected.VmfChanges.AddPropertyListener("ref", _ => trace.Add("new inverse")); - - var staged = EntityOneA.NewBuilder().ApplyFrom(source); - Assert.Same(source, selected.Ref); - Assert.Empty(trace); - staged.ApplyTo(source); - Assert.Empty(trace); - staged.ApplyTo(target); - Assert.Equal(["previous owner", "old inverse", "destination", "new inverse"], trace); - Assert.Null(source.Ref); - Assert.Null(displaced.Ref); - Assert.Same(selected, target.Ref); - Assert.Same(target, selected.Ref); - - var built = staged.Build(); - Assert.Null(target.Ref); - Assert.Same(selected, built.Ref); - Assert.Same(built, selected.Ref); - EntityOneA.NewBuilder().WithRefBuilder(EntityTwoA.NewBuilder()).ApplyTo(built); - Assert.Null(built.Ref); - Assert.Null(selected.Ref); - } - - [Fact] - public void InterfaceDeclaredEndsCanBeImportedFromTheirAbstractRoles() - { - Selector source = new Panel { Name = "source" }; - var target = new Panel { Name = "target" }; - var selected = new Button { Name = "selected" }; - source.Selected = selected; - Panel.NewBuilder().ApplyFrom(source).ApplyTo(target); - Assert.Null(source.Selected); - Assert.Same(selected, target.Selected); - Assert.Same(target, selected.SelectedBy); - Assert.Null(target.Name); - - Selectable previouslySelected = selected; - var replacement = new Button(); - Button.NewBuilder().ApplyFrom(previouslySelected).ApplyTo(replacement); - Assert.Null(selected.SelectedBy); - Assert.Same(target, replacement.SelectedBy); - Assert.Same(replacement, target.Selected); - } - - [Fact] - public void InheritedAndSelfOppositeScalarSlotsKeepTheirIdentity() - { - var owner = new EntityOneA(); - var selected = new EntityTwoA(); - owner.Ref = selected; - var derived = SpecializedEntityOneA.NewBuilder().WithLabel("derived").ApplyFrom(owner).Build(); - Assert.Null(owner.Ref); - Assert.Same(derived, selected.Ref); - Assert.Same(selected, derived.Ref); - Assert.Equal("derived", derived.Label); - - var self = new Partner(); - var destination = new Partner(); - self.PartnerReference = self; - Partner.NewBuilder().ApplyFrom(self).ApplyTo(destination); - Assert.Same(self, destination.PartnerReference); - Assert.Same(destination, self.PartnerReference); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void OrdinaryReciprocalListImportsRespectModesAndKeepTheirObserverOrder(bool append) - { - var one = new EntityOneB { Id = "one" }; - var two = new EntityOneB { Id = "two" }; - var existing = new EntityOneB { Id = "existing" }; - var source = EntityTwoB.NewBuilder().WithRefs([one, null, two, one]).Build(); - var target = EntityTwoB.NewBuilder().WithRefs([existing]).Build(); - var sourceRefs = source.Refs; - var targetRefs = target.Refs; - Assert.Equal([null, two, one], sourceRefs); - var trace = new List(); - using var priorOwner = source.VmfChanges.AddPropertyListener("refs", _ => trace.Add("previous")); - using var destination = target.VmfChanges.AddPropertyListener("refs", _ => trace.Add("destination")); - using var firstInverse = one.VmfChanges.AddPropertyListener("ref", _ => trace.Add("one")); - using var secondInverse = two.VmfChanges.AddPropertyListener("ref", _ => trace.Add("two")); - using var priorInverse = existing.VmfChanges.AddPropertyListener("ref", _ => trace.Add("existing")); - - var staged = EntityTwoB.NewBuilder().AppendCollections(append).ApplyFrom(source); - Assert.Empty(trace); - Assert.Same(source, one.Ref); - Assert.Same(source, two.Ref); - Assert.Same(target, existing.Ref); - staged.ApplyTo(target); - Assert.Same(sourceRefs, source.Refs); - Assert.Same(targetRefs, target.Refs); - Assert.Equal([null], sourceRefs); - Assert.Equal(append ? [existing, null, two, one] : [null, two, one], targetRefs); - Assert.Same(target, one.Ref); - Assert.Same(target, two.Ref); - Assert.Same(append ? target : null, existing.Ref); - Assert.Equal(append ? ["previous", "two", "previous", "one", "destination"] - : ["existing", "destination", "previous", "two", "previous", "one", "destination"], trace); - - trace.Clear(); - var fromTarget = EntityTwoB.NewBuilder().AppendCollections(append).ApplyFrom(target); - Assert.Empty(trace); - fromTarget.ApplyTo(target); - Assert.Equal(append ? [null, existing, null, two, one] : [null, two, one], targetRefs); - Assert.Equal(append ? ["destination", "destination", "destination", "destination"] - : ["two", "one", "destination", "two", "one", "destination"], trace); - Assert.Same(target, one.Ref); - Assert.Same(target, two.Ref); - } - - [Fact] - public void BuildingAnImportedReciprocalListTransfersExactlyTheExistingMembers() - { - var first = new EntityOneB { Id = "first" }; - var second = new EntityOneB { Id = "second" }; - var source = EntityTwoB.NewBuilder().WithRefs([first, null, second, first]).Build(); - var staged = EntityTwoB.NewBuilder().ApplyFrom(source); - Assert.Same(source, first.Ref); - Assert.Same(source, second.Ref); - var built = staged.Build(); - Assert.Equal([null], source.Refs); - Assert.Equal([null, second, first], built.Refs); - Assert.Same(built, first.Ref); - Assert.Same(built, second.Ref); - } - - [Fact] - public void SingularListInverseImportKeepsTheSourceAndMovesOnlyTheTargetMember() - { - var source = new EntityOneB { Id = "source" }; - var target = new EntityOneB { Id = "target" }; - var sibling = new EntityOneB { Id = "sibling" }; - var kept = new EntityOneB { Id = "kept" }; - var parent = EntityTwoB.NewBuilder().WithRefs([source, sibling]).Build(); - var previous = EntityTwoB.NewBuilder().WithRefs([target, kept]).Build(); - var trace = new List(); - using var priorOwner = previous.VmfChanges.AddPropertyListener("refs", _ => trace.Add("old list")); - using var destination = parent.VmfChanges.AddPropertyListener("refs", _ => trace.Add("new list")); - using var assignment = target.VmfChanges.AddPropertyListener("ref", change => - trace.Add(change.NewValue is null ? "clear" : "assign")); - - var staged = EntityOneB.NewBuilder().ApplyFrom(source); - Assert.Empty(trace); - Assert.Same(previous, target.Ref); - staged.ApplyTo(source); - Assert.Empty(trace); - staged.ApplyTo(target); - Assert.Equal(["clear", "old list", "assign", "new list"], trace); - Assert.Equal([kept], previous.Refs); - Assert.Equal([source, sibling, target], parent.Refs); - Assert.Same(parent, source.Ref); - Assert.Same(parent, target.Ref); - Assert.Equal("source", target.Id); - - trace.Clear(); - var built = staged.Build(); - Assert.Equal(["new list"], trace); - Assert.Equal([source, sibling, target, built], parent.Refs); - Assert.Same(parent, built.Ref); - } -} diff --git a/conformance/csharp/StockReciprocalListBuilderTests.cs b/conformance/csharp/StockReciprocalListBuilderTests.cs index 4dccd79e..3eba548d 100644 --- a/conformance/csharp/StockReciprocalListBuilderTests.cs +++ b/conformance/csharp/StockReciprocalListBuilderTests.cs @@ -62,42 +62,6 @@ public void ReciprocalListsKeepTheBulkPositionsAndPublishInverseEditsInOccurrenc Assert.Equal(["repeated:+", "fresh:+", "repeated:+"], events); } - [Fact] - public void EitherEndCanImportTheSameModelAliasTwice() - { - var source = new EntityTwoC(); - var target = new EntityTwoC(); - var left = new EntityOneC(); - EntityOneC?[] original = [left, null, left]; - source.Refs.AddRange(original); - var staged = EntityTwoC.NewBuilder().ApplyFrom(source).ApplyTo(target); - var built = staged.Build(); - Assert.Equal(original, source.Refs); - Assert.Equal(original, target.Refs); - Assert.Equal(original, built.Refs); - Assert.Equal([source, source, target, target, built, built], left.Refs); - } - - [Fact] - public void InverseObserverCanClearTheBulkInsertWithoutLeavingStaleInverses() - { - var source = new EntityOneC(); - var repeated = new EntityTwoC(); - var fresh = new EntityTwoC(); - bool cleared = false; - using var reenter = repeated.VmfChanges.AddPropertyListener("refs", change => - { - if (cleared || Assert.IsType(change).Added.Count == 0) return; - cleared = true; - source.Refs.Clear(); - }); - source.Refs.AddRange([repeated, fresh, repeated]); - Assert.True(cleared); - Assert.Empty(source.Refs); - Assert.Empty(repeated.Refs); - Assert.Empty(fresh.Refs); - } - private static IDisposable Observe(ModelChanges owner, string label, List events) => owner.AddPropertyListener("refs", change => events.Add(label + (Assert.IsType(change).Added.Count != 0 ? ":+" : ":-"))); diff --git a/conformance/csharp/StockReferenceBuilderTests.cs b/conformance/csharp/StockReferenceBuilderTests.cs index 2ce7feef..3c6ad46d 100644 --- a/conformance/csharp/StockReferenceBuilderTests.cs +++ b/conformance/csharp/StockReferenceBuilderTests.cs @@ -9,47 +9,6 @@ namespace Vmf.CSharp.Conformance; public sealed class StockReferenceBuilderTests { - [Fact] - public void EvaluatesEachStagedNestedBuilderOnlyDuringBuild() - { - var child = Builders.Child.NewBuilder().WithValue(1); - var single = Builders.Child2.NewBuilder().WithValue(2); - var counted = new CountingBuilder(child); - var inputs = new List?> { counted, null, counted }; - var parent = Builders.AClass.NewBuilder().WithChildrenBuilders(inputs).WithChildBuilder(single); - inputs.Clear(); - - var existing = new Builders.Child(); - var target = Builders.AClass.NewBuilder().WithChildren([existing]).WithChild(new Builders.Child2()).Build(); - parent.ApplyTo(target); - Assert.Null(target.Child); - Assert.Same(existing, Assert.Single(target.Children)); - parent.AppendCollections(false).ApplyTo(target); - Assert.Empty(target.Children); - Assert.Equal(0, counted.Calls); - - child.WithValue(7); - single.WithValue(8); - var first = parent.Build(); - child.WithValue(9); - single.WithValue(10); - var second = parent.Build(); - - Assert.Equal(4, counted.Calls); - Assert.Equal(8, first.Child!.Value); - Assert.Equal(10, second.Child!.Value); - Assert.NotSame(first.Child, second.Child); - Assert.Collection(first.Children, item => Assert.Equal(7, item!.Value), Assert.Null, item => Assert.Equal(7, item!.Value)); - Assert.Collection(second.Children, item => Assert.Equal(9, item!.Value), Assert.Null, item => Assert.Equal(9, item!.Value)); - Assert.NotSame(first.Children[0], first.Children[2]); - Assert.NotSame(first.Children[0], second.Children[0]); - - var direct = parent.WithChildren([existing]).WithChild(first.Child).Build(); - Assert.Same(existing, Assert.Single(direct.Children)); - Assert.Same(first.Child, direct.Child); - Assert.Null(parent.WithChildBuilder(null).Build().Child); - Assert.Equal(4, counted.Calls); - } [Theory] [InlineData(false)] @@ -98,37 +57,6 @@ public T Build() } } - [Fact] - public void BoundedPositionalReferencesKeepTheirListAndSetSemantics() - { - var a = new Ends.Station { Name = "a" }; - var b = new Ends.Station { Name = "b" }; - var c = new Ends.Station { Name = "c" }; - var kept = new Ends.Station { Name = "kept" }; - var source = Ends.BoundedPicks.NewBuilder().WithTrail([a, null, b, a]).WithChoices([a, b, c]).Build(); - var builder = Ends.BoundedPicks.NewBuilder().ApplyFrom(source); - var target = Ends.BoundedPicks.NewBuilder().WithTrail([kept]).WithChoices([kept]).Build(); - var trail = target.Trail; - var choices = target.Choices; - - builder.ApplyTo(target); - Assert.Same(trail, target.Trail); - Assert.Same(choices, target.Choices); - Assert.Collection(trail, value => Assert.Same(kept, value), value => Assert.Same(a, value), Assert.Null, - value => Assert.Same(b, value), value => Assert.Same(a, value)); - Assert.Collection(choices, value => Assert.Same(kept, value), value => Assert.Same(a, value), - value => Assert.Same(b, value), value => Assert.Same(c, value)); - source.Trail.Clear(); - source.Choices.Clear(); - - builder.AppendCollections(false).ApplyTo(target); - Assert.Collection(trail, value => Assert.Same(a, value), Assert.Null, - value => Assert.Same(b, value), value => Assert.Same(a, value)); - Assert.Collection(choices, value => Assert.Same(a, value), value => Assert.Same(b, value), - value => Assert.Same(c, value)); - Assert.Equal(new[] { "/choices", "/trail" }, target.Validate().Select(issue => issue.ModelPath)); - } - [Fact] public void BoundedOrderedBuilderRetainsExistingSlotsAndAppliesOwningTransfers() { @@ -159,33 +87,6 @@ public void BoundedOrderedBuilderRetainsExistingSlotsAndAppliesOwningTransfers() Assert.Empty(target.Validate()); } - [Fact] - public void CopiesAnOrdinaryListAndSingularReferenceWithoutChangingAliases() - { - var leaf = new Builders.Child(); - var single = new Builders.Child2(); - var source = Builders.AClass.NewBuilder() - .WithName("source").WithChildren([leaf, null, leaf]).WithChild(single).Build(); - var builder = Builders.AClass.NewBuilder().AppendCollections(false).ApplyFrom(source); - source.Children.Clear(); - source.Child = null; - - var target = Builders.AClass.NewBuilder().WithChildren([new Builders.Child()]).Build(); - var list = target.Children; - builder.ApplyTo(target); - Assert.Same(list, target.Children); - Assert.Equal("source", target.Name); - Assert.Collection(list, item => Assert.Same(leaf, item), Assert.Null, item => Assert.Same(leaf, item)); - Assert.Same(single, target.Child); - - builder.AppendCollections(true).ApplyTo(target); - Assert.Equal(6, list.Count); - Assert.Same(leaf, list[3]); - Assert.Null(list[4]); - Assert.Same(leaf, list[5]); - Assert.Empty(source.Children); - } - [Fact] public void CopiesAStockSingularReferenceAndTheInheritedName() { diff --git a/conformance/csharp/StockReferenceDefaultTests.cs b/conformance/csharp/StockReferenceDefaultTests.cs index 0da6e7cc..3b33769f 100644 --- a/conformance/csharp/StockReferenceDefaultTests.cs +++ b/conformance/csharp/StockReferenceDefaultTests.cs @@ -8,51 +8,6 @@ namespace Vmf.CSharp.Conformance; public class StockReferenceDefaultTests { - [Fact] - public void FreshModelAndBuilderCaptureReferenceIdentities() - { - var network = new DefaultNetwork(); - var seed = Assert.Single(network.Nearby); - var field = Field(network, "nearby"); - Assert.Same(seed, DefaultMember(field)); - Assert.False(field.IsSet); - Assert.Same(seed.AsReadOnly(), DefaultMember(Field(network.AsReadOnly(), "nearby"))); - - var builder = DefaultNetwork.NewBuilder(); - var first = builder.Build(); - var second = builder.Build(); - Assert.Same(first.Nearby.Single(), second.Nearby.Single()); - Assert.NotSame(seed, first.Nearby.Single()); - - network.Nearby.Clear(); - Assert.True(field.IsSet); - field.Reset(); - Assert.False(field.IsSet); - Assert.Same(seed, Assert.Single(network.Nearby)); - - var copy = ModelSnapshot.Reflection.DeepCopy(network); - var copiedSeed = Assert.Single(copy.Nearby); - Assert.NotSame(seed, copiedSeed); - Assert.Same(copiedSeed, DefaultMember(Field(copy, "nearby"))); - - var book = LabelBook.NewBuilder().Build(); - var label = Assert.Single(book.Labels); - var labels = Field(book, "labels"); - Assert.Equal("initial", label.Name); - Assert.Same(label, DefaultMember(labels)); - Assert.False(labels.IsSet); - Assert.False(labels.CanSetDefault); - } - - [Fact] - public void OmittedReferenceSetKeepsItsLocalDefault() - { - var network = ModelSnapshot.Read("{}"); - var field = Field(network, "nearby"); - Assert.Same(Assert.Single(network.Nearby), DefaultMember(field)); - Assert.False(field.IsSet); - Assert.Throws(() => ModelSnapshot.Write(network)); - } [Theory] [InlineData("json")] @@ -81,28 +36,6 @@ public void StockDocumentsPreserveExplicitMembersAndEmptyReferenceSets(string fo Assert.False(field.IsSet); } - [Fact] - public void StockReciprocalDefaultsFollowTheSameLinksAsEachCopy() - { - var panel = new Panel(); - var link = new StationLink(); - Field(panel, "links").SetDefault(new[] { link }); - - var deep = ModelSnapshot.Reflection.DeepCopy(panel); - var deepLink = Assert.Single(deep.Links); - Assert.NotSame(link, deepLink); - Assert.Same(deep, Assert.Single(deepLink.Panels)); - Assert.Same(deepLink, DefaultMember(Field(deep, "links"))); - Assert.False(Field(deep, "links").IsSet); - - var shallow = ModelSnapshot.Reflection.ShallowCopy(panel); - Assert.Same(link, Assert.Single(shallow.Links)); - Assert.Same(link, DefaultMember(Field(shallow, "links"))); - Assert.False(Field(shallow, "links").IsSet); - Assert.True(link.Panels.Contains(panel)); - Assert.True(link.Panels.Contains(shallow)); - } - private static ModelProperty Field(object model, string name) => ModelSnapshot.Reflection.Reflect(model).FindProperty(name)!; diff --git a/conformance/csharp/StockScalarGetterBuilderTests.cs b/conformance/csharp/StockScalarGetterBuilderTests.cs index 3049026f..1df2131b 100644 --- a/conformance/csharp/StockScalarGetterBuilderTests.cs +++ b/conformance/csharp/StockScalarGetterBuilderTests.cs @@ -6,32 +6,6 @@ namespace Vmf.CSharp.Conformance; public sealed class StockScalarGetterBuilderTests { - [Fact] - public void MutableBuilderCanImportAnImmutableGetterTraitThroughTheExistingSetter() - { - IReadOnlyWithName source = ImmutableObj.NewBuilder().WithName("frozen").Build(); - var target = MutableObj.NewBuilder().WithName("prior").Build(); - var view = target.AsReadOnly(); - var changes = new List(); - using var watch = target.VmfChanges.AddLocalListener(change => changes.Add(change.PropertyName)); - - var staged = MutableObj.NewBuilder().ApplyFrom(source); - Assert.Empty(changes); - Assert.Equal("prior", view.Name); - Assert.Equal("frozen", staged.Build().Name); - staged.ApplyTo(target); - Assert.Equal(["name"], changes); - Assert.Equal("frozen", target.Name); - Assert.Equal("frozen", view.Name); - MutableObj.NewBuilder().ApplyFrom(target).ApplyTo(target); - Assert.Equal(["name"], changes); - MutableObj.NewBuilder().ApplyFrom(new MutableObj()).ApplyTo(target); - Assert.Equal(["name", "name"], changes); - Assert.Null(target.Name); - Assert.Null(view.Name); - Assert.Equal("frozen", source.Name); - Assert.Null(typeof(IReadOnlyWithName).GetProperty(nameof(IReadOnlyWithName.Name))!.SetMethod); - } [Fact] public void TwoScalarGetterRolesImportOnlyTheirOwnStagedValues() diff --git a/conformance/csharp/StockSeriesBuilderTests.cs b/conformance/csharp/StockSeriesBuilderTests.cs deleted file mode 100644 index d167a674..00000000 --- a/conformance/csharp/StockSeriesBuilderTests.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Eu.Mihosoft.Vmftest.Genericseries; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public sealed class StockSeriesBuilderTests -{ - [Fact] - public void AppendAndReplaceWorkAcrossInheritedAndConcreteInputs() - { - var source = TemperatureSeries.NewBuilder().WithSamples([2.0]).Build(); - SampleSeries inherited = source; - var builder = TemperatureSeries.NewBuilder().WithSamples([1.0]); - - builder.ApplyFrom(inherited).ApplyFrom(source); - Assert.Equal(new double?[] { 1.0, 2.0, 2.0 }, builder.Build().Samples); - builder.AppendCollections(false).ApplyFrom(source); - Assert.Equal(new double?[] { 2.0 }, builder.Build().Samples); - - var targetList = source.Samples; - TemperatureSeries.NewBuilder().ApplyTo(source); - Assert.Equal(new double?[] { 2.0 }, targetList); - TemperatureSeries.NewBuilder().AppendCollections(false).ApplyTo(source); - Assert.Empty(targetList); - Assert.Same(targetList, source.Samples); - } - - [Fact] - public void ImportCapturesNullableMembersAndLeavesStagedValuesIndependent() - { - var source = TemperatureSeries.NewBuilder().WithLatest(1.5).WithSamples([null, 2.5]).Build(); - var builder = TemperatureSeries.NewBuilder().ApplyFrom((NumericSeries)source); - source.Samples.Clear(); - source.Latest = 7.5; - - var built = builder.Build(); - Assert.Equal(1.5, built.Latest); - Assert.Equal(new double?[] { null, 2.5 }, built.Samples); - builder.WithSamples([3.5]).ApplyTo(source); - Assert.Equal(1.5, source.Latest); - Assert.Equal(new double?[] { 3.5 }, source.Samples); - Assert.Equal(new double?[] { null, 2.5 }, built.Samples); - } -} diff --git a/conformance/csharp/StockSharedParentBuilderTests.cs b/conformance/csharp/StockSharedParentBuilderTests.cs index 62d21574..6627f157 100644 --- a/conformance/csharp/StockSharedParentBuilderTests.cs +++ b/conformance/csharp/StockSharedParentBuilderTests.cs @@ -41,24 +41,6 @@ public void CopyingAnAttachedChildImportsItsWritableValueAndKeepsTheOwners() Assert.Equal(["member.value"], events); } - [Fact] - public void AncestorImportsDoNotStageAnOwnerOrReplaceAlreadyStagedValues() - { - var owner = new BinaryExpression(); - var child = NumberExpression.NewBuilder().WithValue(3).Build(); - owner.Right = child; - Expression expression = child; - Element element = child; - var built = NumberExpression.NewBuilder().WithValue(17) - .ApplyFrom(expression).ApplyFrom(element).Build(); - Assert.Equal(17, built.Value); - Assert.Null(built.Parent); - Assert.Same(owner, child.Parent); - Assert.Same(child, owner.Right); - Assert.Null(typeof(NumberExpression).GetProperty(nameof(NumberExpression.Parent))!.SetMethod); - Assert.Null(typeof(NumberExpression.Builder).GetMethod("WithParent")); - } - [Theory] [InlineData(false)] [InlineData(true)] @@ -108,27 +90,4 @@ public void AbstractOwnedChildrenUseTheirSharedInverseWhenImported(bool append) Assert.Same(built, nested.Parent); Assert.Equal(append ? [previous, null] : [null], target.Arguments); } - - [Fact] - public void AbstractOwningBuilderChecksCyclesBeforeChangingAnyTargetProperty() - { - var source = new BinaryExpression(); - var ancestor = new BinaryExpression(); - var previous = new NumberExpression(); - var target = BinaryExpression.NewBuilder().WithOperator("unchanged").WithArguments([previous]).Build(); - ancestor.Left = target; - source.Arguments.Add(ancestor); - var events = new List(); - using var observe = target.VmfChanges.AddLocalListener(change => events.Add(change.PropertyName)); - - var staged = BinaryExpression.NewBuilder().AppendCollections(false).ApplyFrom(source).WithOperator("forbidden"); - Assert.Throws(() => staged.ApplyTo(target)); - Assert.Equal("unchanged", target.Operator); - Assert.Same(previous, Assert.Single(target.Arguments)); - Assert.Same(target, previous.Parent); - Assert.Same(target, ancestor.Left); - Assert.Same(ancestor, target.Parent); - Assert.Same(source, ancestor.Parent); - Assert.Empty(events); - } } diff --git a/conformance/csharp/StockSingularOwningBuilderTests.cs b/conformance/csharp/StockSingularOwningBuilderTests.cs index b4d4d5ce..03781569 100644 --- a/conformance/csharp/StockSingularOwningBuilderTests.cs +++ b/conformance/csharp/StockSingularOwningBuilderTests.cs @@ -40,23 +40,4 @@ public void ImportStagesTheOriginalSingularChildForConstructionOnly() Assert.True(targetSlot.IsSet); Assert.Equal("source", Assert.Single(events)); } - - [Fact] - public void ApplyingASingularSlotStageCannotIntroduceACycle() - { - var root = new CycleSlotNode(); - var branch = new CycleSlotNode(); - var leaf = new CycleSlotNode(); - root.Child = branch; - branch.Child = leaf; - var events = new List(); - using var listener = branch.VmfChanges.AddLocalListener(events.Add); - - CycleSlotNode.NewBuilder().WithChild(root).ApplyTo(branch); - Assert.Throws(() => branch.Child = root); - - Assert.Empty(events); - Assert.Same(branch, root.Child); - Assert.Same(leaf, branch.Child); - } } diff --git a/conformance/csharp/UnorderedCursorTests.cs b/conformance/csharp/UnorderedCursorTests.cs index 3e4a7ab5..ebd5d984 100644 --- a/conformance/csharp/UnorderedCursorTests.cs +++ b/conformance/csharp/UnorderedCursorTests.cs @@ -97,32 +97,6 @@ public void ReplacingAnUnorderedReferenceSlotUsesOneMembershipEdit() Assert.False(root.Peers.Contains(replacement)); } - [Fact] - public void ReplacingAnOwnedMemberTransfersTheReplacementAndDetachesThePreviousChild() - { - var root = OwningCheckpoint(); - var target = root.Shelves[0]!; - var source = root.Shelves[1]!; - var first = target.Volumes.First(); - var last = target.Volumes.Last(); - var moving = Assert.Single(source.Volumes); - using var recorder = JournalRecorder.Start(root, Owning.ModelSnapshot.Registry, Ownership, "base", 0); - using var cursor = Owning.ModelSnapshot.Reflection.OpenGraphCursor(target, ModelTraversalStrategy.ContainmentTree); - Move(cursor, target, first); - Assert.Throws(() => cursor.ReplaceCurrent(last)); - Assert.Throws(() => cursor.ReplaceCurrent(null)); - cursor.ReplaceCurrent(moving); - Move(cursor, last); - Assert.Equal(new[] { moving, last }, target.Volumes); - Assert.Empty(source.Volumes); - Assert.Null(first.Shelf); - Assert.Same(target, moving.Shelf); - var journal = recorder.Finish(); - Assert.Collection(Assert.Single(journal.Transactions).Operations, - edit => CheckMembership(edit, "source", "volumes", ["c"], []), - edit => CheckMembership(edit, "target", "volumes", ["a"], ["c"])); - } - [Fact] public void InsertingAnOwnedMemberTransfersOwnershipWithTheNormalMembershipEventsAndV1Wire() { diff --git a/conformance/csharp/YamlTests.cs b/conformance/csharp/YamlTests.cs index 370dcdfe..acb7e124 100644 --- a/conformance/csharp/YamlTests.cs +++ b/conformance/csharp/YamlTests.cs @@ -213,32 +213,6 @@ public void QuotedAndLiteralTextNeverBecomesAnImplicitScalar() Assert.Null(Values.ReadPlainYaml("description: null").Description); } - [Fact] - public void AQuotedMergeSpellingRemainsAnOrdinaryStructuredProperty() - { - var registry = new SnapshotRegistry([ - new SnapshotType("ArchiveRoot", typeof(ArchiveRoot), () => new ArchiveRoot(), [ - new("<<", SnapshotPropertyKind.Containment, typeof(ArchiveNode), owner => ((ArchiveRoot)owner).Head, - set: (owner, value) => ((ArchiveRoot)owner).Head = (ArchiveNode?)value), - ]), - new SnapshotType("ArchiveNode", typeof(ArchiveNode), () => new ArchiveNode(), [ - new("name", SnapshotPropertyKind.Scalar, typeof(string), owner => ((ArchiveNode)owner).Name, - set: (owner, value) => ((ArchiveNode)owner).Name = (string?)value), - ]), - ]); - var restored = SnapshotYaml.ReadPlain("'<<': { name: child }\n", registry); - var output = SnapshotYaml.WritePlain(restored, registry); - Assert.Contains("\"<<\"", output); - Assert.Equal("child", SnapshotYaml.ReadPlain(output, registry).Head?.Name); - } - - [Fact] - public void VmfReferenceValidationStillRejectsDanglingAndUnknownTypes() - { - Assert.ThrowsAny(() => Values.ReadYaml("review: [missing]\n")); - Assert.ThrowsAny(() => Workshops.ReadYaml("items:\n- '@vmf-type': unknown\n")); - } - private static void VerifyJournal(string checkpoint, string wire, JournalBinding binding, ChangeJournal recorded) { var baseline = Immutables.ReadYaml(checkpoint); diff --git a/conformance/delegated-list-csharp/DelegatedListsTests.cs b/conformance/delegated-list-csharp/DelegatedListsTests.cs index 841329d1..51523afc 100644 --- a/conformance/delegated-list-csharp/DelegatedListsTests.cs +++ b/conformance/delegated-list-csharp/DelegatedListsTests.cs @@ -90,34 +90,6 @@ public void ExplicitVListsBorrowAbstractModelAndScalarStorage() Assert.All(observed, change => Assert.Same(table, change.Source)); } - [Fact] - public void ExplicitObjectListReturnsKeepHostStateOutsideTheModelGraph() - { - var table = new Table { Name = "host" }; - string original = ModelSnapshot.WriteWithoutReferences(table); - var payloads = CheckHostPayloads(table); - var observed = new List(); - using var subscription = table.VmfChanges.AddLocalListener(observed.Add); - - var detached = new Row { Name = "unregistered child" }; - payloads[1] = (sbyte)4; - payloads.Add(detached); - Assert.Same(payloads, table.DirectPayloads()); - Assert.Equal((sbyte)4, Assert.IsType(payloads[1])); - Assert.Same(detached, payloads[4]); - Assert.Empty(observed); - var reflection = ModelSnapshot.Reflection.Reflect(table); - Assert.Null(reflection.FindProperty("payloads")); - Assert.Null(reflection.FindProperty("directPayloads")); - Assert.Same(table, Assert.Single(ModelSnapshot.Reflection.Traverse(table, ModelTraversalStrategy.UniqueNode))); - Assert.Null(typeof(IReadOnlyTable).GetMethod(nameof(Table.Payloads))); - - string wire = ModelSnapshot.WriteWithoutReferences(table); - Assert.Equal(original, wire); - var restored = ModelSnapshot.ReadWithoutReferences(wire); - Assert.NotSame(payloads, CheckHostPayloads(restored)); - } - private static IList CheckHostPayloads(Table table) { var payloads = Assert.IsAssignableFrom>(table.Payloads()); diff --git a/conformance/executable-default-csharp/ExecutableDefaultTests.cs b/conformance/executable-default-csharp/ExecutableDefaultTests.cs index 25199f4f..4a191845 100644 --- a/conformance/executable-default-csharp/ExecutableDefaultTests.cs +++ b/conformance/executable-default-csharp/ExecutableDefaultTests.cs @@ -7,66 +7,6 @@ namespace Vmf.CSharp.Conformance; public class ExecutableDefaultTests { - [Fact] - public void BuilderCopyUsesStagedScalarValuesInEffectivePropertyOrder() - { - ExecutableDefaultValues.RestartSequence(); - var source = new JoinedDefaults(); - var target = new JoinedDefaults(); - Events("joined-hook:null/null", "alias-1", "base-2", "joined-hook:null/null", "alias-3", "base-4"); - var builder = JoinedDefaults.NewBuilder(); - Events("alias-5", "base-6"); - - var applied = new List(); - using var observer = target.VmfChanges.AddLocalListener(change => applied.Add(change.PropertyName)); - Assert.Same(builder, builder.ApplyTo(target)); - Assert.Equal("alias-5", target.Alias); - Assert.Equal("base-6", target.Label); - Assert.Equal(["alias", "label"], applied); - Events(); - - source.Alias = "imported"; - source.Label = null; - Assert.Same(builder, builder.ApplyFrom(source)); - source.Alias = "changed after import"; - builder.ApplyTo(target); - Assert.Equal("imported", target.Alias); - Assert.Null(target.Label); - Events(); - - var built = builder.Build(); - Assert.Equal("imported", built.Alias); - Assert.Null(built.Label); - Events("joined-hook:null/null", "alias-7", "base-8"); - } - - [Fact] - public void MutableBuilderAndReflectionEvaluateDefaultsAtTheJavaBoundaries() - { - var direct = new MutableDefaults(); - Assert.Equal("prepared", direct.Label); - Assert.Equal(28, direct.Quota); - Events("label", "quota"); - - var staged = MutableDefaults.NewBuilder(); - Events("label", "quota"); - var overridden = staged.WithLabel(null).WithQuota(73).Build(); - Assert.Null(overridden.Label); - Assert.Equal(73, overridden.Quota); - Events("label", "quota"); - - var label = Field(overridden, "label"); - var quota = Field(overridden, "quota"); - Assert.True(label.IsSet); - Assert.True(quota.IsSet); - Assert.Equal("prepared", label.DefaultValue); - Assert.Equal(28, quota.DefaultValue); - label.Reset(); - quota.Reset(); - Assert.Equal("prepared", overridden.Label); - Assert.Equal(28, overridden.Quota); - Events("label", "quota", "label", "quota", "label", "quota"); - } [Fact] public void ImmutableBuilderEvaluatesOnceAndRetainsBoxedSignedZero() @@ -89,22 +29,6 @@ public void ImmutableBuilderEvaluatesOnceAndRetainsBoxedSignedZero() Assert.Throws(scale.Reset); } - [Fact] - public void ClassHookRunsOnRawValuesBeforeDeclaredDefaultsAndBuilderAssignments() - { - var direct = new HookedDefaults(); - Assert.Equal("prepared", direct.Label); - Assert.Equal(41, direct.Priority); - Events("hook:null/0", "label", "priority"); - - var staged = HookedDefaults.NewBuilder(); - Events("label", "priority"); - var overridden = staged.WithPriority(73).Build(); - Assert.Equal("prepared", overridden.Label); - Assert.Equal(73, overridden.Priority); - Events("hook:null/0", "label", "priority"); - } - [Fact] public void SnapshotPreservesExplicitNullAndCurrentValues() { diff --git a/conformance/external-binding-csharp/GenericEnumBindingTests.cs b/conformance/external-binding-csharp/GenericEnumBindingTests.cs index 0f54c041..f0979b25 100644 --- a/conformance/external-binding-csharp/GenericEnumBindingTests.cs +++ b/conformance/external-binding-csharp/GenericEnumBindingTests.cs @@ -8,7 +8,6 @@ namespace Vmf.CSharp.Conformance; public class GenericEnumBindingTests { - private const string JavaType = "eu.mihosoft.vmf.conformance.externalbinding.host.DispatchMode"; private static readonly JournalBinding Binding = new("enum-generic", 1, value => ((GenericModeProfile)value).Id!, null, JournalValueCodecs.Standard.WithImmutable("probe.generic-mode/v1", mode => Enum.GetName(mode) ?? throw new ArgumentException(nameof(mode)), Enum.Parse)); @@ -58,28 +57,6 @@ void VerifyJournal(string document) } } - [Fact] - public void ClosedGenericRetainsNullableNativeTypesAndExternalMetadata() - { - var profile = Fixture(); - ModeSamples typed = profile; - IReadOnlyModeSamples view = typed.AsReadOnly(); - Assert.Null(view.Latest); - Assert.Null(view.Samples[1]); - Assert.Equal(DispatchMode.UNDER_REVIEW, view.Samples[0]); - typed.Latest = DispatchMode.READY; - Assert.Equal(DispatchMode.READY, view.Latest); - - var reflected = ModelSnapshot.Reflection.Reflect(profile); - Assert.Equal(typeof(DispatchMode?), reflected.FindProperty("latest")!.ValueType); - Assert.Equal(typeof(DispatchMode?), reflected.FindProperty("samples")!.ValueType); - var metadata = ModelSnapshot.TypeCatalog.Find(typeof(GenericModeProfile))!; - var argument = Assert.Single(Assert.Single(metadata.DirectSupertypes).Arguments); - Assert.Equal(ModelValueKind.External, argument.Kind); - Assert.Equal(JavaType, argument.Name); - Assert.Equal(JavaType, Assert.Single(metadata.Properties, property => property.Name == "samples").ValueType.Name); - } - [Fact] public void SecondaryGenericRolePreservesMappedExternalValues() { diff --git a/conformance/external-binding-csharp/StockExternalBindingTests.cs b/conformance/external-binding-csharp/StockExternalBindingTests.cs index d8f2b2d0..46b649fc 100644 --- a/conformance/external-binding-csharp/StockExternalBindingTests.cs +++ b/conformance/external-binding-csharp/StockExternalBindingTests.cs @@ -85,71 +85,6 @@ public void BuildersTransferNativeExternalValuesWithoutCopyingTheirInstances() Assert.Null(entry.Scratch); } - [Fact] - public void StockReadOnlyExternalListForwardsEditsWithTheListAsSource() - { - var model = Sample.NewBuilder().WithLabels(["a", "b"]).Build(); - var readOnly = model.AsReadOnly(); - var labels = readOnly.Labels; - var viewEvents = new List>(); - var modelEvents = new List>(); - var ownerEvents = new List(); - using var modelListener = model.Labels.AddListener(modelEvents.Add); - using var ownerListener = model.VmfChanges.AddPropertyListener("labels", ownerEvents.Add); - using (labels.AddListener(viewEvents.Add)) - { - Assert.IsNotAssignableFrom>(labels); - Assert.Empty(viewEvents); - model.Labels.Add("c"); - model.Labels.RemoveAt(0); - } - Assert.Same(labels, readOnly.Labels); - Assert.Same(labels, BufferSnapshot.Reflection.Reflect(readOnly).FindProperty("labels")!.Get()); - Assert.Equal(["b", "c"], labels); - Assert.Collection(viewEvents, added => - { - Assert.Empty(added.Removed); - Assert.Equal(new ModelListEntry(2, "c"), Assert.Single(added.Added)); - }, removed => - { - Assert.Empty(removed.Added); - Assert.Equal(new ModelListEntry(0, "a"), Assert.Single(removed.Removed)); - }); - Assert.All(viewEvents, change => Assert.Same(labels, change.Source)); - Assert.All(modelEvents, change => Assert.Same(model.Labels, change.Source)); - Assert.All(ownerEvents, change => Assert.Same(model, change.Source)); - - model.Labels[0] = "d"; - Assert.Equal(2, viewEvents.Count); - Assert.Equal(3, ownerEvents.Count); - var replacement = modelEvents[2]; - Assert.Equal(new ModelListEntry(0, "b"), Assert.Single(replacement.Removed)); - Assert.Equal(new ModelListEntry(0, "d"), Assert.Single(replacement.Added)); - } - - [Fact] - public void AReadOnlyListListenerFailureKeepsTheEditAndModelHistory() - { - var model = new Sample(); - var labels = model.AsReadOnly().Labels; - var expected = new InvalidOperationException("listener failed"); - using var failing = labels.AddListener(_ => throw expected); - var changes = new List>(); - using var remaining = labels.AddListener(changes.Add); - var history = model.VmfChanges; - history.Start(); - - Assert.Same(expected, Assert.Throws(() => model.Labels.Add("kept"))); - Assert.Equal(["kept"], labels); - var edit = Assert.Single(changes); - Assert.Same(labels, edit.Source); - Assert.Equal(new ModelListEntry(0, "kept"), Assert.Single(edit.Added)); - var recorded = Assert.IsType(Assert.Single(history.History)); - Assert.Equal("labels", recorded.PropertyName); - Assert.Equal("kept", Assert.Single(recorded.Added).Value); - history.Stop(); - } - [Fact] public void StockGenericSeriesUsesTheDirectNestedEnumBinding() { @@ -211,53 +146,6 @@ public void StockUuidAndDocumentRevisionJournalRetainsCodecIdsAndBothFrames() } } - [Fact] - public void InMemoryStockJournalsAndHistoryUseOnlyTheJournalValueCodec() - { - var registry = ArchiveSnapshot.Registry.WithExternalValueCodecs(ExternalSnapshotCodecs.Empty); - var checkpoint = Baseline(); - var working = Baseline(); - var journal = JournalRecorder.RecordFrame(working, registry, Archive, "initial", 0, - model => model.Revision = new DocumentRevision(2)); - journal = JournalJson.Read(JournalJson.Write(journal)); - Assert.Equal(1, journal.WireVersion); - var operation = Assert.IsType(Assert.Single(Assert.Single(journal.Transactions).Operations)); - Assert.Equal("test.document-revision/v1", operation.After.CodecId); - Assert.Equal("2", operation.After.Text); - - var replayed = JournalReplayer.Replay(checkpoint, Archive, "initial", journal, registry); - Assert.NotSame(checkpoint, replayed); - Assert.Equal(new DocumentRevision(2), replayed.Revision); - Assert.Equal(new DocumentRevision(1), checkpoint.Revision); - - var history = new JournalHistory(Archive, registry); - history.AddSegment("initial", checkpoint, journal); - var historical = history.Seek(1); - Assert.Equal(new DocumentRevision(1), history.Seek(0).Revision); - Assert.Equal(new DocumentRevision(2), historical.Revision); - historical.Revision = new DocumentRevision(9); - Assert.Equal(new DocumentRevision(2), history.Seek(1).Revision); - - Assert.Throws(() => SnapshotJson.Write(checkpoint, registry)); - string encoded = ArchiveSnapshot.Write(checkpoint); - Assert.Throws(() => SnapshotJson.Read(encoded, registry)); - } - - [Fact] - public void MutableSnapshotHostIsNotAnExternalJournalValue() - { - var checkpoint = Baseline(); - checkpoint.Scratch = new StringBuilder("mutable"); - Assert.Throws(() => - JournalRecorder.Start(checkpoint, ArchiveSnapshot.Registry, Archive, "initial", 0)); - Assert.False(checkpoint.VmfChanges.IsRecording); - - var entry = Baseline(); - using var recorder = JournalRecorder.Start(entry, ArchiveSnapshot.Registry, Archive, "initial", 0); - entry.Scratch = new StringBuilder("mutable"); - Assert.Throws(() => recorder.Finish()); - } - private static ArchiveEntry Baseline() { var entry = new ArchiveEntry { Id = "entry", SourceId = First, Revision = new DocumentRevision(1) }; diff --git a/conformance/generic-bound-csharp/GenericBoundTests.cs b/conformance/generic-bound-csharp/GenericBoundTests.cs index 7570f3ff..b424ef0d 100644 --- a/conformance/generic-bound-csharp/GenericBoundTests.cs +++ b/conformance/generic-bound-csharp/GenericBoundTests.cs @@ -5,11 +5,6 @@ namespace Vmf.CSharp.Conformance; public class GenericBoundTests { - [Fact] - public void GetterOnlyBoundWorksForMutableAndImmutableTypeArguments() - { - Verify(Specimen()); - } [Fact] public void ClosedBoundPreservesWireFieldsAndAliasesInBothRuntimes() @@ -69,20 +64,6 @@ public void NamedTraitClosesItsGenericGetterForMutableAndImmutableValues() } } - [Fact] - public void NamedMutableOnlyTraitRetainsItsExistingClosedBaseClass() - { - var working = MutableQualifiedLabel.NewBuilder().WithQualifier("only").Build(); - var graph = NamedMutableAppliedSelection.NewBuilder().WithOwned([working]).WithCurrent(working) - .WithChoices([working]).Build(); - LabelSlot applied = graph; - IReadOnlyLabelSlot view = graph.AsReadOnly(); - Assert.Same(working, applied.Current); - Assert.True(applied.Choices.Contains(working)); - Assert.Same(working.AsReadOnly(), view.Current); - Assert.Equal("only", view.Current!.Qualifier); - } - [Fact] public void BuilderImportsAClosedGetterOnlyBoundThroughItsGenericBase() { diff --git a/conformance/generic-keyed-csharp/GenericKeyedTests.cs b/conformance/generic-keyed-csharp/GenericKeyedTests.cs index 65a6da6f..70861395 100644 --- a/conformance/generic-keyed-csharp/GenericKeyedTests.cs +++ b/conformance/generic-keyed-csharp/GenericKeyedTests.cs @@ -18,38 +18,6 @@ public class GenericKeyedTests _ => throw new ArgumentException("Unknown generic keyed object") }); - [Fact] - public void OpenAndClosedLookupUseOneIndexThroughBothGenericParents() - { - var registry = Specimen(); - Storage storage = registry.Primary!; - IOutgoingStorage secondary = registry.Primary!; - IReadOnlyStorage readOnly = registry.Primary!.AsReadOnly(); - IReadOnlyOutgoingStorage readOnlySecondary = registry.Primary.AsReadOnly(); - IReadOnlyStorage widened = storage.AsReadOnly(); - WarehouseEntry first = storage.FindOwnedBySlot("A")!; - WarehouseEntry second = secondary.FindOwnedBySlot("B")!; - Assert.Same(first, storage.Owned[0]); - Assert.Same(second, secondary.Owned[1]); - Assert.Same(readOnly.Owned[0], readOnlySecondary.FindOwnedBySlot("A")); - Assert.Same(first.AsReadOnly(), widened.FindOwnedBySlot("A")); - Assert.Equal("slot", ModelSnapshot.Reflection.Reflect(registry.Primary).FindProperty("owned")!.KeyPropertyName); - - Assert.Throws(() => second.Slot = "A"); - Assert.Throws(() => registry.Reserve!.Owned.Add(second)); - Assert.Equal("B", second.Slot); - Assert.Same(second, secondary.Owned[1]); - Assert.Single(registry.Reserve!.Owned); - Assert.Throws(() => - Warehouse.NewBuilder().WithOwned([Entry("x", "duplicate"), Entry("y", "duplicate")]).Build()); - second.Slot = "C"; - Assert.Same(second, secondary.FindOwnedBySlot("C")); - registry.Reserve.Owned.Add(second); - Assert.Null(storage.FindOwnedBySlot("B")); - Assert.Null(storage.FindOwnedBySlot("C")); - Assert.Same(second, registry.Reserve.FindOwnedBySlot("C")); - } - [Fact] public void ConcreteBoundPreservesDerivedTypedLookupRekeyAndReplay() { diff --git a/conformance/immutable-ancestry-csharp/ImmutablePortSettingsTests.cs b/conformance/immutable-ancestry-csharp/ImmutablePortSettingsTests.cs index 5f54c5e3..f78b21b2 100644 --- a/conformance/immutable-ancestry-csharp/ImmutablePortSettingsTests.cs +++ b/conformance/immutable-ancestry-csharp/ImmutablePortSettingsTests.cs @@ -6,26 +6,6 @@ namespace Vmf.CSharp.Conformance; public sealed class ImmutablePortSettingsTests { - [Fact] - public void BoundDefaultsUseConcreteStorageThroughBothGetterOnlyTraits() - { - var defaults = PortSettings.NewBuilder().Build(); - IReadOnlyWithDisplayLabel label = defaults; - IReadOnlyWithTooltipText tooltip = defaults; - Assert.Equal("115200", label.Label); - Assert.Equal("", tooltip.Tooltip); - Assert.Equal(PortMode.NORMAL, defaults.Mode); - Assert.Same(defaults, defaults.AsReadOnly()); - var omitted = ModelSnapshot.ReadPlain("{}"); - Assert.Equal("115200", omitted.Label); - Assert.Equal(PortMode.NORMAL, omitted.Mode); - - var reflected = ModelSnapshot.Reflection.Reflect(defaults); - Assert.Equal(3, reflected.Properties.Count); - Assert.Equal(PortMode.NORMAL, reflected.FindProperty("mode")!.DefaultValue); - Assert.Equal("115200", reflected.FindProperty("label")!.DefaultValue); - Assert.True(ModelSnapshot.TypeCatalog.Find(typeof(PortSettings))!.FindProperty("mode")!.HasExecutableDefault); - } [Theory] [InlineData("json")] diff --git a/conformance/immutable-behavior-csharp/ImmutableBehaviorTests.cs b/conformance/immutable-behavior-csharp/ImmutableBehaviorTests.cs index 0fb4b6b9..47e57016 100644 --- a/conformance/immutable-behavior-csharp/ImmutableBehaviorTests.cs +++ b/conformance/immutable-behavior-csharp/ImmutableBehaviorTests.cs @@ -52,38 +52,6 @@ public void ImmutableCallsStayOffModelAndReadOnlySurfaces() Assert.Same(inherited, inherited.AsReadOnly()); } - [Fact] - public void EachOwnerLazilyReusesOneTypedBindingAcrossOverloadsAndAliases() - { - int before = MethodValue.BindingCount; - var first = new MethodValue("alpha"); - var second = new MethodValue("beta"); - var calls = (IMethodValueCalls)first; - Assert.Equal(before, MethodValue.BindingCount); - var results = new string?[32]; - Parallel.For(0, results.Length, index => results[index] = calls.Render("!")); - Assert.All(results, text => Assert.Equal("!alpha", text)); - Assert.Equal("alp", calls.Render(3)); - Assert.Equal(10, calls.Sum(2, 3, 5)); - Assert.Equal(0, calls.Sum()); - Assert.Equal(before + 1, MethodValue.BindingCount); - Assert.Equal(results.Length + 1, ((IMethodValueCalls)first.AsReadOnly()).Calls()); - Assert.Equal(0, ((IMethodValueCalls)second).Calls()); - Assert.Equal(before + 2, MethodValue.BindingCount); - - string wire = ModelSnapshot.WritePlain(first); - using (var snapshot = JsonDocument.Parse(wire)) - { - var property = Assert.Single(snapshot.RootElement.EnumerateObject()); - Assert.Equal("text", property.Name); - Assert.Equal("alpha", property.Value.GetString()); - } - var restored = ModelSnapshot.ReadPlain(wire); - Assert.Equal(before + 2, MethodValue.BindingCount); - Assert.Equal(0, ((IMethodValueCalls)restored).Calls()); - Assert.Equal(before + 3, MethodValue.BindingCount); - } - [Fact] public void InheritedAndLocalBindingsInitializeIndependently() { diff --git a/conformance/immutable-behavior-csharp/ImmutableToStringTests.cs b/conformance/immutable-behavior-csharp/ImmutableToStringTests.cs deleted file mode 100644 index cde5fc20..00000000 --- a/conformance/immutable-behavior-csharp/ImmutableToStringTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Text.Json; -using Eu.Mihosoft.Vmf.Conformance.Immutablebehavior; -using Xunit; - -namespace Vmf.CSharp.Conformance; - -public class ImmutableToStringTests -{ - [Fact] - public void DelegatedObjectOverridesShareLazyBindingsAndPreserveNull() - { - ImmutableToStringBindings.NullCreated = ImmutableToStringBindings.TextCreated - = ImmutableToStringBindings.InheritedCreated = 0; - var plain = new PlainSummary("plain-data"); - var standalone = new StandaloneSummary("standalone-data"); - var empty = new NullSummary("still-data"); - var text = new TextSummary("alpha"); - var derived = new InheritedSummary("beta"); - Assert.Equal((0, 0, 0), Counts()); - - Assert.Equal(ModelSnapshot.Reflection.FormatSummary(plain), plain.ToString()); - string nonNullableSummary = standalone.ToString(); - Assert.Equal(ModelSnapshot.Reflection.FormatSummary(standalone), nonNullableSummary); - Assert.Null(((object)empty).ToString()); - Assert.Null(((PlainSummary)empty).ToString()); - Assert.Null(empty.AsReadOnly().ToString()); - Assert.Null(typeof(ITextSummaryCalls).GetMethod(nameof(ToString))); - Assert.DoesNotContain(typeof(NullSummary).GetInterfaces(), type => type.Name == "INullSummaryCalls"); - - Assert.Equal("alpha:1", ((object)text).ToString()); - Assert.Equal(1, ((ITextSummaryCalls)text).Calls()); - Assert.Equal("alpha:2", text.AsReadOnly().ToString()); - Assert.Equal("beta:1", ((object)derived).ToString()); - Assert.Equal(1, ((ITextSummaryCalls)derived).Calls()); - Assert.Equal((1, 1, 1), Counts()); - - VerifySnapshots(references: false); - VerifySnapshots(references: true); - } - - private static void VerifySnapshots(bool references) - { - var value = new TextSummary("snapshot"); - int previousBindings = ImmutableToStringBindings.TextCreated; - string Write(TextSummary root) => references - ? ModelSnapshot.Write(root) - : ModelSnapshot.WriteWithoutReferences(root); - string before = Write(value); - using var document = JsonDocument.Parse(before); - Assert.Equal("snapshot", document.RootElement.GetProperty("label").GetString()); - Assert.False(document.RootElement.TryGetProperty("calls", out _)); - Assert.Equal(previousBindings, ImmutableToStringBindings.TextCreated); - Assert.Equal("snapshot:1", value.ToString()); - Assert.Equal(before, Write(value)); - - var loaded = ModelSnapshot.Read(before); - Assert.Equal(previousBindings + 1, ImmutableToStringBindings.TextCreated); - Assert.Equal("snapshot:1", loaded.ToString()); - Assert.Equal(previousBindings + 2, ImmutableToStringBindings.TextCreated); - } - - private static (int Null, int Text, int Inherited) Counts() => - (ImmutableToStringBindings.NullCreated, ImmutableToStringBindings.TextCreated, - ImmutableToStringBindings.InheritedCreated); -} diff --git a/conformance/inherited-opposites-csharp/GetterRoleReciprocalTests.cs b/conformance/inherited-opposites-csharp/GetterRoleReciprocalTests.cs index 18133d29..e0ef5977 100644 --- a/conformance/inherited-opposites-csharp/GetterRoleReciprocalTests.cs +++ b/conformance/inherited-opposites-csharp/GetterRoleReciprocalTests.cs @@ -63,18 +63,6 @@ public void MembershipAndConcreteSetterShareOneGetterRoleInverse() Assert.Equal(teamTrace, projectedTeamTrace); } - [Fact] - public void ReferenceAwareSnapshotsReconstructEitherOmittedEnd() - { - string wire = ModelSnapshot.Write(CreateCheckpoint()); - var setOnly = JsonNode.Parse(wire)!; - setOnly["people"]![0]!.AsObject().Remove("team"); - CheckBaseline(ModelSnapshot.Read(setOnly.ToJsonString())); - var scalarOnly = JsonNode.Parse(wire)!; - scalarOnly["teams"]![0]!.AsObject().Remove("members"); - CheckBaseline(ModelSnapshot.Read(scalarOnly.ToJsonString())); - } - [Theory] [InlineData(VmfDocumentFormat.Json)] [InlineData(VmfDocumentFormat.Xml)] diff --git a/conformance/inherited-opposites-csharp/InheritedOppositeTests.cs b/conformance/inherited-opposites-csharp/InheritedOppositeTests.cs index 87462a9b..f828e60c 100644 --- a/conformance/inherited-opposites-csharp/InheritedOppositeTests.cs +++ b/conformance/inherited-opposites-csharp/InheritedOppositeTests.cs @@ -69,21 +69,6 @@ public void InterfaceOnlySecondaryReciprocalsShareStorageAndPreserveBothEndsInCo AssertSecondarySnapshot(ModelSnapshot.Read(snapshot)); } - [Fact] - public void ConcreteSecondaryRolesStillSupportDirectInstancesAndRoleMutations() - { - IConcreteDispatchTeam first = new ConcreteDispatchTeam(); - IConcreteDispatchTeam second = new NamedConcreteDispatchTeam { Name = "second" }; - IConcreteDispatchMember member = new NamedConcreteDispatchMember { Name = "member" }; - - Assert.True(first.Members.Add(member)); - Assert.Same(first, member.Team); - member.Team = second; - Assert.Empty(first.Members); - Assert.Same(member, Assert.Single(second.Members)); - Assert.Same(second.AsReadOnly(), member.AsReadOnly().Team); - } - private static void AssertSecondarySnapshot(DispatchBoard board) { var north = Assert.IsType(board.Teams[0]); @@ -130,36 +115,6 @@ public void PrimaryClassOppositesKeepOneInheritedSlotAndBothLiveInverses() Assert.Same(a, part.Team); } - [Fact] - public void AbstractPrimaryOppositesKeepExactLiveAndRecordedEdits() - { - var root = new RelationshipSite(); - AbstractTeam a = new ConcreteTeam(); - AbstractTeam b = new ConcreteTeam(); - AbstractPart part = new ConcretePart(); - root.AbstractTeams.AddRange([a, b]); - a.Parts.Add(part); - a.Featured.Add(part); - using var trace = new Trace(root, [(a, "a"), (b, "b"), (part, "part")]); - - part.Owner = b; - part.Team = b; - - Assert.Empty(a.Parts); - Assert.Empty(a.Featured); - Assert.Same(part, Assert.Single(b.Parts)); - Assert.Same(part, Assert.Single(b.Featured)); - Assert.Same(b.AsReadOnly(), part.AsReadOnly().Owner); - Assert.Same(b.AsReadOnly(), part.AsReadOnly().Team); - trace.VerifyAndUndo(InheritedLive, InheritedHistory); - Assert.Same(part, Assert.Single(a.Parts)); - Assert.Same(part, Assert.Single(a.Featured)); - Assert.Empty(b.Parts); - Assert.Empty(b.Featured); - Assert.Same(a, part.Owner); - Assert.Same(a, part.Team); - } - [Fact] public void NamedGenericOppositesPreserveClosedTypesUndoAndSnapshotIdentity() { diff --git a/conformance/inherited-opposites-csharp/SequenceRoleReciprocalTests.cs b/conformance/inherited-opposites-csharp/SequenceRoleReciprocalTests.cs index 31efaeba..9a27009e 100644 --- a/conformance/inherited-opposites-csharp/SequenceRoleReciprocalTests.cs +++ b/conformance/inherited-opposites-csharp/SequenceRoleReciprocalTests.cs @@ -58,15 +58,6 @@ void CheckPositions() } } - [Fact] - public void SnapshotCollectionClaimsRestoreMissingSingularEndsAtOriginalPositions() - { - var json = JsonNode.Parse(ModelSnapshot.Write(CreateCheckpoint()))!; - Assert.True(json["orderedPeople"]![0]!.AsObject().Remove("team")); - Assert.True(json["listPeople"]![1]!.AsObject().Remove("team")); - CheckBaseline(ModelSnapshot.Read(json.ToJsonString())); - } - [Fact] public void PositionalReciprocalRoleEditsReplayFromFreshV1Checkpoint() { diff --git a/conformance/keyed-redeclaration-csharp/KeyedRedeclarationTests.cs b/conformance/keyed-redeclaration-csharp/KeyedRedeclarationTests.cs index aafdbcca..0acbbb5b 100644 --- a/conformance/keyed-redeclaration-csharp/KeyedRedeclarationTests.cs +++ b/conformance/keyed-redeclaration-csharp/KeyedRedeclarationTests.cs @@ -15,40 +15,6 @@ public class KeyedRedeclarationTests _ => throw new ArgumentException("Unknown keyed model object") }); - [Fact] - public void IdenticalParentLookupsShareOneStorageThroughEveryProjection() - { - var warehouse = Specimen(); - IStockOwner stock = warehouse; - IBackupOwner backup = warehouse; - ICombinedStock combined = warehouse; - IReadOnlyCombinedStock view = warehouse.AsReadOnly(); - StockEntry first = combined.FindItemsBySku("A")!; - Assert.Same(warehouse.Items, stock.Items); - Assert.Same(stock.Items, backup.Items); - Assert.Same(stock.Items, combined.Items); - Assert.Same(first, warehouse.Items[0]); - Assert.Same(first.AsReadOnly(), view.FindItemsBySku("A")); - Assert.Same(first.AsReadOnly(), warehouse.AsReadOnly().FindItemsBySku("A")); - Assert.Throws(() => first.Sku = "B"); - Assert.Same(first, stock.FindItemsBySku("A")); - first.Sku = "C"; - Assert.Same(first, backup.FindItemsBySku("C")); - - var separate = StandardStock.NewBuilder().WithItems([Entry("other", "other")]).Build(); - using var separateJson = JsonDocument.Parse(ModelSnapshot.Write(separate)); - Assert.True(separateJson.RootElement.TryGetProperty("stock", out _)); - Assert.False(separateJson.RootElement.TryGetProperty("receipts", out _)); - separate.Items.Add(first); - Assert.Null(combined.FindItemsBySku("C")); - Assert.Same(first, separate.FindItemsBySku("C")); - - var direct = DirectStock.NewBuilder().WithItems([Entry("direct", "D")]).Build(); - using var directJson = JsonDocument.Parse(ModelSnapshot.Write(direct)); - Assert.True(directJson.RootElement.TryGetProperty("direct_stock", out _)); - Assert.Same(direct.Items[0].AsReadOnly(), direct.AsReadOnly().FindItemsBySku("D")); - } - [Fact] public void RedeclarationChangesSnapshotNameAndRetainsLogicalJournalProperty() { diff --git a/conformance/named-inverse-csharp/ProjectedRelationshipTests.cs b/conformance/named-inverse-csharp/ProjectedRelationshipTests.cs index e544ead5..7e2e08a2 100644 --- a/conformance/named-inverse-csharp/ProjectedRelationshipTests.cs +++ b/conformance/named-inverse-csharp/ProjectedRelationshipTests.cs @@ -18,15 +18,6 @@ public class ProjectedRelationshipTests _ => throw new ArgumentException("Unknown connector journal object") }); - [Fact] - public void AbstractGetterProjectsTheSameInitializedOwningList() - { - var flow = Specimen(); - VerifyGraph(flow); - VerifyGraph(ModelSnapshot.ReadXml(ModelSnapshot.WriteXml(flow))); - VerifyGraph(ModelSnapshot.ReadYaml(ModelSnapshot.WriteYaml(flow))); - } - [Fact] public void TransferViaBaseGetterReplaysV1AgainstFreshJavaAndCSharpCheckpoints() { diff --git a/conformance/ordinary-containment-csharp/BulkListAliasTests.cs b/conformance/ordinary-containment-csharp/BulkListAliasTests.cs index 4fadc32e..e500d9b2 100644 --- a/conformance/ordinary-containment-csharp/BulkListAliasTests.cs +++ b/conformance/ordinary-containment-csharp/BulkListAliasTests.cs @@ -122,77 +122,6 @@ public void UndoUsesContiguousRunsUnlessAnOwningAliasMustBeRestored(bool owning, Assert.Same(source, second.Owner); } - [Fact] - public void OwningBulkObserverFailuresPreserveOtherInversesAndNestedEdits() - { - var (source, first, second, spare) = NewGraph(spareBetweenMatches: true); - var children = source.Children; - var destination = new ValueMatchedList(); - var inserted = new ValueMatchedCard { Id = "inserted", Caption = "inserted" }; - var trace = new List(); - var firstFailure = new InvalidOperationException("first inverse"); - var secondFailure = new InvalidOperationException("second inverse"); - var listFailure = new InvalidOperationException("list observer"); - using var firstObserver = first.VmfChanges.AddPropertyListener("owner", _ => - { - if (first.Owner is not null) return; - Assert.Same(spare, Assert.Single(children)); - Assert.Same(source, second.Owner); - trace.Add("first inverse"); - Assert.Throws(() => children.RemoveAll([spare])); - trace.Add("guarded"); - destination.Children.Add(first); - trace.Add("adopted"); - throw firstFailure; - }); - using var secondObserver = second.VmfChanges.AddPropertyListener("owner", _ => - { - Assert.Null(second.Owner); - trace.Add("second inverse"); - throw secondFailure; - }); - using var listObserver = children.AddListener(change => - { - if (change.Removed.Count != 0) - { - trace.Add("first removal"); - children.Add(inserted); - throw listFailure; - } - trace.Add("first insertion"); - }); - using var laterObserver = children.AddListener(change => - { - if (change.Removed.Count != 0) - { - Assert.Equal(new[] { 0, 2, 3 }, change.Removed.Select(slot => slot.Index)); - Assert.Same(first, change.Removed[0].Value); - Assert.Same(second, change.Removed[1].Value); - Assert.Null(change.Removed[2].Value); - Assert.Equal(2, children.Count); - Assert.Same(inserted, children[1]); - trace.Add("later removal"); - } - else - { - trace.Add("later insertion"); - } - }); - var error = Assert.Throws(() => children.RemoveAll([second.AsReadOnly(), null])); - Assert.Same(firstFailure, error); - Assert.Equal(new Exception[] { secondFailure, listFailure }, ModelChanges.GetSuppressedObserverExceptions(error)); - Assert.Equal(new[] - { - "first inverse", "guarded", "adopted", "second inverse", - "first removal", "first insertion", "later insertion", "later removal" - }, trace); - Assert.Same(destination, first.Owner); - Assert.Same(first, Assert.Single(destination.Children)); - Assert.Null(second.Owner); - Assert.Same(spare, children[0]); - Assert.Same(source, inserted.Owner); - } - [Fact] public void ReciprocalIdentityListDoesNotNormalizeTheHeldViewForBulkMatching() { @@ -216,47 +145,6 @@ public void ReciprocalIdentityListDoesNotNormalizeTheHeldViewForBulkMatching() Assert.Equal(new[] { 0, 2 }, Assert.Single(edits).Removed.Select(pair => pair.Index)); } - [Fact] - public void InstanceProjectionIdentityIsIndependentOfModelListLookup() - { - var archive = new Eu.Mihosoft.Vmf.Conformance.Values.ArchiveNode(); - var node = new Eu.Mihosoft.Vmf.Conformance.Values.ArchiveNode(); - var alias = node.AsReadOnly(); - Assert.Same(alias, node.AsReadOnly()); - Assert.True(alias.Equals(alias)); - Assert.False(alias.Equals(node)); - Assert.False(node.Equals(alias)); - Assert.Equal(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(alias), alias.GetHashCode()); - - var trail = archive.Trail; - trail.AddRange([node, null, node]); - var projected = archive.AsReadOnly().Trail; - Assert.Same(alias, projected[0]); - Assert.Contains(alias, projected); - Assert.Same(alias, projected[2]); - Assert.True(trail.Contains(alias)); - Assert.Equal(0, trail.IndexOf(alias)); - Assert.False(trail.RemoveAll([alias])); - Assert.True(trail.Remove(alias)); - Assert.True(trail.Remove(alias)); - Assert.Null(Assert.Single(trail)); - - var parent = new LegacyContainer(); - var child = new LegacyChild(); - var childAlias = child.AsReadOnly(); - parent.Children.Add(child); - Assert.True(parent.Children.Contains(childAlias)); - Assert.Contains(childAlias, parent.AsReadOnly().Children); - Assert.True(parent.Children.Remove(childAlias)); - Assert.Null(child.Owner); - - var values = new Eu.Mihosoft.Vmf.Conformance.Values.CollectionProfile().Messages; - values.AddRange(["value", null]); - Assert.Contains(new string("value"), values); - Assert.True(values.Remove(new string("value"))); - Assert.Null(Assert.Single(values)); - } - [Theory] [InlineData(true)] [InlineData(false)] @@ -314,54 +202,6 @@ ModelCollectionChange Record(Action edit) } } - [Fact] - public void StructuralOwningReplayReportsAndDetachesTheReceiversOwnChild() - { - var source = new ValueMatchedList(); - source.Children.Add(null); - var target = new LegacyContainer(); - var child = new LegacyChild(); - target.Children.Add(child); - source.VmfChanges.Start(); - source.Children.RemoveAt(0); - source.VmfChanges.Stop(); - var removal = Assert.Single(source.VmfChanges.History); - - var events = new List>(); - using (target.Children.AddListener(events.Add)) - { - removal.Apply(target); - } - Assert.Empty(target.Children); - Assert.Null(child.Owner); - Assert.Same(child, Assert.Single(Assert.Single(events).Removed).Value); - } - - [Fact] - public void OrdinaryOppositeCanUndoBulkRemovalWhenTheRemovedIdentityIsAlreadyPresent() - { - var member = new Eu.Mihosoft.Vmftest.Referenceends.Member(); - var restored = new Eu.Mihosoft.Vmftest.Referenceends.Team(); - var replaced = new Eu.Mihosoft.Vmftest.Referenceends.Team(); - var teams = member.Teams; - teams.AddRange([restored, replaced]); - - var changes = member.VmfChanges; - changes.Start(); - Assert.True(teams.RemoveAll([restored])); - changes.Stop(); - var removal = Assert.Single(changes.History); - teams[0] = restored; - - Assert.True(removal.CanUndo); - Assert.True(removal.Undo()); - Assert.Equal(2, teams.Count); - Assert.Same(restored, teams[0]); - Assert.Same(restored, teams[1]); - Assert.Same(member, Assert.Single(restored.Members)); - Assert.Empty(replaced.Members); - } - [Fact] public void SharedShallowSequencePublishesTheSparseRemovalToBothOwners() { @@ -378,32 +218,6 @@ public void SharedShallowSequencePublishesTheSparseRemovalToBothOwners() Assert.Equal(new[] { 0, 1, 2, 4 }, Assert.IsType(Assert.Single(secondWatch)).Removed.Select(pair => pair.Index!.Value)); } - [Fact] - public void SparseReferenceAndOwnershipFiltersRoundTripTheSameV1Positions() - { - const string checkpoint = "bulk-filter"; - var binding = new JournalBinding("ordinary-list-bulk", 1, value => value is ValueMatchedCard card ? card.Id! : "list"); - var (graph, _, second, spare) = NewGraph(); - string saved = ModelSnapshot.Write(graph); - using var recorder = JournalRecorder.Start(graph, ModelSnapshot.Registry, binding, checkpoint, 20); - Assert.True(graph.References.RemoveAll([second.AsReadOnly(), null])); - Assert.NotNull(recorder.PublishFrame()); - Assert.True(graph.Children.RemoveAll([second.AsReadOnly(), null])); - var journal = JournalJson.Read(JournalJson.Write(recorder.Finish())); - Assert.Equal(1, journal.WireVersion); - Assert.Equal(new[] { 0, 1, 2, 4 }, Assert.IsType(Assert.Single(journal.Transactions[0].Operations)).Indices); - Assert.Equal(new[] { 0, 1, 2 }, Assert.IsType(Assert.Single(journal.Transactions[1].Operations)).Indices); - - var baseline = ModelSnapshot.Read(saved); - var replayed = JournalReplayer.Replay(baseline, binding, checkpoint, journal, ModelSnapshot.Registry); - var replayedSpare = Assert.IsType(Assert.Single(replayed.Children)); - Assert.Same(replayedSpare, Assert.Single(replayed.References)); - Assert.Same(replayed, replayedSpare.Owner); - Assert.Equal(spare.Id, replayedSpare.Id); - Assert.Equal(4, baseline.Children.Count); - Assert.Same(baseline.Children[0], baseline.References[4]); - } - private static (ValueMatchedList Graph, ValueMatchedCard First, ValueMatchedCard Second, ValueMatchedCard Spare) NewGraph( bool spareBetweenMatches = false) { diff --git a/conformance/ordinary-containment-csharp/OrdinaryContainmentTests.cs b/conformance/ordinary-containment-csharp/OrdinaryContainmentTests.cs index 0d5b4ea2..9f94b3fc 100644 --- a/conformance/ordinary-containment-csharp/OrdinaryContainmentTests.cs +++ b/conformance/ordinary-containment-csharp/OrdinaryContainmentTests.cs @@ -447,26 +447,6 @@ static void TransferFirstChild(LegacyLayout graph) => graph.Containers[1].Children.Add(graph.Containers[0].Children[0]); } - [Fact] - public void UnevenNativeReinsertionRecordsExistingRemoveAndAddOperations() - { - var checkpoint = Fixture("plain"); - var working = ModelSnapshot.Reflection.DeepCopy(checkpoint); - var journal = JournalRecorder.RecordFrame(working, ModelSnapshot.Registry, Binding, - "checkpoint", 0, model => - { - var children = model.Containers[0].Children; - children.AddRange([new LegacyChild { Name = "c" }, children[1]]); - }); - Assert.Equal(1, journal.WireVersion); - Assert.Equal(new[] { JournalListEditKind.Remove, JournalListEditKind.Add }, - Assert.Single(journal.Transactions).Operations.OfType().Select(edit => edit.Kind)); - var replayed = JournalReplayer.Replay(checkpoint, Binding, "checkpoint", journal, ModelSnapshot.Registry); - Assert.Equal(new string?[] { null, "a", "c", "b" }, replayed.Containers[0].Children.Select(entry => entry?.Name)); - Assert.All(replayed.Containers[0].Children.OfType(), - child => Assert.Same(replayed.Containers[0], child.Owner)); - } - [Theory] [InlineData(false)] [InlineData(true)] diff --git a/conformance/ordinary-containment-csharp/OrdinaryOwningBuilderTests.cs b/conformance/ordinary-containment-csharp/OrdinaryOwningBuilderTests.cs index 5183e90b..5e8b2605 100644 --- a/conformance/ordinary-containment-csharp/OrdinaryOwningBuilderTests.cs +++ b/conformance/ordinary-containment-csharp/OrdinaryOwningBuilderTests.cs @@ -54,46 +54,6 @@ public void UnorderedBuilderReplacementPublishesMembershipAndKeepsBoundsForValid Assert.Equal("/volumes", Assert.Single(target.Validate()).ModelPath); } - [Fact] - public void SameSourceAppendKeepsBothOwningAliasesAndAppendsANullSlot() - { - var source = BuilderSource(); - var list = source.Children; - var repeated = list[0]!; - var events = new List(); - using var listener = Watch(source, "source", events); - - var staged = LegacyContainer.NewBuilder().ApplyFrom(source); - Assert.Empty(events); - Assert.Same(source, repeated.Owner); - staged.ApplyTo(source); - - Assert.Same(list, source.Children); - Assert.Equal(["null", "a", "null", "b", "a"], Names(source)); - Assert.Same(repeated, list[1]); - Assert.Same(repeated, list[4]); - Assert.Same(source, repeated.Owner); - Assert.Equal(["source:[]:[0]"], events); - } - - [Fact] - public void SameSourceReplacementCopiesSlotsThroughOrdinaryInsertion() - { - var source = BuilderSource(); - var list = source.Children; - var repeated = list[0]!; - var events = new List(); - using var listener = Watch(source, "source", events); - - LegacyContainer.NewBuilder().AppendCollections(false).ApplyFrom(source).ApplyTo(source); - - Assert.Same(list, source.Children); - Assert.Equal(["null", "b", "a"], Names(source)); - Assert.Same(repeated, list[2]); - Assert.Same(source, repeated.Owner); - Assert.Equal(["source:[0, 1, 2, 3]:[]", "source:[]:[0, 1, 2]"], events); - } - [Fact] public void DistinctReplacementTransfersTheOriginalChildrenAndKeepsLiveLists() { @@ -144,32 +104,6 @@ public void InvalidCycleLeavesTheGraphAndEarlierBuilderPropertiesUnchanged(bool Assert.Same(branch, leaf.__vmfContainerLink.Owner); } - [Fact] - public void ReplacementRechecksAContainmentCycleIntroducedByAnEarlierObserver() - { - var root = new BuilderCycleNode(); - var target = new BuilderCycleNode { Caption = "branch" }; - var leaf = new BuilderCycleNode(); - target.Children.Add(leaf); - var events = new List(); - using var list = target.Children.AddListener(_ => events.Add("children")); - using var listener = target.VmfChanges.AddPropertyListener("caption", change => - { - events.Add(change.PropertyName); - root.Children.Add(target); - }); - var staged = BuilderCycleNode.NewBuilder().WithCaption("changed").WithChildren([root]).AppendCollections(false); - - Assert.Throws(() => staged.ApplyTo(target)); - - Assert.Equal(["caption"], events); - Assert.Equal("changed", target.Caption); - Assert.Same(target, Assert.Single(root.Children)); - Assert.Same(leaf, Assert.Single(target.Children)); - Assert.Same(root, target.__vmfContainerLink.Owner); - Assert.Same(target, leaf.__vmfContainerLink.Owner); - } - private static LegacyContainer BuilderSource() { var source = LegacyContainer.NewBuilder().WithName("source") diff --git a/conformance/ordinary-containment-csharp/OwningPredicateTests.cs b/conformance/ordinary-containment-csharp/OwningPredicateTests.cs index ae76b773..d5f97c1d 100644 --- a/conformance/ordinary-containment-csharp/OwningPredicateTests.cs +++ b/conformance/ordinary-containment-csharp/OwningPredicateTests.cs @@ -15,39 +15,6 @@ public class OwningPredicateTests _ => throw new ArgumentException("Unexpected predicate model.", nameof(model)), }); - [Fact] - public void PredicateRemovalAndUndoUseOriginalPositionsWithoutDetachingTheRetainedAlias() - { - var graph = Fixture(); - var owner = graph.Containers[0]; - var alias = graph.Featured!; - var cut = owner.Children[3]!; - owner.Children[0] = alias; - var delivered = new List(); - using var aliasInverse = alias.VmfChanges.AddPropertyListener("owner", _ => delivered.Add("alias")); - using var cutInverse = cut.VmfChanges.AddPropertyListener("owner", - _ => delivered.Add(cut.Owner is null ? "cut:detach" : "cut:attach")); - using var view = owner.AsReadOnly().Children.AddListener(edit => delivered.Add("view:" + Slots(edit))); - using var writable = owner.Children.AddListener(edit => delivered.Add("mutable:" + Slots(edit))); - owner.VmfChanges.Start(); - RemoveEnds(owner); - var edit = Assert.IsType(Assert.Single(owner.VmfChanges.History)); - owner.VmfChanges.Stop(); - CheckFinal(graph); - Assert.Null(cut.Owner); - Assert.Equal(["cut:detach", "view:[0,3]/[]", "mutable:[0,3]/[]"], delivered); - delivered.Clear(); - Assert.True(edit.Undo()); - Assert.Collection(owner.Children, item => Assert.Same(alias, item), Assert.Null, - item => Assert.Same(alias, item), item => Assert.Same(cut, item)); - Assert.Same(owner, cut.Owner); - Assert.Equal(["cut:attach", "view:[]/[0,3]", "mutable:[]/[0,3]"], delivered); - delivered.Clear(); - Assert.True(edit.Redo()); - Assert.Equal(["cut:detach", "view:[0,3]/[]", "mutable:[0,3]/[]"], delivered); - CheckFinal(graph); - } - [Fact] public void PredicateFailureIsSilentAndTheTemporaryAliasExchangeReplaysInOneFrame() { diff --git a/conformance/ordinary-containment-csharp/OwningReplacementTests.cs b/conformance/ordinary-containment-csharp/OwningReplacementTests.cs index 125ac239..e2152e7f 100644 --- a/conformance/ordinary-containment-csharp/OwningReplacementTests.cs +++ b/conformance/ordinary-containment-csharp/OwningReplacementTests.cs @@ -65,70 +65,6 @@ public void TransferReplacementDeliversItsFullRangeAndReplaysBothProducers() } } - [Fact] - public void AliasesRemainAttachedAndNativeUndoRestoresTheNullAndAliasPositions() - { - var owner = new LegacyContainer { Name = "owner" }; - var alias = new LegacyChild { Name = "alias" }; - owner.Children.AddRange([new LegacyChild { Name = "placeholder" }, null, alias]); - owner.Children[0] = alias; - int index = 0; - owner.VmfChanges.Start(); - owner.Children.ReplaceAll(child => index++ == 0 ? null : child); - var edit = Assert.IsType(Assert.Single(owner.VmfChanges.History)); - owner.VmfChanges.Stop(); - Assert.Same(owner, alias.Owner); - Assert.Null(owner.Children[0]); - Assert.Same(alias, owner.Children[2]); - Assert.True(edit.Undo()); - Assert.Same(alias, owner.Children[0]); - Assert.Null(owner.Children[1]); - Assert.Same(alias, owner.Children[2]); - Assert.True(edit.Redo()); - Assert.Same(owner, alias.Owner); - Assert.Null(owner.Children[0]); - } - - [Fact] - public void RejectedTransformCycleAndKeyLeaveTheOriginalOwnershipIntact() - { - var graph = Fixture(); - var source = graph.Containers[0]; - var target = graph.Containers[1]; - var leaving = target.Children[0]!; - var moving = source.Children[0]!; - var observed = new List(); - using var sourceWatch = source.Children.AddListener(_ => observed.Add("source")); - using var targetWatch = target.Children.AddListener(_ => observed.Add("target")); - Assert.Throws(() => target.Children.ReplaceAll(value => value is null - ? throw new InvalidOperationException("transform failed") : moving)); - Assert.Same(leaving, target.Children[0]); - Assert.Same(target, leaving.Owner); - Assert.Same(moving, Assert.Single(source.Children)); - Assert.Same(source, moving.Owner); - Assert.Empty(observed); - - var root = new BuilderCycleNode(); - var leaf = new BuilderCycleNode(); - root.Children.Add(leaf); - Assert.Throws(() => root.Children.ReplaceAll(_ => root)); - Assert.Same(leaf, Assert.Single(root.Children)); - - var room = new ReadingRoom(); - var first = new Shelf { Name = "first" }; - var second = new Shelf { Name = "second" }; - room.Shelves.AddRange([first, second]); - using var keyedWatch = room.Shelves.AddListener(edit => observed.Add(Slots(edit))); - Assert.Throws(() => room.Shelves.ReplaceAll(value => ReferenceEquals(value, first) - ? new Shelf { Name = second.Name } : value)); - Assert.Empty(observed); - Assert.Same(first, room.FindShelvesByName("first")); - room.Shelves.ReplaceAll(value => ReferenceEquals(value, first) ? second : first); - Assert.Equal(["[0,1]/[0,1]"], observed); - Assert.Same(second, room.Shelves[0]); - Assert.Same(second, room.FindShelvesByName("second")); - } - [Fact] public void EmptyOwningReplacementHasNoNativeOrPortableEdit() { diff --git a/conformance/ordinary-containment-csharp/SharedInverseTests.cs b/conformance/ordinary-containment-csharp/SharedInverseTests.cs index d41ca90d..87ca188c 100644 --- a/conformance/ordinary-containment-csharp/SharedInverseTests.cs +++ b/conformance/ordinary-containment-csharp/SharedInverseTests.cs @@ -49,93 +49,6 @@ public void OneReadOnlyInverseFollowsNamedSlotsAndCurrentOwnerIdentity() Assert.Same(first, twig.Parent); } - [Fact] - public void TransactionUndoRestoresTheOriginalNamedSlotAndInverse() - { - var model = Checkpoint(); - var child = model.Roots[0]!.Left; - var changes = model.VmfChanges; - changes.Start(); - changes.StartTransaction(); - MoveChild(model); - var transaction = changes.PublishTransaction(); - changes.Stop(); - CheckMoved(model); - - Assert.True(transaction!.Undo()); - CheckInitial(model); - Assert.Same(child, model.Roots[0]!.Left); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ClearingASingularSlotReportsOneOwningEditThroughEveryScope(bool anonymous) - { - var model = anonymous ? DetachCheckpoint() : Checkpoint(); - var owner = model.Roots[0]!; - var child = (anonymous ? owner.Staging : owner.Left)!; - var name = anonymous ? "staging" : "left"; - var view = owner.AsReadOnly(); - var local = new List(); - var named = new List(); - var recursive = new List(); - var inverse = new List(); - var readOnly = new List(); - var readOnlyAncestor = new List(); - var changes = model.VmfChanges; - var viewChanges = view.VmfChanges; - using (owner.VmfChanges.AddLocalListener(local.Add)) - using (owner.VmfChanges.AddPropertyListener(name, named.Add)) - using (changes.AddRecursiveListener(recursive.Add)) - using (child.VmfChanges.AddLocalListener(inverse.Add)) - using (viewChanges.AddRecursiveListener(readOnly.Add)) - using (model.AsReadOnly().VmfChanges.AddRecursiveListener(readOnlyAncestor.Add)) - { - changes.Start(); - viewChanges.Start(); - Clear(); - viewChanges.Stop(); - changes.Stop(); - } - Assert.Empty(readOnlyAncestor); - var group = Assert.Single(changes.Transactions); - foreach (var events in new IReadOnlyList[] { local, named, recursive, changes.History, group.Changes }) - { - var edit = Assert.Single(events); - Assert.Same(owner, edit.Source); - Assert.Equal(name, edit.PropertyName); - Assert.Same(child, edit.OldValue); - Assert.Null(edit.NewValue); - } - foreach (var events in new IReadOnlyList[] - { readOnly, viewChanges.History, Assert.Single(viewChanges.Transactions).Changes }) - { - var edit = Assert.Single(events); - Assert.Same(view, edit.Source); - Assert.Equal(name, edit.PropertyName); - Assert.Same(child.AsReadOnly(), edit.OldValue); - Assert.Null(edit.NewValue); - } - var inverseEdit = Assert.Single(inverse); - Assert.True(inverseEdit.IsInverse); - Assert.Same(child, inverseEdit.Source); - Assert.Equal(anonymous ? "__vmf_prop_unnamed_container" : "parent", inverseEdit.PropertyName); - Assert.Same(owner, inverseEdit.OldValue); - Assert.Null(inverseEdit.NewValue); - CheckDetached(model); - Assert.Null(child.Parent); - Assert.True(group.Undo()); - Assert.Same(child, anonymous ? owner.Staging : owner.Left); - Assert.Same(anonymous ? null : owner, child.Parent); - - void Clear() - { - if (anonymous) owner.Staging = null; - else owner.Left = null; - } - } - [Theory] [InlineData("json")] [InlineData("yaml")] diff --git a/conformance/ordinary-containment-csharp/UnorderedContainmentTests.cs b/conformance/ordinary-containment-csharp/UnorderedContainmentTests.cs index f17bd5e6..9f6f8497 100644 --- a/conformance/ordinary-containment-csharp/UnorderedContainmentTests.cs +++ b/conformance/ordinary-containment-csharp/UnorderedContainmentTests.cs @@ -13,36 +13,6 @@ public class UnorderedContainmentTests _ => "room", }); - [Fact] - public void IdentityMembershipHasLiveReadOnlyAndValidatedOwnership() - { - var model = Checkpoint(); - var source = model.Shelves[0]!; - var peer = new Volume { Name = "A" }; - Assert.False(source.Volumes.Add(model.Featured!)); - Assert.Throws(() => source.Volumes.AddRange([peer, null!])); - Assert.Null(peer.Shelf); - Assert.Equal(2, source.Volumes.Count); - var view = source.AsReadOnly(); - Assert.True(source.Volumes.Add(peer)); - Assert.True(view.Volumes.Contains(peer.AsReadOnly())); - Assert.Equal("/shelves/0/volumes", Assert.Single(model.Validate()).ModelPath); - Assert.True(source.Volumes.Remove(peer)); - Assert.Null(peer.Shelf); - Assert.Empty(model.Validate()); - Assert.False(ModelSnapshot.Reflection.Reflect(source).FindProperty("volumes")!.IsOrdered); - - var copy = ModelSnapshot.Reflection.DeepCopy(model); - CheckCheckpoint(copy); - Assert.NotSame(model.Featured, copy.Featured); - var other = copy.Shelves[0]!; - var first = Named(other, "A"); - other.Volumes.Remove(first); - other.Volumes.Add(first); - Assert.True(model.ContentEquals(copy)); - Assert.Equal(model.ContentHashCode(), copy.ContentHashCode()); - } - [Fact] public void LocalHistoryAndGraphPatchReuseTheTransferredIdentity() { diff --git a/conformance/ordinary-containment-csharp/ValueMatchingAliasTests.cs b/conformance/ordinary-containment-csharp/ValueMatchingAliasTests.cs index b73ecbb2..69493d68 100644 --- a/conformance/ordinary-containment-csharp/ValueMatchingAliasTests.cs +++ b/conformance/ordinary-containment-csharp/ValueMatchingAliasTests.cs @@ -58,19 +58,6 @@ void Verify(string saved, string edits) } } - [Fact] - public void SharedShallowReferenceListRetainsItsReadOnlyAliasResolver() - { - var first = new ValueMatchedCard { Id = "first", Caption = "same" }; - var second = new ValueMatchedCard { Id = "second", Caption = "same" }; - var source = new ValueMatchedList(); - source.References.AddRange([first, second]); - var copy = ModelSnapshot.Reflection.ShallowCopy(source); - Assert.Same(source.References, copy.References); - Assert.True(copy.References.Remove(second.AsReadOnly())); - Assert.Same(second, Assert.Single(source.References)); - } - private static ValueMatchedList CreateCheckpoint() { var first = new ValueMatchedCard { Id = "first", Caption = "same" }; diff --git a/conformance/redeclaration-csharp/RedeclarationTests.cs b/conformance/redeclaration-csharp/RedeclarationTests.cs index 35a2ded7..05b71ce7 100644 --- a/conformance/redeclaration-csharp/RedeclarationTests.cs +++ b/conformance/redeclaration-csharp/RedeclarationTests.cs @@ -7,105 +7,6 @@ namespace Vmf.CSharp.Conformance; public class RedeclarationTests { - [Fact] - public void MixedTraitPromotesOnlyTheConcreteSetterAndKeepsItsCollectionLive() - { - var concrete = new Settings(); - MixedSettings trait = concrete; - Assert.False(typeof(MixedSettings).GetProperty(nameof(trait.Name))?.SetMethod?.IsPublic == true); - Assert.True(typeof(MixedSettings).GetProperty(nameof(trait.Level))?.SetMethod?.IsPublic == true); - Assert.True(typeof(Settings).GetProperty(nameof(concrete.Name))?.SetMethod?.IsPublic == true); - trait.Level = 3; - trait.Measures.Add(7); - Assert.Equal(3, concrete.Level); - Assert.Equal([7], concrete.Measures); - - var view = concrete.AsReadOnly(); - var name = ModelSnapshot.Reflection.Reflect(concrete).FindProperty("name")!; - var readOnlyName = ModelSnapshot.Reflection.Reflect(view).FindProperty("name")!; - Assert.True(name.CanWrite); - Assert.False(readOnlyName.CanWrite); - Assert.Equal("display_name", name.WireName); - Assert.Equal("origin", name.DefaultValue); - var edits = new List(); - using var subscription = concrete.VmfChanges.AddPropertyListener("name", change => edits.Add(change.NewValue)); - concrete.Name = "assigned"; - name.Set("reflected"); - Assert.True(name.IsSet); - Assert.Equal("reflected", trait.Name); - Assert.Equal("reflected", view.Name); - Assert.Throws(() => readOnlyName.Set("blocked")); - name.Reset(); - Assert.False(name.IsSet); - Assert.Equal("origin", view.Name); - Assert.Equal(new[] { "assigned", "reflected", "origin" }, edits); - } - - [Fact] - public void RedeclarationLayersDefaultsAndValidationOverOnePhysicalSlot() - { - var derived = Reconfigured.NewBuilder().WithName("from builder").WithLevel(6).Build(); - Settings asBase = derived; - MixedSettings asTrait = derived; - Assert.Equal("from builder", asBase.Name); - Assert.Equal(6, asTrait.Level); - asBase.Name = "via base"; - asBase.Level = 8; - Assert.Equal("via base", derived.Name); - Assert.Equal(8, derived.Level); - - var fields = ModelSnapshot.Reflection.Reflect(derived); - var name = Assert.Single(fields.Properties, property => property.Name == "name"); - var level = Assert.Single(fields.Properties, property => property.Name == "level"); - Assert.Equal("name", name.WireName); - Assert.EndsWith(".Reconfigured", name.DeclaringType); - Assert.Equal("reconfigured", name.DefaultValue); - Assert.Equal(4, level.DefaultValue); - name.Reset(); - level.Reset(); - Assert.Equal("reconfigured", asTrait.Name); - Assert.Equal(4, asBase.Level); - Assert.False(name.IsSet); - Assert.False(level.IsSet); - asBase.Level = 1; - Assert.Single(derived.Validate(), issue => issue.ModelCode == "vmf.range" && issue.ModelPath == "/level"); - asBase.Level = 0; - var issues = derived.Validate(); - Assert.Equal(2, issues.Count); - Assert.All(issues, issue => - { - Assert.Equal("vmf.range", issue.ModelCode); - Assert.Equal("/level", issue.ModelPath); - }); - - var implicitDefaults = new Unconfigured(); - Assert.Null(implicitDefaults.Name); - Assert.Equal(0, implicitDefaults.Level); - var explicitNull = new ExplicitNull(); - Assert.Null(explicitNull.Name); - var explicitField = ModelSnapshot.Reflection.Reflect(explicitNull).FindProperty("name")!; - Assert.Equal("optional_name", explicitField.WireName); - explicitField.Set("present"); - explicitField.Reset(); - Assert.Null(explicitNull.Name); - } - - [Fact] - public void ImmutableRedeclarationsPassTheEffectiveValueToTheirBaseConstructor() - { - FrozenSetting original = FrozenSetting.NewBuilder().Build(); - FrozenSetting revised = RevisedSetting.NewBuilder().Build(); - Assert.Equal("original", original.Label); - Assert.Equal(0, original.Limit); - Assert.Null(revised.Label); - Assert.Equal(6, revised.Limit); - var label = Assert.Single(ModelSnapshot.Reflection.Reflect(revised).Properties, field => field.Name == "label"); - Assert.Equal("caption", label.WireName); - Assert.Null(label.DefaultValue); - Assert.False(label.CanWrite); - Assert.Equal(0, new RevisedSetting(limit: 0).Limit); - Assert.Null(new FrozenSetting(label: new OptionalValue(null)).Label); - } [Fact] public void SchemaPreservesBothRangesOnARedeclaredScalar() diff --git a/conformance/redeclaration-csharp/ValueChoiceTests.cs b/conformance/redeclaration-csharp/ValueChoiceTests.cs index 570cc27e..624e8689 100644 --- a/conformance/redeclaration-csharp/ValueChoiceTests.cs +++ b/conformance/redeclaration-csharp/ValueChoiceTests.cs @@ -69,43 +69,6 @@ public void ConcreteBranchesPreserveExistingSnapshotAndJournalSemantics(string f File.WriteAllText(PathFor("csharp", "journal"), log); } - [Fact] - public void UnownedModelAlternativeKeepsByValueOmissionAndReferenceValidation() - { - var value = new ObjectOption { Value = new OptionObject() }; - Assert.Same(value.Value, ((ValueChoice)value).Value); - Assert.False(typeof(ValueChoice).GetProperty(nameof(ValueChoice.Value))!.CanWrite); - Assert.Null(JsonNode.Parse(ModelSnapshot.WriteWithoutReferences(value, global::Vmf.Runtime.ReferenceMode.Omit))!["value"]); - Assert.Throws(() => ModelSnapshot.Write(value)); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ImportedUntypedObjectsCompareByMapAndListContents(bool references) - { - const string left = """{"value":{"items":[1,null,-0.0,9007199254740993],"flag":true}}"""; - const string right = """{"value":{"flag":true,"items":[1,null,-0.0,9007199254740993]}}"""; - var reflection = ModelSnapshot.Reflection; - NullOption Read(string json) => references ? ModelSnapshot.Read(json) - : ModelSnapshot.ReadWithoutReferences(json); - var first = Read(left); - var second = Read(right); - var firstView = first.AsReadOnly(); - var secondView = second.AsReadOnly(); - Assert.NotSame(first.Value, second.Value); - Assert.True(reflection.ContentEquals(first, second)); - Assert.True(reflection.ContentEquals(second, first)); - Assert.True(reflection.ContentEquals(firstView, secondView)); - Assert.Equal(reflection.ContentHashCode(first), reflection.ContentHashCode(secondView)); - - foreach (string different in new[] { right.Replace("-0.0", "0.0"), right.Replace("[1,", "[1.0,"), - right.Replace("1,null", "null,1"), right.Replace("9007199254740993", "9007199254740992") }) - { - Assert.False(reflection.ContentEquals(firstView, Read(different))); - } - } - [Fact] public void NonportableCyclicObjectValuesKeepTheirHostEquality() { diff --git a/conformance/reference-default-csharp/ComposedReferenceDefaultsTests.cs b/conformance/reference-default-csharp/ComposedReferenceDefaultsTests.cs index e3bab62c..63628404 100644 --- a/conformance/reference-default-csharp/ComposedReferenceDefaultsTests.cs +++ b/conformance/reference-default-csharp/ComposedReferenceDefaultsTests.cs @@ -5,44 +5,4 @@ namespace Vmf.CSharp.Conformance; public sealed partial class InheritedMixedDefaultsTests { - [Fact] - public void PassiveConcreteRoleSharesTheReferenceDefaultOwnersLifecycle() - { - InheritedMixedDefaultBindings.Events.Clear(); - var owner = new ComposedDefaultSelectionLeaf(); - Calls("ahead", "queue", "summary", "zulu"); - IPassiveConcreteRole role = owner; - DefaultPrimary primary = owner; - var view = owner.AsReadOnly(); - Assert.Equal("north", role.Region); - Assert.Equal("early", owner.Ahead); - Assert.Equal([4, 5], owner.Summary); - Assert.Same(owner.Queue[0], Members(Field(primary, "queue"))[0]); - Assert.Same(owner.Queue[0].AsReadOnly(), Members(Field(view, "queue"))[0]); - Assert.Same(view, role.AsReadOnly()); - role.Region = "south"; - Assert.Equal("south", view.Region); - - var builder = ComposedDefaultSelectionLeaf.NewBuilder(); - Calls("queue", "ahead", "summary", "zulu"); - var built = builder.Build(); - Calls("ahead", "summary", "zulu"); - var empty = builder.WithQueue([]).WithRank(18).Build(); - Calls("ahead", "summary", "zulu"); - Assert.Empty(empty.Queue); - Assert.Same(Field(built, "queue").DefaultValue, Field(empty, "queue").DefaultValue); - Assert.Equal(18, empty.Rank); - Assert.Equal("north", empty.Region); - - var deep = ModelSnapshot.Reflection.DeepCopy(owner); - Calls("ahead", "summary", "zulu"); - var shallow = ModelSnapshot.Reflection.ShallowCopy(owner); - Calls("ahead", "summary", "zulu"); - Assert.Equal("south", deep.Region); - Assert.Equal("south", shallow.Region); - Assert.Same(deep.Queue[0], Members(Field(deep, "queue"))[0]); - Assert.NotSame(owner.Queue[0], deep.Queue[0]); - Assert.Same(Field(primary, "queue").DefaultValue, Field(shallow, "queue").DefaultValue); - Assert.Same(owner.Queue[0], shallow.Queue[0]); - } } diff --git a/conformance/reference-default-csharp/HookReferenceDefaultsTests.cs b/conformance/reference-default-csharp/HookReferenceDefaultsTests.cs index 7bb60254..5cc628be 100644 --- a/conformance/reference-default-csharp/HookReferenceDefaultsTests.cs +++ b/conformance/reference-default-csharp/HookReferenceDefaultsTests.cs @@ -6,47 +6,6 @@ namespace Vmf.CSharp.Conformance; public sealed partial class HookReferenceDefaultsTests { - [Fact] - public void InheritedHookRunsBeforeDefaultsAndCopyShellsKeepItsAddedMembership() - { - HookReferenceDefaultBindings.Events.Clear(); - Assert.Single(new HookSelectionBase().Queue); - Calls("queue", "zulu"); - Initialized(new HookSelection()); - Calls("hook", "earlier", "queue", "zulu"); - var leaf = new HookSelectionLeaf(); - Initialized(leaf); - Calls("hook", "earlier", "queue", "zulu"); - - var staged = HookSelectionLeaf.NewBuilder(); - Calls("queue", "earlier", "zulu"); - var first = staged.Build(); - Initialized(first); - Calls("hook", "earlier", "zulu"); - var empty = staged.WithQueue([]).Build(); - Calls("hook", "earlier", "zulu"); - Assert.Empty(empty.Queue); - Assert.True(Field(empty).IsSet); - Assert.Same(Field(first).DefaultValue, Field(empty).DefaultValue); - Field(empty).Reset(); - Assert.Same(first.Queue[0], Assert.Single(empty.Queue)); - Calls(); - - var deep = ModelSnapshot.Reflection.DeepCopy(leaf); - Calls("hook", "earlier", "zulu"); - var shallow = ModelSnapshot.Reflection.ShallowCopy(leaf); - Calls("hook", "earlier", "zulu"); - foreach (var copy in new[] { deep, shallow }) - { - Assert.Equal(["hook-member", "seed"], copy.Queue.Select(member => member.Code)); - Assert.Same(copy.Queue[1], Fallback(copy)); - Assert.True(Field(copy).IsSet); - } - Assert.NotSame(leaf.Queue[0], deep.Queue[1]); - Assert.Same(leaf.Queue[0], shallow.Queue[1]); - Assert.Same(Field(leaf).DefaultValue, Field(shallow).DefaultValue); - Calls(); - } private static void Initialized(HookSelection owner) { diff --git a/conformance/reference-default-csharp/InheritedMixedDefaultsTests.cs b/conformance/reference-default-csharp/InheritedMixedDefaultsTests.cs index 104748cb..b910f68b 100644 --- a/conformance/reference-default-csharp/InheritedMixedDefaultsTests.cs +++ b/conformance/reference-default-csharp/InheritedMixedDefaultsTests.cs @@ -70,22 +70,6 @@ public void ConstructorsBuildersAndCopiesFollowTheEffectiveJavaProviderOrder() Calls(); } - [Fact] - public void ManagedProvidersAloneAlsoRequireEffectiveConstructorOrder() - { - InheritedMixedDefaultBindings.Events.Clear(); - var model = new ManagedSelectionLeaf(); - Calls("summary", "queue"); - var staged = ManagedSelectionLeaf.NewBuilder(); - Calls("queue", "summary"); - var built = staged.Build(); - Calls("summary"); - var copy = ModelSnapshot.Reflection.DeepCopy(model); - Calls("summary"); - Assert.Equal([4, 5], built.Earlier); - Assert.NotSame(model.Queue[0], copy.Queue[0]); - } - private static ModelProperty Field(object owner, string name) => ModelSnapshot.Reflection.Reflect(owner).FindProperty(name)!; diff --git a/conformance/reference-default-csharp/ProjectedDefaultsTests.cs b/conformance/reference-default-csharp/ProjectedDefaultsTests.cs index 1593b104..7b316aff 100644 --- a/conformance/reference-default-csharp/ProjectedDefaultsTests.cs +++ b/conformance/reference-default-csharp/ProjectedDefaultsTests.cs @@ -6,72 +6,6 @@ namespace Vmf.CSharp.Conformance; public sealed partial class ProjectedDefaultsTests { - private static readonly string[] CopyOrder = ["accent", "ahead", "before", "marks", "numbers", "path", "prunes", "summary", "zulu"]; - - [Fact] - public void SecondaryDefaultProvidersBindOnceAndEachConcreteHostCapturesItsOwnMembership() - { - ProjectedDefaultBindings.Events.Clear(); - var primary = new ProjectionPrimary(); - Calls("before", "numbers", "path"); - var queueRole = new ProjectedQueueRole(); - Calls("queue", "summary", "zulu"); - var favoriteRole = new ProjectedFavoriteRole(); - Calls("accent", "favorites"); - - var calibration = new ProjectedCalibrationRole(); - Calls("marks", "prunes"); - - var owner = new ProjectedDefaultsLeaf(); - Calls("accent", "ahead", "before", "favorites", "marks", "numbers", "path", "prunes", "queue", "summary", "zulu"); - IProjectedQueueRoot queues = owner; - IProjectedFavoriteRoot favorites = owner; - var queueSeed = queues.Queue[0]; - var favoriteSeed = Assert.Single(favorites.Favorites); - Assert.Same(queueSeed, Captured(queues, "queue")[0]); - Assert.Same(favoriteSeed, Assert.Single(Captured(favorites, "favorites"))); - Assert.Same(queueSeed.AsReadOnly(), Captured(queues.AsReadOnly(), "queue")[0]); - Assert.Same(favoriteSeed.AsReadOnly(), Assert.Single(Captured(favorites.AsReadOnly(), "favorites"))); - Assert.NotSame(Captured(queueRole, "queue")[0], queueSeed); - Assert.NotSame(Assert.Single(Captured(favoriteRole, "favorites")), favoriteSeed); - Assert.Equal(primary.Numbers, owner.Numbers); - Assert.Equal([4, 5], owner.Summary); - Assert.Equal(calibration.Marks, owner.Marks); - Assert.Equal(calibration.Prunes, owner.Prunes); - Assert.Equal("before", owner.Before); - Assert.Equal("path", owner.Path); - Assert.Equal("concrete", owner.Label); - Assert.Equal("ahead", owner.Ahead); - - var builder = ProjectedDefaultsLeaf.NewBuilder(); - Calls("favorites", "queue", "accent", "ahead", "before", "marks", "numbers", "path", "prunes", "summary", "zulu"); - var populated = builder.Build(); - Calls(CopyOrder); - var empty = builder.WithQueue([]).WithFavorites([]).WithNotes("configured").WithRank(18).Build(); - Calls(CopyOrder); - Assert.Empty(empty.Queue); - Assert.Empty(empty.Favorites); - Assert.Same(Captured(populated, "queue"), Captured(empty, "queue")); - Assert.Same(Captured(populated, "favorites"), Captured(empty, "favorites")); - Assert.Equal("configured", empty.Notes); - Assert.Equal(18, empty.Rank); - Field(empty, "favorites").Reset(); - Assert.Same(Assert.Single(populated.Favorites), Assert.Single(empty.Favorites)); - Calls(); - - var deep = ModelSnapshot.Reflection.DeepCopy(owner); - Calls(CopyOrder); - var shallow = ModelSnapshot.Reflection.ShallowCopy(owner); - Calls(CopyOrder); - Assert.NotSame(queueSeed, deep.Queue[0]); - Assert.NotSame(favoriteSeed, Assert.Single(deep.Favorites)); - Assert.Same(deep.Queue[0], Captured(deep, "queue")[0]); - Assert.Same(Assert.Single(deep.Favorites), Assert.Single(Captured(deep, "favorites"))); - Assert.Same(queueSeed, shallow.Queue[0]); - Assert.Same(favoriteSeed, Assert.Single(shallow.Favorites)); - Assert.Same(Captured(owner, "queue"), Captured(shallow, "queue")); - Assert.Same(Captured(owner, "favorites"), Captured(shallow, "favorites")); - } private static ModelProperty Field(object owner, string name) => ModelSnapshot.Reflection.Reflect(owner).FindProperty(name)!; diff --git a/conformance/reference-default-csharp/ReferenceDefaultBindings.cs b/conformance/reference-default-csharp/ReferenceDefaultBindings.cs index 51112a93..d1dd18a2 100644 --- a/conformance/reference-default-csharp/ReferenceDefaultBindings.cs +++ b/conformance/reference-default-csharp/ReferenceDefaultBindings.cs @@ -4,13 +4,11 @@ internal static class ReferenceDefaultBindings { internal static int MutableCalls; internal static int ImmutableCalls; - internal static bool DuplicateSeed; internal static IEnumerable Favorites() { MutableCalls++; - var seed = Target("default-favorite"); - return DuplicateSeed ? [seed, seed] : [seed]; + return [Target("default-favorite")]; } internal static IEnumerable Featured() diff --git a/conformance/reference-default-csharp/ReferenceDefaultTests.cs b/conformance/reference-default-csharp/ReferenceDefaultTests.cs index b60d7d4c..499f4ab7 100644 --- a/conformance/reference-default-csharp/ReferenceDefaultTests.cs +++ b/conformance/reference-default-csharp/ReferenceDefaultTests.cs @@ -20,115 +20,6 @@ public class ReferenceDefaultTests _ => throw new ArgumentException("Unregistered reference-default object") }); - [Fact] - public void OwnersAndBuildersCaptureEachDeclaredProviderOnce() - { - int before = ReferenceDefaultBindings.MutableCalls; - var owner = new MutablePicks(); - var favorites = Field(owner, "favorites"); - var fallback = Members(favorites); - var initial = Assert.IsType(Assert.Single(fallback)); - Assert.Same(initial, Assert.Single(owner.Favorites)); - Assert.Same(fallback, favorites.DefaultValue); - Assert.False(favorites.IsSet); - Assert.Throws(() => ((ICollection)fallback).Clear()); - Assert.Same(initial.AsReadOnly(), Assert.Single(Members(Field(owner.AsReadOnly(), "favorites")))); - owner.Favorites.Clear(); - Assert.True(favorites.IsSet); - favorites.Reset(); - Assert.Same(initial, Assert.Single(owner.Favorites)); - Assert.Equal(before + 2, ReferenceDefaultBindings.MutableCalls); - - before = ReferenceDefaultBindings.MutableCalls; - var staged = MutablePicks.NewBuilder().WithFavorites([]); - var first = staged.Build(); - var second = staged.Build(); - Assert.Equal(before + 2, ReferenceDefaultBindings.MutableCalls); - Assert.Empty(first.Favorites); - Assert.Same(Field(first, "favorites").DefaultValue, Field(second, "favorites").DefaultValue); - - before = ReferenceDefaultBindings.ImmutableCalls; - var frozenBuilder = FrozenPicks.NewBuilder(); - var frozen = frozenBuilder.Build(); - var frozenDefault = Members(Field(frozen, "featured")); - Assert.Equal(before + 2, ReferenceDefaultBindings.ImmutableCalls); - Assert.Same(frozenDefault, Field(frozen, "featured").DefaultValue); - Assert.Same(frozenDefault[0], frozen.Featured[0]); - Assert.NotSame(frozen.Featured[0], frozen.Featured[1]); - Assert.Equal(frozen.Featured[0], frozen.Featured[1]); - Assert.Same(frozen, frozen.AsReadOnly()); - Assert.False(Field(frozen, "favorites").CanSetDefault); - - ReferenceDefaultBindings.DuplicateSeed = true; - try - { - Assert.Throws(() => new MutablePicks()); - Assert.Throws(() => MutablePicks.NewBuilder()); - } - finally - { - ReferenceDefaultBindings.DuplicateSeed = false; - } - } - - [Fact] - public void NestedImmutableBuildersKeepTheCapturedReferenceDefaults() - { - int before = ReferenceDefaultBindings.ImmutableCalls; - var child = SelectionToken.NewBuilder().WithKey("nested").WithLabel("explicit"); - var staged = FrozenPicks.NewBuilder().WithFavoritesBuilders([child]).WithFeaturedBuilders([]); - var first = staged.Build(); - var second = staged.Build(); - Assert.Equal(before + 2, ReferenceDefaultBindings.ImmutableCalls); - Assert.Empty(first.Featured); - Assert.Empty(second.Featured); - Assert.Equal("nested", Assert.Single(first.Favorites).Key); - Assert.NotSame(Assert.Single(first.Favorites), Assert.Single(second.Favorites)); - Assert.Same(Field(first, "featured").DefaultValue, Field(second, "featured").DefaultValue); - Assert.Same(Field(first, "favorites").DefaultValue, Field(second, "favorites").DefaultValue); - Assert.DoesNotContain(Members(Field(first, "favorites")), value => ReferenceEquals(value, Assert.Single(first.Favorites))); - } - - [Fact] - public void FrozenBuilderImportsAppendToCapturedReferenceDefaults() - { - int before = ReferenceDefaultBindings.ImmutableCalls; - var builder = FrozenPicks.NewBuilder(); - var seed = builder.Build(); - var favorite = seed.Favorites.First(); - var featured = seed.Featured[0]; - var incoming = ReferenceDefaultBindings.Token("incoming", "seed"); - Assert.Equal(favorite, incoming); - Assert.NotSame(favorite, incoming); - var source = FrozenPicks.NewBuilder().WithFavorites([favorite, incoming]) - .WithFeatured([featured, incoming]).Build(); - - var appended = builder.ApplyFrom(source).Build(); - Assert.Equal(3, appended.Favorites.Count); - Assert.All(seed.Favorites, member => Assert.True(appended.Favorites.Contains(member))); - Assert.True(appended.Favorites.Contains(incoming)); - Assert.Equal(3, appended.Featured.Count); - Assert.Same(featured, appended.Featured[0]); - Assert.Same(seed.Featured[1], appended.Featured[1]); - Assert.Same(incoming, appended.Featured[2]); - Assert.Same(Field(seed, "favorites").DefaultValue, Field(appended, "favorites").DefaultValue); - Assert.Same(Field(seed, "featured").DefaultValue, Field(appended, "featured").DefaultValue); - - var replaced = builder.AppendCollections(false).ApplyFrom(source).Build(); - Assert.Equal(2, replaced.Favorites.Count); - Assert.Same(incoming, replaced.Featured[1]); - var nested = SelectionToken.NewBuilder().WithKey("lazy"); - var afterNested = builder.AppendCollections(true).WithFavoritesBuilders([nested]) - .WithFeaturedBuilders([nested]).ApplyFrom(source).Build(); - Assert.Equal(2, afterNested.Favorites.Count); - Assert.Equal(2, afterNested.Featured.Count); - Assert.Same(incoming, afterNested.Featured[1]); - Assert.Same(Field(seed, "featured").DefaultValue, Field(afterNested, "featured").DefaultValue); - Assert.Equal(before + 4, ReferenceDefaultBindings.ImmutableCalls); - Assert.Equal(2, seed.Featured.Count); - } - - [Fact] public void NestedMutableBuildersStageMembershipWithoutReevaluatingDefaults() { @@ -197,22 +88,6 @@ public void CopiesRemapLatentDeclaredAndConfiguredReferenceDefaults() Assert.Equal(calls, ReferenceDefaultBindings.MutableCalls); } - [Fact] - public void ExplicitEmptyReferenceFieldsLeaveTheCapturedDefaultIntact() - { - var missing = ModelSnapshot.Read("{}"); - Assert.Single(missing.Favorites); - Assert.Equal(2, missing.Featured.Count); - var empty = ModelSnapshot.Read("""{"picked":[],"featured":[]}"""); - Assert.Empty(empty.Favorites); - Assert.Empty(empty.Featured); - var favorite = Field(empty, "favorites"); - var reset = Assert.Single(Members(favorite)); - favorite.Reset(); - Assert.Same(reset, Assert.Single(empty.Favorites)); - Assert.Throws(() => ModelSnapshot.Write(empty)); - } - [Fact] public void LegacyReciprocalDocumentsStillRejectConflictingExplicitMemberships() { diff --git a/conformance/reference-default-csharp/RootHookDefaultsTests.cs b/conformance/reference-default-csharp/RootHookDefaultsTests.cs index 6c1dccb2..07e0f462 100644 --- a/conformance/reference-default-csharp/RootHookDefaultsTests.cs +++ b/conformance/reference-default-csharp/RootHookDefaultsTests.cs @@ -5,56 +5,6 @@ namespace Vmf.CSharp.Conformance; public sealed partial class HookReferenceDefaultsTests { - [Fact] - public void RootHookRunsOnTheConcreteLeafBeforeItsOwnProviders() - { - HookReferenceDefaultBindings.Events.Clear(); - var root = new RootHookSelection(); - Calls("hook-root", "earlier", "queue", "zulu"); - Initialized(root, root.AsReadOnly(), root.Queue, root.Earlier, root.Zulu); - - var leaf = new RootHookSelectionLeaf(); - Calls("hook-leaf", "ahead", "earlier", "queue", "zulu"); - Initialized(leaf, leaf.AsReadOnly(), leaf.Queue, leaf.Earlier, leaf.Zulu); - Assert.Equal("early", leaf.Ahead); - var builder = RootHookSelectionLeaf.NewBuilder(); - Calls("queue", "ahead", "earlier", "zulu"); - var built = builder.Build(); - Calls("hook-leaf", "ahead", "earlier", "zulu"); - Initialized(built, built.AsReadOnly(), built.Queue, built.Earlier, built.Zulu); - var empty = builder.WithQueue([]).Build(); - Calls("hook-leaf", "ahead", "earlier", "zulu"); - Assert.Empty(empty.Queue); - Assert.Same(Field(built).DefaultValue, Field(empty).DefaultValue); - - var deep = ModelSnapshot.Reflection.DeepCopy(leaf); - Calls("hook-leaf", "ahead", "earlier", "zulu"); - var shallow = ModelSnapshot.Reflection.ShallowCopy(leaf); - Calls("hook-leaf", "ahead", "earlier", "zulu"); - Assert.Equal(["hook-member", "seed"], deep.Queue.Select(member => member.Code)); - Assert.Equal(["hook-member", "seed"], shallow.Queue.Select(member => member.Code)); - Assert.NotSame(leaf.Queue[0], deep.Queue[1]); - Assert.Same(deep.Queue[1], Fallback(deep)); - Assert.Same(leaf.Queue[0], shallow.Queue[1]); - Assert.Same(Field(leaf).DefaultValue, Field(shallow).DefaultValue); - } - - [Fact] - public void ClosestDeclaredHookReplacesTheRootHook() - { - HookReferenceDefaultBindings.Events.Clear(); - var owner = new RootHookOverride(); - Calls("hook-child-local", "earlier", "queue", "zulu"); - Initialized(owner, owner.AsReadOnly(), owner.Queue, owner.Earlier, owner.Zulu); - var builder = RootHookOverride.NewBuilder(); - Calls("queue", "earlier", "zulu"); - builder.Build(); - Calls("hook-child-local", "earlier", "zulu"); - var copy = ModelSnapshot.Reflection.DeepCopy(owner); - Calls("hook-child-local", "earlier", "zulu"); - Assert.Equal(["hook-member", "seed"], copy.Queue.Select(member => member.Code)); - Assert.Same(copy.Queue[1], Fallback(copy)); - } [Fact] public void StandaloneHookCopiesItsUnorderedMembersAndFallback()