using System.Net; using System.Text; namespace BigRegister.Tests; /// /// Stub HttpMessageHandler shared by the ZGW source tests (no live server, no mocking /// library) — keyed purely by request URL (method-agnostic, since no test scenario reuses a /// URL across GET/POST). Records every request's url/body/auth-scheme for assertion. /// Factored out of OpenZaakZaakSourceTests once OpenZaakDocumentSourceTests needed the /// identical stub. /// /// An optional callback lets a test inject a failing status /// for a given url on a given (0-based) attempt — e.g. "503 on the first call to /zaken, then /// let it through" — to exercise ZgwHttpClient's retry without a live server. When it returns /// a non-2xx code, is not called for that attempt (so a test that /// models an "always fails" url never has to also teach `respond` a success body it never /// reaches). /// internal sealed class ZgwStubHandler(Func respond, Func? status = null) : HttpMessageHandler { public List Requests { get; } = new(); public List AuthSchemes { get; } = new(); public List Bodies { get; } = new(); public string BodyOf(string url) => Bodies[Requests.LastIndexOf(url)]; protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var url = request.RequestUri!.ToString(); var attempt = Requests.Count(r => r == url); Requests.Add(url); AuthSchemes.Add(request.Headers.Authorization?.Scheme); Bodies.Add(request.Content?.ReadAsStringAsync(cancellationToken).GetAwaiter().GetResult() ?? ""); var code = status?.Invoke(url, attempt) ?? HttpStatusCode.OK; if (!((int)code >= 200 && (int)code < 300)) return Task.FromResult(new HttpResponseMessage(code) { Content = new StringContent("{\"detail\":\"stub failure\"}", Encoding.UTF8, "application/json"), }); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(respond(url), Encoding.UTF8, "application/json"), }); } }