OpenAPI-document van de SlpSoftware-host vastgelegd met snapshot-test en contactcontract
openapi/slpsoftware.v1.json is de bron voor de gegenereerde frontend-types; een test haalt het document van de echte host op en faalt bij afwijking (UPDATE_OPENAPI=1 herschrijft het bestand). De contactmodule voegt de herbruikbare foutresponses, de verplichte Idempotency-Key en de verplichte velden met maximale lengtes toe via een documenttransformer, zodat Core ongemoeid blijft. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -88,7 +88,7 @@ public class ContactMessagesControllerTests
|
||||
var result = await Create(new ContactOptions { Enabled = true, ProblemTypeBase = "https://example.test/problems/" })
|
||||
.Submit(new ContactMessageRequest(null, null, null, null, null, null, null), CancellationToken.None);
|
||||
|
||||
var problem = result.Should().BeOfType<BadRequestObjectResult>().Subject.Value.Should().BeOfType<ValidationProblemDetails>().Subject;
|
||||
var problem = result.Should().BeOfType<ObjectResult>().Subject.Value.Should().BeOfType<ValidationProblemDetails>().Subject;
|
||||
problem.Status.Should().Be(400);
|
||||
problem.Type.Should().Be("https://example.test/problems/validation");
|
||||
problem.Errors["email"].Should().Equal("invalid");
|
||||
@@ -102,7 +102,7 @@ public class ContactMessagesControllerTests
|
||||
|
||||
var result = await Create().Submit(null, CancellationToken.None);
|
||||
|
||||
((ValidationProblemDetails)((BadRequestObjectResult)result).Value!).Type.Should().Be("about:blank");
|
||||
((ValidationProblemDetails)((ObjectResult)result).Value!).Type.Should().Be("about:blank");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using FluentAssertions;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the committed OpenAPI document of the SlpSoftware host (<c>openapi/slpsoftware.v1.json</c>)
|
||||
/// equal to what the real, composed host serves, and checks the contact contract inside it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The document is the single source from which the frontend client (<c>cms-client</c>)
|
||||
/// generates its types. To regenerate after an intended API change run:
|
||||
/// <c>UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot</c>.
|
||||
/// </remarks>
|
||||
public class OpenApiSnapshotTests(DisabledContactHostFactory factory) : IClassFixture<DisabledContactHostFactory>
|
||||
{
|
||||
private const string FileName = "slpsoftware.v1.json";
|
||||
|
||||
private static string RepositoryRoot()
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "SlpModularCms.sln")))
|
||||
{
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
return directory?.FullName ?? throw new InvalidOperationException("SlpModularCms.sln not found above the test output.");
|
||||
}
|
||||
|
||||
private static string SnapshotPath() => Path.Combine(RepositoryRoot(), "openapi", FileName);
|
||||
|
||||
private async Task<string> FetchAsync()
|
||||
{
|
||||
var response = await factory.CreateClient().GetAsync("/openapi/v1.json");
|
||||
response.IsSuccessStatusCode.Should().BeTrue();
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A stable form: no request-derived <c>servers</c>, every object's keys in ordinal order (the
|
||||
/// generator's order depends on assembly discovery), 2-space indentation, LF, trailing newline.
|
||||
/// </summary>
|
||||
internal static string Normalize(string json)
|
||||
{
|
||||
var root = JsonNode.Parse(json)!.AsObject();
|
||||
root.Remove("servers");
|
||||
|
||||
var text = Sort(root)!.ToJsonString(new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
});
|
||||
|
||||
return text.Replace("\r\n", "\n") + "\n";
|
||||
}
|
||||
|
||||
private static JsonNode? Sort(JsonNode? node) => node switch
|
||||
{
|
||||
JsonObject obj => new JsonObject(obj
|
||||
.OrderBy(p => p.Key, StringComparer.Ordinal)
|
||||
.Select(p => new KeyValuePair<string, JsonNode?>(p.Key, Sort(p.Value)))),
|
||||
JsonArray array => new JsonArray(array.Select(Sort).ToArray()),
|
||||
_ => node?.DeepClone(),
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task TheCommittedDocument_EqualsWhatTheHostServes()
|
||||
{
|
||||
var current = Normalize(await FetchAsync());
|
||||
var path = SnapshotPath();
|
||||
|
||||
if (Environment.GetEnvironmentVariable("UPDATE_OPENAPI") == "1")
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
await File.WriteAllTextAsync(path, current, new System.Text.UTF8Encoding(false));
|
||||
return;
|
||||
}
|
||||
|
||||
File.Exists(path).Should().BeTrue($"{path} is missing. Generate it with: UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot");
|
||||
var committed = (await File.ReadAllTextAsync(path)).Replace("\r\n", "\n");
|
||||
|
||||
committed.Should().Be(
|
||||
current,
|
||||
"the OpenAPI document changed. If that is intended, regenerate the committed file with: " +
|
||||
"UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheDocument_ContainsTheContactContract()
|
||||
{
|
||||
var doc = JsonNode.Parse(Normalize(await FetchAsync()))!;
|
||||
var paths = doc["paths"]!.AsObject();
|
||||
|
||||
paths.Select(p => p.Key).Should().Contain(["/api/v1/contact-messages", "/api/v1/contact-messages/token"]);
|
||||
|
||||
// POST /contact-messages
|
||||
var post = doc["paths"]!["/api/v1/contact-messages"]!["post"]!;
|
||||
var header = post["parameters"]!.AsArray().Single(p => p!["name"]!.GetValue<string>() == "Idempotency-Key")!;
|
||||
header["in"]!.GetValue<string>().Should().Be("header");
|
||||
header["required"]!.GetValue<bool>().Should().BeTrue();
|
||||
header["schema"]!["format"]!.GetValue<string>().Should().Be("uuid");
|
||||
|
||||
post["requestBody"]!["required"]!.GetValue<bool>().Should().BeTrue();
|
||||
post["requestBody"]!["content"]!["application/json"]!["schema"]!["$ref"]!.GetValue<string>()
|
||||
.Should().EndWith("/ContactMessageRequest");
|
||||
|
||||
post["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["202", "400", "404", "413", "429"]);
|
||||
post["responses"]!["400"]!["$ref"]!.GetValue<string>().Should().EndWith("/Validation");
|
||||
post["responses"]!["413"]!["$ref"]!.GetValue<string>().Should().EndWith("/TooLarge");
|
||||
post["responses"]!["429"]!["$ref"]!.GetValue<string>().Should().EndWith("/RateLimited");
|
||||
|
||||
// GET /contact-messages/token
|
||||
var token = doc["paths"]!["/api/v1/contact-messages/token"]!["get"]!;
|
||||
token["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["200", "404", "429"]);
|
||||
|
||||
// Request schema: the contract's required fields and limits.
|
||||
var request = doc["components"]!["schemas"]!["ContactMessageRequest"]!;
|
||||
request["required"]!.AsArray().Select(n => n!.GetValue<string>())
|
||||
.Should().BeEquivalentTo(["name", "email", "subject", "message", "hpCheck", "token"]);
|
||||
var properties = request["properties"]!;
|
||||
properties["name"]!["maxLength"]!.GetValue<int>().Should().Be(100);
|
||||
properties["email"]!["maxLength"]!.GetValue<int>().Should().Be(254);
|
||||
properties["subject"]!["maxLength"]!.GetValue<int>().Should().Be(100);
|
||||
properties["message"]!["maxLength"]!.GetValue<int>().Should().Be(2000);
|
||||
properties["hpCheck"]!["maxLength"]!.GetValue<int>().Should().Be(0);
|
||||
|
||||
// Reusable responses.
|
||||
var responses = doc["components"]!["responses"]!;
|
||||
responses["RateLimited"]!["headers"]!["Retry-After"].Should().NotBeNull();
|
||||
responses["Validation"]!["content"]!["application/problem+json"].Should().NotBeNull();
|
||||
responses["TooLarge"]!["content"]!["application/problem+json"].Should().NotBeNull();
|
||||
|
||||
var codes = doc["components"]!["schemas"]!["ValidationProblem"]!["properties"]!["errors"]!["additionalProperties"]!["items"]!["enum"]!
|
||||
.AsArray().Select(n => n!.GetValue<string>());
|
||||
codes.Should().BeEquivalentTo(["required", "tooLong", "invalid", "expired"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheDocument_HoldsNoHostNamesAddressesOrSecrets()
|
||||
{
|
||||
var text = Normalize(await FetchAsync());
|
||||
|
||||
text.Should().NotContain("127.0.0.1").And.NotContain("localhost");
|
||||
text.Should().NotContain("@", "no e-mail addresses (not even examples)");
|
||||
text.ToLowerInvariant().Should().NotContain("secret\":").And.NotContain("password\":\"");
|
||||
JsonNode.Parse(text)!.AsObject().ContainsKey("servers").Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Normalize_IsDeterministic_RegardlessOfKeyOrder()
|
||||
{
|
||||
const string a = """{"servers":[{"url":"http://x"}],"b":1,"a":{"z":1,"y":[{"d":1,"c":2}]}}""";
|
||||
const string b = """{"a":{"y":[{"c":2,"d":1}],"z":1},"b":1}""";
|
||||
|
||||
Normalize(a).Should().Be(Normalize(b));
|
||||
Normalize(a).Should().EndWith("\n").And.NotContain("\r");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user