using System.Net; using ClawdDotNet.Core.Deploymentcenter; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; namespace ClawdDotNet.Core.Tests.Deploymentcenter; public sealed class ErrorReporterTests { private static (ErrorReporter Reporter, CapturingHandler Handler) Build( Func? now = null, HttpStatusCode status = HttpStatusCode.Created) { var handler = new CapturingHandler(status, """{"status":"success","item_id":7,"is_new":true,"occurrence_count":1}"""); var api = new DeploymentcenterApi("https://dc.example", "tok", new HttpClient(handler)); var reporter = new ErrorReporter( api, "clawddotnet", "production", "0.1.0", NullLogger.Instance, ownsApi: true, now: now); return (reporter, handler); } private static Exception Thrown(string message) { try { throw new InvalidOperationException(message); } catch (Exception ex) { return ex; } } [Fact] public async Task Report_goes_to_the_error_endpoint() { var (reporter, handler) = Build(); using var _ = reporter; var sent = await reporter.ReportAsync(Thrown("Kaputt"), fatal: true); sent.ShouldBeTrue(); handler.LastRequest!.RequestUri!.ToString().ShouldBe("https://dc.example/api/errors/v1/report"); handler.LastBody!.ShouldContain("\"exception\":\"System.InvalidOperationException\""); handler.LastBody.ShouldNotBeNull().ShouldContain("\"message\":\"Kaputt\""); handler.LastBody.ShouldNotBeNull().ShouldContain("\"level\":\"fatal\""); handler.LastBody.ShouldNotBeNull().ShouldContain("\"project_slug\":\"clawddotnet\""); } /// /// An error loop must not turn into a thousand requests. The same error goes out /// at most once per time window — the server throttles too, but only /// after the requests have already gone over the line. /// [Fact] public async Task The_same_error_goes_out_only_once_per_time_window() { var now = DateTimeOffset.UtcNow; var (reporter, handler) = Build(() => now); using var _ = reporter; var error = Thrown("Immer wieder"); (await reporter.ReportAsync(error)).ShouldBeTrue(); (await reporter.ReportAsync(error)).ShouldBeFalse(); (await reporter.ReportAsync(error)).ShouldBeFalse(); handler.Calls.ShouldBe(1); } [Fact] public async Task After_the_time_window_it_is_reported_again() { var now = DateTimeOffset.UtcNow; var (reporter, handler) = Build(() => now); using var _ = reporter; var error = Thrown("Immer wieder"); await reporter.ReportAsync(error); now = now.AddMinutes(6); await reporter.ReportAsync(error); handler.Calls.ShouldBe(2); } /// /// A reporting path that throws itself would be the worst of all worlds — the /// original error would get lost in the process. /// [Fact] public async Task A_rejected_call_does_not_throw_outward() { var (reporter, _) = Build(status: HttpStatusCode.Unauthorized); using var __ = reporter; var sent = await reporter.ReportAsync(Thrown("Egal")); sent.ShouldBeFalse(); } }