Files
atomic-design-poc/backend/tests/BigRegister.Tests/OpenZaakZaakSourceTests.cs
T
ehoandClaude Sonnet 5 8560746d15 refactor: strip WP-/RB- ticket refs from backend (RD-19)
The backend half of the sweep RD-18 did for the front end. git blame
holds the provenance and stays correct when the code moves; the
comment names a closed ticket and tells the reader nothing the
sentence around it does not.

public/letter.css and LetterHtml.golden.html change together, because
the renderer inlines the CSS and the golden file snapshots the
result.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 21:48:08 +02:00

402 lines
18 KiB
C#

using System.Net;
using BigRegister.Api.Data;
using BigRegister.Api.Zgw;
using BigRegister.Domain.Applications;
using BigRegister.Domain.Authorization;
using BigRegister.Tests.Builders;
namespace BigRegister.Tests;
/// <summary>
/// Exercises the OpenZaak read source against a stub HttpMessageHandler (no live server, no
/// mocking library) — the guarantee that it follows ZGW pagination, maps a zaak's zaaktype
/// back to the internal aanvraag-type key, and always sends a Bearer token.
/// </summary>
public class OpenZaakZaakSourceTests
{
private const string ZrcBase = "https://oz.example/zaken/api/v1";
private const string ZtBase = "https://oz.example/catalogi/api/v1";
private const string ZaaktypeUrl = $"{ZtBase}/zaaktypen/zt-1";
private static string Page1 => $$"""
{ "count": 2, "next": "{{ZrcBase}}/zaken?page=2", "results": [
{ "url": "{{ZrcBase}}/zaken/uuid-1", "identificatie": "ZAAK-1",
"zaaktype": "{{ZaaktypeUrl}}", "startdatum": "2026-03-01",
"einddatum": null, "registratiedatum": "2026-03-01" } ] }
""";
private static string Page2 => $$"""
{ "count": 2, "next": null, "results": [
{ "url": "{{ZrcBase}}/zaken/uuid-2", "identificatie": "ZAAK-2",
"zaaktype": "{{ZaaktypeUrl}}", "startdatum": "2026-01-01",
"einddatum": "2026-02-01", "registratiedatum": "2026-01-01" } ] }
""";
[Fact]
public void Follows_pagination_maps_the_internal_aanvraag_type_and_sends_bearer_token()
{
// Regression for a real bug found via a live behandelportal walkthrough: this used to
// return OpenZaak's human zaaktype label ("Herregistratie arts") as Type, which the FE's
// AANVRAAG_TYPES trust boundary always rejects (it only accepts the internal key, the
// same contract LocalZaakSource honors) — every werkvoorraad load failed to parse.
var handler = new ZgwStubHandler(url => url switch
{
_ when url == $"{ZrcBase}/zaken" => Page1,
_ when url == $"{ZrcBase}/zaken?page=2" => Page2,
_ => throw new InvalidOperationException($"unexpected ZGW GET {url}"),
});
var options = new ZgwOptions
{
ZrcBaseUrl = ZrcBase,
ZtcBaseUrl = ZtBase,
ClientId = "c",
Secret = "s",
ZaaktypeUrls = new() { ["herregistratie"] = ZaaktypeUrl },
};
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var cases = source.ListCases(DateTimeOffset.UtcNow);
// Both pages accumulated.
Assert.Equal(2, cases.Count);
Assert.Equal(new[] { "uuid-1", "uuid-2" }, cases.Select(c => c.Id));
Assert.All(cases, c => Assert.Equal("herregistratie", c.Type));
Assert.Equal("InBehandeling", cases[0].Status.Tag); // open
Assert.Equal("Goedgekeurd", cases[1].Status.Tag); // closed
// No Catalogi round-trip needed — the type maps back via the local Zgw:ZaaktypeUrls config.
Assert.DoesNotContain(handler.Requests, r => r.Contains("zaaktypen"));
// Every outbound request carried a Bearer token.
Assert.All(handler.AuthSchemes, s => Assert.Equal("Bearer", s));
}
[Fact]
public void ListCases_throws_when_a_zaak_zaaktype_has_no_configured_aanvraag_type()
{
var handler = new ZgwStubHandler(url => url switch
{
_ when url == $"{ZrcBase}/zaken" => Page1,
_ when url == $"{ZrcBase}/zaken?page=2" => Page2,
_ => throw new InvalidOperationException($"unexpected ZGW GET {url}"),
});
var options = new ZgwOptions { ZrcBaseUrl = ZrcBase, ZtcBaseUrl = ZtBase, ClientId = "c", Secret = "s" };
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
Assert.Throws<InvalidOperationException>(() => source.ListCases(DateTimeOffset.UtcNow));
}
[Fact]
public void ListMyCases_filters_by_the_callers_bsn()
{
var handler = new ZgwStubHandler(url => url switch
{
_ when url.StartsWith($"{ZrcBase}/zaken") => """{ "count": 0, "next": null, "results": [] }""",
_ => throw new InvalidOperationException($"unexpected ZGW GET {url}"),
});
var options = new ZgwOptions { ZrcBaseUrl = ZrcBase, ZtcBaseUrl = ZtBase, ClientId = "c", Secret = "s" };
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var caller = new ZorgverlenerCaller("111222333", "Dr. Test", PrincipalRole.Drafter);
source.ListMyCases(caller, DateTimeOffset.UtcNow);
Assert.Single(handler.Requests, r =>
r.StartsWith($"{ZrcBase}/zaken?") &&
r.Contains("rol__betrokkeneIdentificatie__natuurlijkPersoon__inpBsn=111222333"));
}
[Fact]
public void CreateZaak_posts_zaak_status_and_rol_and_maps_the_result_back()
{
const string zaaktypeUrl = $"{ZtBase}/zaaktypen/zt-registratie";
var handler = new ZgwStubHandler(url => url switch
{
_ when url == $"{ZrcBase}/zaken" => $$"""
{ "url": "{{ZrcBase}}/zaken/uuid-new", "identificatie": "BIG-2026-000123",
"zaaktype": "{{zaaktypeUrl}}", "startdatum": "2026-07-28",
"einddatum": null, "registratiedatum": "2026-07-28" }
""",
_ when url.StartsWith($"{ZtBase}/statustypen") => """
{ "count": 1, "next": null,
"results": [ { "url": "https://oz.example/catalogi/api/v1/statustypen/st-1", "volgnummer": 1 } ] }
""",
_ when url.StartsWith($"{ZtBase}/roltypen") => """
{ "count": 1, "next": null,
"results": [ { "url": "https://oz.example/catalogi/api/v1/roltypen/rt-initiator" } ] }
""",
_ when url == $"{ZrcBase}/statussen" => "{}",
_ when url == $"{ZrcBase}/rollen" => "{}",
_ => throw new InvalidOperationException($"unexpected ZGW call {url}"),
});
var options = new ZgwOptions
{
ZrcBaseUrl = ZrcBase,
ZtcBaseUrl = ZtBase,
ClientId = "c",
Secret = "s",
Bronorganisatie = "123443210",
VerantwoordelijkeOrganisatie = "123443210",
ZaaktypeUrls = new() { ["registratie"] = zaaktypeUrl },
};
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var aanvraag = Given.Concept(type: "registratie", owner: "111222333").Submitted().Build();
var caller = new ZorgverlenerCaller(aanvraag.Owner, "Dr. Test", PrincipalRole.Drafter);
var (referentie, status, zaakUrl) = source.CreateZaak(aanvraag, new DateTimeOffset(2026, 7, 28, 12, 0, 0, TimeSpan.Zero), caller);
// The stub echoes back its own (hardcoded) identificatie, same as a real OpenZaak response.
Assert.Equal("BIG-2026-000123", referentie);
Assert.Equal("InBehandeling", status.Tag);
Assert.Equal("BIG-2026-000123", status.Referentie);
Assert.Equal($"{ZrcBase}/zaken/uuid-new", zaakUrl);
// Zaak: mapped zaaktype + configured RSINs + the local reference as identificatie.
var zaakBody = handler.BodyOf($"{ZrcBase}/zaken");
Assert.Contains(zaaktypeUrl, zaakBody);
Assert.Contains("123443210", zaakBody);
Assert.Contains(aanvraag.Referentie, zaakBody);
// Status: points at the created zaak's URL and the resolved statustype.
var statusBody = handler.BodyOf($"{ZrcBase}/statussen");
Assert.Contains($"{ZrcBase}/zaken/uuid-new", statusBody);
Assert.Contains("statustypen/st-1", statusBody);
// Rol: points at the created zaak, the resolved initiator roltype, and the BSN.
var rolBody = handler.BodyOf($"{ZrcBase}/rollen");
Assert.Contains($"{ZrcBase}/zaken/uuid-new", rolBody);
Assert.Contains("roltypen/rt-initiator", rolBody);
Assert.Contains("111222333", rolBody);
}
[Fact]
public void CreateZaak_throws_when_the_aanvraag_type_has_no_configured_zaaktype()
{
var options = new ZgwOptions { ZrcBaseUrl = ZrcBase, ZtcBaseUrl = ZtBase, ClientId = "c", Secret = "s" };
var handler = new ZgwStubHandler(url => throw new InvalidOperationException($"no HTTP call expected, got {url}"));
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var aanvraag = Given.Concept(type: "unknown-type", owner: "111222333").Submitted().Build();
var caller = new ZorgverlenerCaller(aanvraag.Owner, "Dr. Test", PrincipalRole.Drafter);
Assert.Throws<InvalidOperationException>(() => source.CreateZaak(aanvraag, DateTimeOffset.UtcNow, caller));
}
// --- Besluit write (a status transition on an existing zaak) --------------------
[Fact]
public void RecordBesluit_posts_the_last_statustype_with_besluit_and_toelichting()
{
const string zaaktypeUrl = $"{ZtBase}/zaaktypen/zt-registratie";
var handler = new ZgwStubHandler(url => url switch
{
_ when url.StartsWith($"{ZtBase}/statustypen") => """
{ "count": 2, "next": null, "results": [
{ "url": "https://oz.example/catalogi/api/v1/statustypen/st-1", "volgnummer": 1 },
{ "url": "https://oz.example/catalogi/api/v1/statustypen/st-2", "volgnummer": 2 } ] }
""",
_ when url.StartsWith($"{ZtBase}/resultaattypen") => """
{ "count": 1, "next": null,
"results": [ { "url": "https://oz.example/catalogi/api/v1/resultaattypen/rst-1" } ] }
""",
_ when url == $"{ZrcBase}/resultaten" => "{}",
_ when url == $"{ZrcBase}/statussen" => "{}",
_ => throw new InvalidOperationException($"unexpected ZGW call {url}"),
});
var options = new ZgwOptions
{
ZrcBaseUrl = ZrcBase,
ZtcBaseUrl = ZtBase,
ClientId = "c",
Secret = "s",
ZaaktypeUrls = new() { ["registratie"] = zaaktypeUrl },
};
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var aanvraag = Given.Concept(type: "registratie", owner: "111222333")
.Submitted()
.WithZaakUrl($"{ZrcBase}/zaken/uuid-existing")
.Build();
var caller = new MedewerkerCaller("m1", new[] { MedewerkerRol.Behandelaar }, "Medewerker Test", PrincipalRole.Drafter);
source.RecordBesluit(aanvraag, Besluit.Afwijzen, "onvolledig", DateTimeOffset.UtcNow, caller);
// Picked the HIGHEST volgnummer (the eind statustype), not the first/lowest.
var statusBody = handler.BodyOf($"{ZrcBase}/statussen");
Assert.Contains($"{ZrcBase}/zaken/uuid-existing", statusBody);
Assert.Contains("statustypen/st-2", statusBody);
Assert.Contains("Afwijzen", statusBody);
Assert.Contains("onvolledig", statusBody);
}
[Fact]
public void RecordBesluit_creates_a_resultaat_before_posting_the_eindstatus()
{
// Regression for a real bug found against a live OpenZaak: posting straight to the eind
// statustype without a Resultaat first gets rejected with 400 "Zaak has no resultaat" —
// ZGW requires the Resultaat to exist before a zaak can reach its eindstatus.
const string zaaktypeUrl = $"{ZtBase}/zaaktypen/zt-registratie";
var handler = new ZgwStubHandler(url => url switch
{
_ when url.StartsWith($"{ZtBase}/statustypen") => """
{ "count": 1, "next": null,
"results": [ { "url": "https://oz.example/catalogi/api/v1/statustypen/st-1", "volgnummer": 1 } ] }
""",
_ when url.StartsWith($"{ZtBase}/resultaattypen") => """
{ "count": 1, "next": null,
"results": [ { "url": "https://oz.example/catalogi/api/v1/resultaattypen/rst-1" } ] }
""",
_ when url == $"{ZrcBase}/resultaten" => "{}",
_ when url == $"{ZrcBase}/statussen" => "{}",
_ => throw new InvalidOperationException($"unexpected ZGW call {url}"),
});
var options = new ZgwOptions
{
ZrcBaseUrl = ZrcBase,
ZtcBaseUrl = ZtBase,
ClientId = "c",
Secret = "s",
ZaaktypeUrls = new() { ["registratie"] = zaaktypeUrl },
};
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var aanvraag = Given.Concept(type: "registratie", owner: "111222333")
.Submitted()
.WithZaakUrl($"{ZrcBase}/zaken/uuid-existing")
.Build();
var caller = new MedewerkerCaller("m1", new[] { MedewerkerRol.Behandelaar }, "Medewerker Test", PrincipalRole.Drafter);
source.RecordBesluit(aanvraag, Besluit.Goedkeuren, null, DateTimeOffset.UtcNow, caller);
var resultaatBody = handler.BodyOf($"{ZrcBase}/resultaten");
Assert.Contains($"{ZrcBase}/zaken/uuid-existing", resultaatBody);
Assert.Contains("resultaattypen/rst-1", resultaatBody);
// The Resultaat must exist BEFORE the eindstatus is posted, not after.
Assert.True(
handler.Requests.IndexOf($"{ZrcBase}/resultaten") < handler.Requests.IndexOf($"{ZrcBase}/statussen"),
"expected /resultaten to be posted before /statussen");
}
[Fact]
public void RecordBesluit_does_nothing_when_the_aanvraag_has_no_zaak()
{
var options = new ZgwOptions { ZrcBaseUrl = ZrcBase, ZtcBaseUrl = ZtBase, ClientId = "c", Secret = "s" };
var handler = new ZgwStubHandler(url => throw new InvalidOperationException($"no HTTP call expected, got {url}"));
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
// ZaakUrl deliberately left unset — no builder call touches it, so it stays null.
var aanvraag = Given.Concept(type: "registratie", owner: "111222333").Submitted().Build();
var caller = new MedewerkerCaller("m1", new[] { MedewerkerRol.Behandelaar }, "Medewerker Test", PrincipalRole.Drafter);
source.RecordBesluit(aanvraag, Besluit.Goedkeuren, null, DateTimeOffset.UtcNow, caller);
Assert.Empty(handler.Requests);
}
[Fact]
public void RecordBesluit_throws_when_the_aanvraag_type_has_no_configured_zaaktype()
{
var options = new ZgwOptions { ZrcBaseUrl = ZrcBase, ZtcBaseUrl = ZtBase, ClientId = "c", Secret = "s" };
var handler = new ZgwStubHandler(url => throw new InvalidOperationException($"no HTTP call expected, got {url}"));
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var aanvraag = Given.Concept(type: "unknown-type", owner: "111222333")
.Submitted()
.WithZaakUrl($"{ZrcBase}/zaken/uuid-existing")
.Build();
var caller = new MedewerkerCaller("m1", new[] { MedewerkerRol.Behandelaar }, "Medewerker Test", PrincipalRole.Drafter);
Assert.Throws<InvalidOperationException>(() => source.RecordBesluit(aanvraag, Besluit.Goedkeuren, null, DateTimeOffset.UtcNow, caller));
}
// --- Bounded retry in ZgwHttpClient, exercised through the create-zaak write path ---
private static (ZgwOptions options, Aanvraag.Submitted aanvraag, CallerIdentity caller) CreateZaakFixture()
{
const string zaaktypeUrl = $"{ZtBase}/zaaktypen/zt-registratie";
var options = new ZgwOptions
{
ZrcBaseUrl = ZrcBase,
ZtcBaseUrl = ZtBase,
ClientId = "c",
Secret = "s",
Bronorganisatie = "123443210",
VerantwoordelijkeOrganisatie = "123443210",
ZaaktypeUrls = new() { ["registratie"] = zaaktypeUrl },
};
var aanvraag = Given.Concept(type: "registratie", owner: "111222333").Submitted().Build();
var caller = new ZorgverlenerCaller(aanvraag.Owner, "Dr. Test", PrincipalRole.Drafter);
return (options, aanvraag, caller);
}
private static string RespondFor(string zaaktypeUrl, string url) => url switch
{
_ when url == $"{ZrcBase}/zaken" => $$"""
{ "url": "{{ZrcBase}}/zaken/uuid-new", "identificatie": "BIG-2026-000123",
"zaaktype": "{{zaaktypeUrl}}", "startdatum": "2026-07-28",
"einddatum": null, "registratiedatum": "2026-07-28" }
""",
_ when url.StartsWith($"{ZtBase}/statustypen") => """
{ "count": 1, "next": null,
"results": [ { "url": "https://oz.example/catalogi/api/v1/statustypen/st-1", "volgnummer": 1 } ] }
""",
_ when url.StartsWith($"{ZtBase}/roltypen") => """
{ "count": 1, "next": null,
"results": [ { "url": "https://oz.example/catalogi/api/v1/roltypen/rt-initiator" } ] }
""",
_ when url == $"{ZrcBase}/statussen" => "{}",
_ when url == $"{ZrcBase}/rollen" => "{}",
_ => throw new InvalidOperationException($"unexpected ZGW call {url}"),
};
[Fact]
public void CreateZaak_retries_a_transient_failure_and_then_succeeds()
{
var (options, aanvraag, caller) = CreateZaakFixture();
var zaaktypeUrl = options.ZaaktypeUrls["registratie"];
var handler = new ZgwStubHandler(
url => RespondFor(zaaktypeUrl, url),
(url, attempt) => url == $"{ZrcBase}/zaken" && attempt == 0 ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK);
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var (referentie, _, zaakUrl) = source.CreateZaak(aanvraag, new DateTimeOffset(2026, 7, 28, 12, 0, 0, TimeSpan.Zero), caller);
Assert.Equal("BIG-2026-000123", referentie);
Assert.Equal($"{ZrcBase}/zaken/uuid-new", zaakUrl);
Assert.Equal(2, handler.Requests.Count(r => r == $"{ZrcBase}/zaken"));
}
[Fact]
public void CreateZaak_gives_up_after_three_attempts_on_a_persistent_transient_failure()
{
var (options, aanvraag, caller) = CreateZaakFixture();
var zaaktypeUrl = options.ZaaktypeUrls["registratie"];
var handler = new ZgwStubHandler(
url => RespondFor(zaaktypeUrl, url),
(url, _) => url == $"{ZrcBase}/zaken" ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK);
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var ex = Assert.Throws<HttpRequestException>(() => source.CreateZaak(aanvraag, DateTimeOffset.UtcNow, caller));
Assert.Contains("503", ex.Message);
Assert.Equal(3, handler.Requests.Count(r => r == $"{ZrcBase}/zaken"));
}
[Fact]
public void CreateZaak_does_not_retry_a_permanent_rejection()
{
var (options, aanvraag, caller) = CreateZaakFixture();
var zaaktypeUrl = options.ZaaktypeUrls["registratie"];
var handler = new ZgwStubHandler(
url => RespondFor(zaaktypeUrl, url),
(url, _) => url == $"{ZrcBase}/statussen" ? HttpStatusCode.BadRequest : HttpStatusCode.OK);
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
Assert.Throws<HttpRequestException>(() => source.CreateZaak(aanvraag, DateTimeOffset.UtcNow, caller));
// No retry on 400, and — the property that makes the whole design safe — no duplicate
// zaak was created by a retry that never should have happened.
Assert.Equal(1, handler.Requests.Count(r => r == $"{ZrcBase}/statussen"));
Assert.Equal(1, handler.Requests.Count(r => r == $"{ZrcBase}/zaken"));
}
}