using Backend.Data;
using Backend.Jobs;
using Backend.Upgrades;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
namespace Backend.Tests;
/// Records upgrade commands instead of publishing them (or refuses them, as NATS being down would).
internal sealed class RecordingUpgradeSender : IAgentUpgradeSender
{
public List<(string ClientId, AgentUpgradeCommandPayload Command)> Sent { get; } = [];
public bool Fail { get; set; }
public Task DispatchAgentUpgradeAsync(string clientId, AgentUpgradeCommandPayload command, CancellationToken cancellationToken)
{
if (Fail)
{
return Task.FromResult(false);
}
lock (Sent)
{
Sent.Add((clientId, command));
}
return Task.FromResult(true);
}
}
/// Seeding and driving helpers for the agent upgrade tests.
internal static class AgentUpgradeTestKit
{
public const string V1 = "2026.10.20.1200";
public const string V2 = "2026.10.23.1400";
public const string V3 = "2026.10.30.0900";
/// Removes every upgrade, package and device, so each test starts from an empty fleet.
public static Task ResetAsync(this BackendTestFixture fixture)
=> fixture.WithDbAsync(async db =>
{
await db.AgentUpgrades.ExecuteDeleteAsync();
await db.AgentPackages.ExecuteDeleteAsync();
await db.DeviceGroupMembers.ExecuteDeleteAsync();
await db.DeviceInventory.ExecuteDeleteAsync();
await db.Devices.ExecuteDeleteAsync();
await db.AppSettings.Where(s => s.Key == AgentUpgradeSettingsStore.Key || s.Key == Backend.Enrollment.AgentDownloadAccess.PublicKey).ExecuteDeleteAsync();
fixture.Services.GetRequiredService().Invalidate();
});
/// Public agent downloads on or off (off is the default).
public static async Task SetPublicDownloadsAsync(this BackendTestFixture fixture, bool on)
{
using var scope = fixture.Services.CreateScope();
await scope.ServiceProvider.GetRequiredService().SetPublicAsync(on, "test", CancellationToken.None);
}
/// Imports a package built from through the catalog, as the sync does.
public static async Task SeedPackageAsync(
this BackendTestFixture fixture, string version, string packageType = AgentPackageTypes.WindowsZip, string? content = null)
{
var source = Path.Combine(fixture.DataPath, "incoming", Guid.NewGuid().ToString("N"), "Agent.zip");
Directory.CreateDirectory(Path.GetDirectoryName(source)!);
await File.WriteAllTextAsync(source, content ?? $"agent {version} {packageType}");
using var scope = fixture.Services.CreateScope();
var package = await scope.ServiceProvider.GetRequiredService()
.ImportAsync(packageType, source, version, CancellationToken.None);
return package ?? throw new InvalidOperationException($"{version} {packageType} was not imported");
}
public static async Task SeedAgentAsync(
this BackendTestFixture fixture, string hostname, string? version, string? runtime = "win-x64",
bool online = true, string? osCaption = null, string? install = null)
{
var clientId = await fixture.SeedDeviceAsync(hostname, online);
await fixture.WithDbAsync(async db =>
{
var device = await db.Devices.SingleAsync(d => d.ClientId == clientId);
device.AgentVersion = version;
device.AgentRuntime = runtime;
device.OsCaption = osCaption;
device.AgentInstall = install;
await db.SaveChangesAsync();
});
return clientId;
}
public static Task SeedUpgradeAsync(
this BackendTestFixture fixture, string clientId, string from, string target, string state,
string? reason = null, string source = AgentUpgradeSources.Manual, Guid? packageId = null,
Action? configure = null)
=> fixture.WithDbAsync(async db =>
{
var row = new AgentUpgradeEntity
{
Id = Guid.NewGuid(),
ClientId = clientId,
FromVersion = from,
TargetVersion = target,
PackageType = AgentPackageTypes.WindowsZip,
PackageId = packageId,
Source = source,
State = state,
Reason = reason,
CreatedUtc = DateTimeOffset.UtcNow,
FinishedUtc = AgentUpgradeStates.Finished.Contains(state) ? DateTimeOffset.UtcNow : null,
};
configure?.Invoke(row);
db.AgentUpgrades.Add(row);
await db.SaveChangesAsync();
return row;
});
public static Task UpgradeAsync(this BackendTestFixture fixture, Guid id)
=> fixture.WithDbAsync(db => db.AgentUpgrades.AsNoTracking().SingleAsync(u => u.Id == id));
public static Task> UpgradesOfAsync(this BackendTestFixture fixture, string clientId)
=> fixture.WithDbAsync(db => db.AgentUpgrades.AsNoTracking().Where(u => u.ClientId == clientId).ToListAsync());
public static Task> HistoryAsync(this BackendTestFixture fixture, string clientId)
=> fixture.WithDbAsync(db => db.AuditEvents.AsNoTracking()
.Where(e => e.ClientId == clientId && e.Category == "device")
.OrderBy(e => e.Id)
.ToListAsync());
public static Task SaveSettingsAsync(this BackendTestFixture fixture, AgentUpgradeSettingsDto settings)
=> fixture.WithDbAsync(async db =>
{
var row = await Backend.Auth.SettingsDocuments.LoadAsync(db, AgentUpgradeSettingsStore.Key, CancellationToken.None);
Backend.Auth.SettingsDocuments.Stage(db, row, AgentUpgradeSettingsStore.Key, null, settings, "test", always: true);
await db.SaveChangesAsync();
fixture.Services.GetRequiredService().Invalidate();
});
public static AgentUpgradeScheduler Scheduler(this BackendTestFixture fixture, IAgentUpgradeSender sender)
=> new(fixture.Services.GetRequiredService(), sender, NullLogger.Instance);
/// Keeps every device online as of (a simulated clock).
public static Task TouchAllAsync(this BackendTestFixture fixture, DateTimeOffset now, params string[] except)
=> fixture.WithDbAsync(async db =>
{
var excluded = except.ToList();
await db.Devices.Where(d => !excluded.Contains(d.ClientId))
.ExecuteUpdateAsync(s => s.SetProperty(d => d.LastSeenUtc, now));
});
public static async Task ApplyEventAsync(
this BackendTestFixture fixture, Guid upgradeId, string clientId, string state, string? reason = null,
string? subjectClientId = null, IReadOnlyList? log = null)
{
using var scope = fixture.Services.CreateScope();
return await scope.ServiceProvider.GetRequiredService().ApplyEventAsync(
subjectClientId ?? clientId,
new AgentUpgradeEventPayload(upgradeId, clientId, state, reason, null, null, null, log, DateTimeOffset.UtcNow),
CancellationToken.None);
}
public static async Task ReadAsync(this HttpResponseMessage response)
{
var body = await response.Content.ReadAsStringAsync();
return JsonDefaults.Deserialize(body) ?? throw new InvalidOperationException(body);
}
}