Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ omitted apart from one that was explicitly set to `null` or to a value. A contro
| `PTrampert.SimplePatch.Swashbuckle` | net8.0 | Swashbuckle schema filter |
| `PTrampert.SimplePatch.OpenApi` | net10.0 | `Microsoft.AspNetCore.OpenApi` schema transformer. It is net10.0 only because it needs `GetOrCreateSchemaAsync`. |
| `*.Test` | match their subject | NUnit test projects, one per shipped package (except `Schema`, which the integration tests cover) |
| `PTrampert.SimplePatch.Test.External` | net8.0 | A second assembly for the core tests, holding non-public types they use from another assembly. Not packed. |
| `PTrampert.SimplePatch.Sample` | net8.0 | Sample web API, not packed |

Docs are built with docfx (`docfx.json`, `index.md`, `docs/`). The API reference is generated
Expand All @@ -37,6 +38,10 @@ public face of the library on nuget.org.
- Source property attributes are carried over: `[JsonConverter]` becomes
`[OptionalConverter]`, `[JsonPropertyName]` is copied, and each `ValidationAttribute` becomes an
`[OptionalValidation(type, index)]` that runs only when the property is present.
- The internal `EmitPatchClassBuilder` builds the same class from the same `PatchClassModel` with
Reflection.Emit, one dynamic assembly per source type. The assembly declares
`[IgnoresAccessChecksTo]` for every assembly the class names, so it also supports non-public
source types. `PatchClassBuilderTest` runs against both builders.
- `JsonOptionsExtensions.AddSimplePatchConverters` registers `OptionalJsonConverterFactory` and
`PatchJsonConverterFactory`.
- The OpenAPI packages build the patch schema from the **source model's** schema, not from the
Expand Down
9 changes: 9 additions & 0 deletions PTrampert.SimplePatch.Test.External/ExternalInternalColor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace PTrampert.SimplePatch.Test.External;

// Internal, so a patch class that names it needs an access grant for this assembly as well as for
// the assembly of the source type that uses it.
internal enum ExternalInternalColor
{
Red,
Blue,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<!-- A second assembly for PTrampert.SimplePatch.Test, so a patch source type can have a
non-public property type from an assembly other than its own. -->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="PTrampert.SimplePatch.Test" />
</ItemGroup>

</Project>
143 changes: 143 additions & 0 deletions PTrampert.SimplePatch.Test/EmitPatchClassBuilderTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using PTrampert.SimplePatch.Test.External;
using PTrampert.SimplePatch.Test.TestObjects;

namespace PTrampert.SimplePatch.Test;

// Cases only the Emit builder supports: source types that aren't public. Cases it shares with the
// Roslyn builder are in PatchClassBuilderTest.
public class EmitPatchClassBuilderTest
{
private static readonly JsonSerializerOptions Options = CreateOptions();

private static JsonSerializerOptions CreateOptions()
{
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
options.AddSimplePatchConverters();
return options;
}

private static IPatchObject<T> Deserialize<T>(string json) =>
(IPatchObject<T>)JsonSerializer.Deserialize(json, EmitPatchClassBuilder.GetPatchClassFor(typeof(T)), Options)!;

[Test]
public void GetPatchClassFor_ReturnsTheSameTypeEachTime()
{
var first = EmitPatchClassBuilder.GetPatchClassFor(typeof(InternalClassTestObject));

Assert.That(EmitPatchClassBuilder.GetPatchClassFor(typeof(InternalClassTestObject)), Is.SameAs(first));
}

[Test]
public void Patch_InternalClass_AppliesSetAndExplicitNullValues()
{
var patch = Deserialize<InternalClassTestObject>(
"""{ "display_name": null, "initOnly": "New", "converted": "value" }""");

var result = patch.Patch(new InternalClassTestObject
{
Name = "Old", InitOnly = "Old", Rating = 3, Converted = "Old",
});

Assert.Multiple((Action)(() =>
{
Assert.That(result.Name, Is.Null, "An explicit null should be applied.");
Assert.That(result.InitOnly, Is.EqualTo("New"));
Assert.That(result.Rating, Is.EqualTo(3), "A property the patch leaves out should keep its value.");
Assert.That(result.Converted, Is.EqualTo("Internal:value"),
"The internal [JsonConverter] on the source property should be used.");
}));
}

[Test]
public void Validate_InternalClass_RunsTheSourceValidatorsOnSetProperties()
{
var invalid = Deserialize<InternalClassTestObject>("""{ "rating": 20 }""");
var omitted = Deserialize<InternalClassTestObject>("""{ "initOnly": "x" }""");
var invalidResults = new List<ValidationResult>();
var omittedResults = new List<ValidationResult>();

var invalidIsValid = Validator.TryValidateObject(invalid, new ValidationContext(invalid), invalidResults, true);
var omittedIsValid = Validator.TryValidateObject(omitted, new ValidationContext(omitted), omittedResults, true);

Assert.Multiple((Action)(() =>
{
Assert.That(invalidIsValid, Is.False);
Assert.That(invalidResults.Select(r => r.ErrorMessage),
Is.EqualTo(new[] { "The field Rating must be between 1 and 10." }));
Assert.That(omittedIsValid, Is.True, "Validation should skip a property the patch leaves out.");
}));
}

[Test]
public void Patch_PrivateNestedClass()
{
var patch = Deserialize<PrivateNestedTestObject>("""{ "name": "New" }""");

var result = patch.Patch(new PrivateNestedTestObject { Name = "Old", Other = "Kept" });

Assert.Multiple((Action)(() =>
{
Assert.That(result.Name, Is.EqualTo("New"));
Assert.That(result.Other, Is.EqualTo("Kept"));
}));
}

[Test]
public void Patch_PrivatePositionalRecord_KeepsTheTargetsOtherValues()
{
var patch = Deserialize<PrivatePositionalRecordTestObject>("""{ "count": 5 }""");

var result = patch.Patch(new PrivatePositionalRecordTestObject("Old", 1));

Assert.That(result, Is.EqualTo(new PrivatePositionalRecordTestObject("Old", 5)));
}

[Test]
public void Patch_InternalPrimaryConstructorClass_BindsGetOnlyPropertiesThroughTheConstructor()
{
var patch = Deserialize<InternalPrimaryConstructorTestObject>("""{ "name": "New" }""");

var result = patch.Patch(new InternalPrimaryConstructorTestObject("Old") { Color = "Red" });

Assert.Multiple((Action)(() =>
{
Assert.That(result.Name, Is.EqualTo("New"));
Assert.That(result.Color, Is.EqualTo("Red"));
}));
}

[Test]
public void Patch_InternalStruct()
{
var patch = Deserialize<InternalStructTestObject>("""{ "count": 2 }""");

var result = patch.Patch(new InternalStructTestObject { Name = "Kept", Count = 1 });

Assert.That(result, Is.EqualTo(new InternalStructTestObject { Name = "Kept", Count = 2 }));
}

[Test]
public void Patch_PropertyOfANonPublicTypeFromAnotherAssembly()
{
var patch = Deserialize<ExternalPropertyTypeTestObject>("""{ "color": 1 }""");

var result = patch.Patch(new ExternalPropertyTypeTestObject { Color = ExternalInternalColor.Red, Other = "Kept" });

Assert.Multiple((Action)(() =>
{
Assert.That(result.Color, Is.EqualTo(ExternalInternalColor.Blue));
Assert.That(result.Other, Is.EqualTo("Kept"));
}));
}

private class PrivateNestedTestObject
{
public string? Name { get; set; }

public string? Other { get; set; }
}

private record PrivatePositionalRecordTestObject(string Name, int Count);
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

<ItemGroup>
<ProjectReference Include="..\PTrampert.SimplePatch\PTrampert.SimplePatch.csproj" />
<ProjectReference Include="..\PTrampert.SimplePatch.Test.External\PTrampert.SimplePatch.Test.External.csproj" />
</ItemGroup>

</Project>
Loading
Loading