Files
AutopilotMonitor/src/Backend/AutopilotMonitor.Functions.Tests/AppsAnalyticsHelperPagingTests.cs
T
Oliver Kieselbach 51737174b2 feat(backend,mcp): typed API contract COMPLETED — every remaining top-level success body is a manifest-exported wire DTO, and the guard now catches the bypass shapes that let them escape. The 08-31 migration's ratchet only saw inline WriteAsJsonAsync(new {...}); four bypass classes had kept ~20 endpoint families untyped: (A) Shared classes without IApiResponse — GeographicMetricsResponse, FleetHealthMetrics, ImePatternHealthResponse, SlaMetricsResponse, PlatformUsageMetrics now implement it (wire byte-identical, interface is empty); (B) Functions-local named response families moved verbatim to Shared — PlatformAgentMetricsResponse/SessionAgentMetric/DeliveryLatencyMetrics/CrashRateMetrics/CrashExceptionSummary, AgentEfficiencyMetricsResponse family (CloneAsCacheHit relocated into the service; init→set for netstandard2.0), OffboardResponse; (C) anonymous/object builders converted to DTOs with old-vs-new wire-parity facts (TypedContractCompletionWireParityTests, 14 facts incl. every vanishing-key case): rule-stats x2 (RuleStatsResponse; uniqueRules is global-only via an optional slot at its exact wire position), verdict-calibration (builder renamed VerdictCalibrationResponseBuilder, PathRow/TrendWindow to Shared), metrics/app (MetricsMath), apps list/analytics/sessions x6 routes (AppsAnalyticsHelper; legacy + paged list share ONE DTO via optional paging keys), ime-versions lean projection (ImeVersionHistoryLeanEntry [WireContract]; bare-array envelope stays, typed as IReadOnlyList<object>), device-journeys + time-attribution fleet envelopes, feature-flags, diagnostics/paths, session restore, cascade-delete Enqueued arm (error arms stay anonymous by design), feedback eligibility/list; (D) Serialize+WriteString path — ListBackupsResponse under the backup surface's own serializer options; AppInsightsQuery's Serialize is an outgoing REQUEST body (not response debt, baselined as such). TypedResponseGuardTests gains three ratchets with mutation-proven red/green: WriteAsJsonAsync(<variable assigned an anonymous object>) (empty baseline), JsonSerializer.Serialize(new{ (error-tolerant; 1 documented request-body entry), and object/Task<object>-returning Build*/Compute*/*Payload/*Response methods (1 documented union entry); the local-WriteJson-wrapper class is closed structurally (generic T : IApiResponse — an interface-typed parameter would serialize zero properties, the generic keeps the concrete type). Manifest regenerated 208→298 exported types; MCP adopts the new types (get_rule_stats typed with the trend-drop as explicit output shaping, get_platform_metrics drops its hand-declared mirror for PlatformAgentMetricsResponse, verdict-calibration-shape derives its rows via extends Omit<generated wire row> so backend renames go tsc-red). Six backend shape-test files switched from default-options serialization to the production wire options via TestWire (ApiJsonOptions; the old default-options runs only matched while payloads were anonymous with lowercase members), and three assertions that pinned null-VALUED keys now pin key ABSENCE — production always omitted them (WhenWritingNull); the parity facts prove the wire itself is unchanged. Deliberately still untyped: auth/me, CheckMcpAccess dictionary, TenantAdmins/GlobalAdmins entity-row arrays and the object-slot payloads (RuleDryRun, HealthCheck, TenantConfigFieldSchema, ...) — the documented read-model follow-up. Suites: Backend 5323, DecisionCore 577, Agent 2805, SummaryDialog 44, MCP 617, Web tsc 0 + vitest 957, generator idempotent.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 04:32:51 +02:00

68 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Text.Json;
using AutopilotMonitor.Functions.Functions.Apps;
using AutopilotMonitor.Shared.Models;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Covers the opt-in pagination surface on <see cref="AppsAnalyticsHelper.BuildAppsListResponse"/>:
/// no pageSize → legacy full array; pageSize → offset-paginated envelope with a stable cursor.
/// </summary>
public class AppsAnalyticsHelperPagingTests
{
private static List<AppInstallSummary> FiveApps()
{
var started = DateTime.UtcNow.AddDays(-1);
var list = new List<AppInstallSummary>();
// Names intentionally out of order so the deterministic appName tiebreaker is exercised.
foreach (var name in new[] { "Echo", "Alpha", "Delta", "Bravo", "Charlie" })
list.Add(new AppInstallSummary { AppName = name, Status = "Succeeded", StartedAt = started });
return list;
}
private static JsonElement Build(int? pageSize, int skip = 0) =>
TestWire.SerializeToElement(AppsAnalyticsHelper.BuildAppsListResponse(
FiveApps(), days: 30, pageSize: pageSize, skip: skip,
nextLinkForOffset: o => $"/api/apps/list?pageSize={pageSize}&skip={o}"));
[Fact]
public void NoPageSize_ReturnsLegacyFullArray_WithoutPagingFields()
{
var root = Build(pageSize: null);
Assert.Equal(5, root.GetProperty("totalApps").GetInt32());
Assert.Equal(5, root.GetProperty("apps").GetArrayLength());
Assert.False(root.TryGetProperty("nextLink", out _));
Assert.False(root.TryGetProperty("offset", out _));
}
[Fact]
public void PageSize_FirstPage_SlicesDeterministicallyAndEmitsNextLink()
{
var root = Build(pageSize: 2, skip: 0);
Assert.Equal(5, root.GetProperty("totalApps").GetInt32());
Assert.Equal(2, root.GetProperty("count").GetInt32());
Assert.Equal(0, root.GetProperty("offset").GetInt32());
var apps = root.GetProperty("apps");
Assert.Equal("Alpha", apps[0].GetProperty("appName").GetString());
Assert.Equal("Bravo", apps[1].GetProperty("appName").GetString());
Assert.Equal("/api/apps/list?pageSize=2&skip=2", root.GetProperty("nextLink").GetString());
}
[Fact]
public void PageSize_LastPage_OmitsNextLink()
{
var root = Build(pageSize: 2, skip: 4);
Assert.Equal(1, root.GetProperty("count").GetInt32());
Assert.Equal("Echo", root.GetProperty("apps")[0].GetProperty("appName").GetString());
// Wire options omit null keys (WhenWritingNull): no further page → no nextLink key.
Assert.False(root.TryGetProperty("nextLink", out _));
}
}