Files
Alphaeus Mote 4b7fd22a3c feat(runs): record every run with its skipped targets and live counts
A Runs record now holds what started a run (manual, schedule or trigger),
what it targeted and the devices it skipped (orphaned, or offline with
Only Devices Online Now), which previously existed only in the POST
response. Executions answer with RunCounts (targets, pending, running,
succeeded, failed, cancelled, skipped, online now), per-target online state
and failure summary, and the skipped list (narrowed to a scoped role's
devices). GET /api/executions lists recent runs across scripts. Schedules
count orphaned members as skipped instead of dropping them silently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:35:10 -04:00

224 lines
11 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
public class JobRunTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
[Fact]
public async Task DevicesAndGroupsRunAsOneDeduplicatedExecution()
{
using var client = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("multi-target");
var a = await fixture.SeedDeviceAsync("RUN-A");
var b = await fixture.SeedDeviceAsync("RUN-B");
var c = await fixture.SeedDeviceAsync("RUN-C");
var orphan = await fixture.SeedDeviceAsync("RUN-ORPHAN", orphaned: true);
var groupId = await SeedStaticGroupAsync("run-group", b, c, orphan);
var run = await RunAsync(client, new CreateJobRequest(
null, scriptId, GroupIds: [groupId], ClientIds: [a, b]));
Assert.NotNull(run.RunId);
Assert.Equal(["RUN-A", "RUN-B", "RUN-C"], run.Jobs.Select(j => j.Hostname).Order());
Assert.Equal(["RUN-ORPHAN"], run.SkippedOrphaned);
Assert.All(run.Jobs, j => Assert.Equal(scriptId, j.ScriptId));
}
[Fact]
public async Task OnlineOnlySkipsDevicesThatAreNotOnline()
{
using var client = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("online-only");
var up = await fixture.SeedDeviceAsync("ONLINE-HOST", online: true);
var down = await fixture.SeedDeviceAsync("OFFLINE-HOST");
var run = await RunAsync(client, new CreateJobRequest(
null, scriptId, ClientIds: [up, down], OnlineOnly: true));
Assert.Equal("ONLINE-HOST", Assert.Single(run.Jobs).Hostname);
Assert.Equal(["OFFLINE-HOST"], run.SkippedOffline);
}
[Fact]
public async Task SeveralGroupsAloneAreAValidTarget()
{
using var client = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("groups-only");
var g1 = await SeedStaticGroupAsync("groups-only-1", await fixture.SeedDeviceAsync("G1-HOST"));
var g2 = await SeedStaticGroupAsync("groups-only-2", await fixture.SeedDeviceAsync("G2-HOST"));
var run = await RunAsync(client, new CreateJobRequest(null, scriptId, GroupIds: [g1, g2]));
Assert.Equal(2, run.Jobs.Count);
var runIds = await fixture.WithDbAsync(async db => await Task.FromResult(db.Jobs
.Where(j => run.Jobs.Select(r => r.JobId).Contains(j.JobId))
.Select(j => j.RunId).Distinct().ToList()));
Assert.Equal([run.RunId], runIds);
}
[Fact]
public async Task ASingleDeviceStillAnswersWithItsJob()
{
using var client = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("single");
var device = await fixture.SeedDeviceAsync("SINGLE-HOST");
var response = await client.PostAsJsonAsync(
ApiRoutes.Jobs, new CreateJobRequest(device, scriptId), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var job = await response.Content.ReadFromJsonAsync<JobDto>(JsonDefaults.Options);
Assert.Equal("SINGLE-HOST", job!.Hostname);
}
[Fact]
public async Task ASingleOfflineDeviceWithOnlineOnlyIsRefused()
{
using var client = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("single-online-only");
var device = await fixture.SeedDeviceAsync("SINGLE-OFFLINE");
var response = await client.PostAsJsonAsync(
ApiRoutes.Jobs, new CreateJobRequest(device, scriptId, OnlineOnly: true), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
}
[Fact]
public async Task AScopedRoleOnlyReadsJobsOfItsDevices()
{
using var admin = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("scoped-read");
var mine = await fixture.SeedDeviceAsync("SCOPED-MINE");
var theirs = await fixture.SeedDeviceAsync("SCOPED-THEIRS");
var run = await RunAsync(admin, new CreateJobRequest(null, scriptId, ClientIds: [mine, theirs]));
var mineJob = run.Jobs.Single(j => j.ClientId == mine).JobId;
var theirJob = run.Jobs.Single(j => j.ClientId == theirs).JobId;
using var scoped = await fixture.ScopedSignedInAsync("scoped-reader", mine);
var list = await scoped.GetFromJsonAsync<List<JobDto>>($"{ApiRoutes.Jobs}?scriptId={scriptId}", JsonDefaults.Options);
Assert.Equal([mineJob], list!.Select(j => j.JobId));
Assert.Equal(HttpStatusCode.OK, (await scoped.GetAsync(ApiRoutes.For.Job(mineJob))).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.Job(theirJob))).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.JobOutput(theirJob))).StatusCode);
var execution = await scoped.GetFromJsonAsync<ExecutionDetailDto>(ApiRoutes.For.Execution(run.RunId!.Value), JsonDefaults.Options);
Assert.Equal([mine], execution!.Targets.Select(t => t.ClientId));
}
[Fact]
public async Task AnExecutionCountsEveryTargetIncludingTheSkippedOnes()
{
using var client = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("progress-counts");
var up = await fixture.SeedDeviceAsync("COUNT-UP", online: true);
var down = await fixture.SeedDeviceAsync("COUNT-DOWN");
var orphan = await fixture.SeedDeviceAsync("COUNT-ORPHAN", orphaned: true);
var groupId = await SeedStaticGroupAsync("count-group", down, orphan);
var run = await RunAsync(client, new CreateJobRequest(null, scriptId, GroupIds: [groupId], ClientIds: [up]));
await fixture.WithDbAsync(async db =>
{
var job = await db.Jobs.SingleAsync(j => j.RunId == run.RunId && j.ClientId == up);
job.State = JobState.Failed;
job.OutputSummary = "Access is denied.";
await db.SaveChangesAsync();
});
var execution = (await client.GetFromJsonAsync<ExecutionDetailDto>(ApiRoutes.For.Execution(run.RunId!.Value), JsonDefaults.Options))!;
Assert.Equal(RunSources.Manual, execution.Source);
Assert.Equal("Group “count-group” and COUNT-UP", execution.TargetsLabel);
Assert.Equal(new RunCountsDto(Targets: 3, Pending: 1, Running: 0, Succeeded: 0, Failed: 1, Cancelled: 0, Skipped: 1, Online: 1), execution.Counts);
var skip = Assert.Single(execution.Skipped!);
Assert.Equal(("COUNT-ORPHAN", SkipReasons.Orphaned), (skip.Hostname, skip.Reason));
var failed = execution.Targets.Single(t => t.ClientId == up);
Assert.True(failed.Online);
Assert.Equal("Access is denied.", failed.Summary);
}
[Fact]
public async Task RecentExecutionsSpanScriptsWithTheirCounts()
{
using var client = await fixture.SignedInAsync("run-admin");
var first = await fixture.SeedScriptAsync("recent-one");
var second = await fixture.SeedScriptAsync("recent-two");
var device = await fixture.SeedDeviceAsync("RECENT-HOST");
var orphan = await fixture.SeedDeviceAsync("RECENT-ORPHAN", orphaned: true);
var older = await RunAsync(client, new CreateJobRequest(null, first, ClientIds: [device]));
var newer = await RunAsync(client, new CreateJobRequest(null, second, ClientIds: [device, orphan]));
var recent = (await client.GetFromJsonAsync<List<ExecutionSummaryDto>>($"{ApiRoutes.Executions}?limit=200", JsonDefaults.Options))!;
var newerIndex = recent.FindIndex(e => e.RunId == newer.RunId);
var olderIndex = recent.FindIndex(e => e.RunId == older.RunId);
Assert.True(newerIndex >= 0 && newerIndex < olderIndex);
Assert.Equal("recent-two", recent[newerIndex].ScriptName);
Assert.Equal((2, 1), (recent[newerIndex].Counts!.Targets, recent[newerIndex].Counts!.Skipped));
var forFirst = (await client.GetFromJsonAsync<List<ExecutionSummaryDto>>($"{ApiRoutes.Executions}?scriptId={first}", JsonDefaults.Options))!;
Assert.Equal([older.RunId!.Value], forFirst.Select(e => e.RunId));
}
[Fact]
public async Task AScopedRoleSeesOnlyItsOwnSkippedDevices()
{
using var admin = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("scoped-skips");
var mine = await fixture.SeedDeviceAsync("SKIP-MINE");
var theirs = await fixture.SeedDeviceAsync("SKIP-THEIRS", orphaned: true);
var run = await RunAsync(admin, new CreateJobRequest(null, scriptId, ClientIds: [mine, theirs]));
using var scoped = await fixture.ScopedSignedInAsync("skip-reader", mine);
var execution = (await scoped.GetFromJsonAsync<ExecutionDetailDto>(ApiRoutes.For.Execution(run.RunId!.Value), JsonDefaults.Options))!;
Assert.Empty(execution.Skipped!);
Assert.Equal(1, execution.Counts!.Targets);
}
[Fact]
public async Task NoTargetIsABadRequest()
{
using var client = await fixture.SignedInAsync("run-admin");
var scriptId = await fixture.SeedScriptAsync("no-target");
var response = await client.PostAsJsonAsync(
ApiRoutes.Jobs, new CreateJobRequest(null, scriptId), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
private static async Task<GroupRunDto> RunAsync(HttpClient client, CreateJobRequest request)
{
var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, request, JsonDefaults.Options);
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
}
private Task<Guid> SeedStaticGroupAsync(string name, params string[] members)
=> fixture.WithDbAsync(async db =>
{
var group = new DeviceGroupEntity
{
Id = Guid.NewGuid(), Name = name, Kind = GroupKind.Static,
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
};
db.DeviceGroups.Add(group);
foreach (var member in members)
{
db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity
{
GroupId = group.Id, ClientId = member, AddedUtc = DateTimeOffset.UtcNow,
});
}
await db.SaveChangesAsync();
return group.Id;
});
}