Files
ExecuteR/tests/Backend.Tests/ScriptParameterEndpointTests.cs
Alphaeus Mote 96d042b0c6 feat(schedules): target any mix of devices and groups
A trigger now carries lists of devices and groups (JSON columns, like a
role's device scope) or All Devices, instead of one device or one group.
A firing reaches the de-duplicated union; event triggers fire for a device
in any target. Saving needs at least one target, every target must exist,
All Devices stands alone, and a device-scoped role must have every target
in scope (as single targets did).

At fire time a group or device that no longer exists is skipped and noted
in the last result; the rest still run. Deleting a group or removing a
device drops it from schedules' targets, disabling only those left with
none. A schedule saved without a time zone stays UTC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 18:14:46 -05:00

293 lines
15 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>The param() import endpoint, and required values checked the same way by every start.</summary>
public class ScriptParameterEndpointTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private static readonly ScriptParameter RequiredName = new("Name", ScriptParameterType.String, Required: true);
private static readonly ScriptParameter OptionalCount = new("Count", ScriptParameterType.Number);
private static Dictionary<string, JsonElement> Args(object values)
=> JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(JsonSerializer.Serialize(values))!;
[Fact]
public async Task ParseMergesTheParamBlockIntoTheCurrentParameters()
{
using var client = await fixture.SignedInAsync("params-admin");
var response = await client.PostAsJsonAsync(ApiRoutes.ScriptParametersParse, new ParseScriptParametersRequest(
"param([Parameter(Mandatory)][string]$Name, [int]$Count = 2)",
Current: [new ScriptParameter("Name", ScriptParameterType.Number, Expansion: ValueExpansion.Literal), new("Old", ScriptParameterType.String)]),
JsonDefaults.Options);
response.EnsureSuccessStatusCode();
var result = (await response.Content.ReadFromJsonAsync<ScriptParametersParseDto>(JsonDefaults.Options))!;
Assert.True(result.Merged);
Assert.Equal(["Name", "Count"], result.Parameters.Select(p => p.Name));
Assert.Equal((ScriptParameterType.String, true, ValueExpansion.Literal),
(result.Parameters[0].Type, result.Parameters[0].Required, result.Parameters[0].Expansion));
Assert.Equal(2, result.Parameters[1].DefaultValue!.Value.GetInt32());
}
[Fact]
public async Task ParseLeavesParametersAloneWhileTheCodeHasErrors()
{
using var client = await fixture.SignedInAsync("params-admin");
ScriptParameter[] current = [new("Name", ScriptParameterType.String)];
var response = await client.PostAsJsonAsync(ApiRoutes.ScriptParametersParse,
new ParseScriptParametersRequest("param([string]$Na", Current: current), JsonDefaults.Options);
response.EnsureSuccessStatusCode();
var result = (await response.Content.ReadFromJsonAsync<ScriptParametersParseDto>(JsonDefaults.Options))!;
Assert.False(result.Merged);
Assert.Equal(["Name"], result.Parameters.Select(p => p.Name));
Assert.Contains(result.Diagnostics, d => d.Severity == "error");
}
[Fact]
public async Task ParseRefusesBash()
{
using var client = await fixture.SignedInAsync("params-admin");
var response = await client.PostAsJsonAsync(ApiRoutes.ScriptParametersParse,
new ParseScriptParametersRequest("echo hi", ScriptEngine.Bash), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task ARunNeedsEveryRequiredValueWithoutADefault()
{
using var client = await fixture.SignedInAsync("params-admin");
var scriptId = await SeedScriptAsync("required-run", RequiredName, OptionalCount);
var device = await fixture.SeedDeviceAsync("PARAMS-RUN");
var missing = await client.PostAsJsonAsync(ApiRoutes.Jobs,
new CreateJobRequest(null, scriptId, ClientIds: [device]), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, missing.StatusCode);
Assert.Contains("“Name” needs a value", await missing.Content.ReadAsStringAsync());
var blank = await client.PostAsJsonAsync(ApiRoutes.Jobs,
new CreateJobRequest(null, scriptId, Args(new { Name = " " }), ClientIds: [device]), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, blank.StatusCode);
var given = await client.PostAsJsonAsync(ApiRoutes.Jobs,
new CreateJobRequest(null, scriptId, Args(new { Name = "widget" }), ClientIds: [device]), JsonDefaults.Options);
given.EnsureSuccessStatusCode();
}
[Fact]
public async Task ADefaultSatisfiesARequiredParameter()
{
using var client = await fixture.SignedInAsync("params-admin");
var scriptId = await SeedScriptAsync("required-default",
RequiredName with { DefaultValue = JsonSerializer.SerializeToElement("fallback") });
var device = await fixture.SeedDeviceAsync("PARAMS-DEFAULT");
var response = await client.PostAsJsonAsync(ApiRoutes.Jobs,
new CreateJobRequest(null, scriptId, ClientIds: [device]), JsonDefaults.Options);
response.EnsureSuccessStatusCode();
}
[Theory]
[InlineData("""{ "Name": "x", "Count": "many" }""", "must be a number")]
[InlineData("""{ "Name": "x", "Nope": 1 }""", "not a parameter")]
[InlineData("""{ "name": "x" }""", "not a parameter")]
[InlineData("""{ "Name": ["x"] }""", "must be text")]
public async Task ARunRefusesValuesThatDoNotFit(string arguments, string error)
{
using var client = await fixture.SignedInAsync("params-admin");
var scriptId = await SeedScriptAsync($"misfit-{Guid.NewGuid():N}", RequiredName, OptionalCount);
var device = await fixture.SeedDeviceAsync("PARAMS-MISFIT");
var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(
null, scriptId, JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(arguments), ClientIds: [device]),
JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains(error, await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task AValidateSetLimitsTheValues()
{
using var client = await fixture.SignedInAsync("params-admin");
var scriptId = await SeedScriptAsync("validate-set",
new ScriptParameter("Mode", ScriptParameterType.String, AllowedValues: ["Fast", "Safe"]));
var device = await fixture.SeedDeviceAsync("PARAMS-SET");
var wrong = await client.PostAsJsonAsync(ApiRoutes.Jobs,
new CreateJobRequest(null, scriptId, Args(new { Mode = "Reckless" }), ClientIds: [device]), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, wrong.StatusCode);
var anyCase = await client.PostAsJsonAsync(ApiRoutes.Jobs,
new CreateJobRequest(null, scriptId, Args(new { Mode = "safe" }), ClientIds: [device]), JsonDefaults.Options);
anyCase.EnsureSuccessStatusCode();
}
[Fact]
public async Task ATriggerNeedsTheRequiredValuesToo()
{
using var client = await fixture.SignedInAsync("params-admin");
var scriptId = await SeedScriptAsync("required-trigger", RequiredName);
var missing = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *"), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, missing.StatusCode);
Assert.Contains("needs a value", await missing.Content.ReadAsStringAsync());
var given = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *", Arguments: Args(new { Name = "x" })),
JsonDefaults.Options);
given.EnsureSuccessStatusCode();
}
[Fact]
public async Task AScheduleFollowsDefaultsAndStopsWhenTheScriptGainsARequiredValue()
{
using var client = await fixture.SignedInAsync("params-admin");
var scriptId = await SeedScriptAsync("evolving", OptionalCount);
var device = await fixture.SeedDeviceAsync("PARAMS-EVOLVE");
var create = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
scriptId, ScriptTriggerType.Scheduled, ClientIds: [device], CronExpression: "0 1 * * *"), JsonDefaults.Options);
create.EnsureSuccessStatusCode();
var triggerId = (await create.Content.ReadFromJsonAsync<Dictionary<string, Guid>>(JsonDefaults.Options))!["id"];
// The script gains a required parameter with no default after the schedule was saved.
await SetParametersAsync(scriptId, OptionalCount, RequiredName);
var listed = (await client.GetFromJsonAsync<List<ScriptTriggerDto>>(ApiRoutes.Triggers, JsonDefaults.Options))!
.Single(t => t.Id == triggerId);
Assert.Contains("“Name” needs a value", listed.ArgumentsProblem);
var fired = await (await client.PostAsync(ApiRoutes.For.TriggerRun(triggerId), null))
.Content.ReadFromJsonAsync<TriggerRunResultDto>(JsonDefaults.Options);
Assert.Equal(0, fired!.Queued);
Assert.StartsWith("Not run:", fired.Message);
var trigger = await fixture.WithDbAsync(db => db.ScriptTriggers.SingleAsync(t => t.Id == triggerId));
Assert.True(trigger.Enabled);
// A default on the script is enough: the untouched value follows it.
await SetParametersAsync(scriptId, OptionalCount, RequiredName with { DefaultValue = JsonSerializer.SerializeToElement("now set") });
var again = await (await client.PostAsync(ApiRoutes.For.TriggerRun(triggerId), null))
.Content.ReadFromJsonAsync<TriggerRunResultDto>(JsonDefaults.Options);
Assert.Equal(1, again!.Queued);
}
[Fact]
public async Task SavingABashScriptChecksItsParameters()
{
using var client = await fixture.SignedInAsync("params-admin");
var badDefault = await client.PostAsJsonAsync(ApiRoutes.Scripts, new SaveScriptRequest(
"bad-default", null, "echo $Count",
[new ScriptParameter("Count", ScriptParameterType.Number, DefaultValue: JsonSerializer.SerializeToElement("lots"))],
Engine: ScriptEngine.Bash),
JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, badDefault.StatusCode);
var duplicate = await client.PostAsJsonAsync(ApiRoutes.Scripts, new SaveScriptRequest(
"duplicate", null, "", [new ScriptParameter("A", ScriptParameterType.String), new("a", ScriptParameterType.String)],
Engine: ScriptEngine.Bash),
JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, duplicate.StatusCode);
var good = await SaveAsync(client, new SaveScriptRequest(
"good-defaults", null, "echo $Ports",
[new ScriptParameter("Ports", ScriptParameterType.Array, ElementType: PrimitiveType.Number,
DefaultValue: JsonSerializer.SerializeToElement(new[] { 80, 443 }))],
Engine: ScriptEngine.Bash));
Assert.Equal("[80,443]", Assert.Single(good.Parameters).DefaultValue!.Value.GetRawText());
}
[Fact]
public async Task SavingAPowerShellScriptStoresWhatTheCodeDeclares()
{
using var client = await fixture.SignedInAsync("params-admin");
const string code = """
<#
.PARAMETER Documented
From help.
#>
param([Parameter(Mandatory)][int[]]$Ports = @(80, 443), [string]$Path, [string]$Documented)
""";
// Whatever the client sent: wrong types, a parameter the code lacks, none for one it has.
var created = await SaveAsync(client, new SaveScriptRequest("from-code", null, code,
[
new ScriptParameter("ports", ScriptParameterType.String, Expansion: ValueExpansion.Literal),
new("Path", ScriptParameterType.Number, Description: "Hand-written"),
new("Documented", ScriptParameterType.String, Description: "Replaced by help"),
new("Stale", ScriptParameterType.String),
]));
Assert.Equal(["Ports", "Path", "Documented"], created.Parameters.Select(p => p.Name));
var ports = created.Parameters[0];
Assert.Equal((ScriptParameterType.Array, PrimitiveType.Number, true), (ports.Type, ports.ElementType, ports.Required));
Assert.Equal("[80,443]", ports.DefaultValue!.Value.GetRawText());
Assert.Equal(ValueExpansion.Literal, ports.Expansion);
Assert.Equal((ScriptParameterType.String, "Hand-written"), (created.Parameters[1].Type, created.Parameters[1].Description));
Assert.Equal("From help.", created.Parameters[2].Description);
// An update that sends no parameters keeps the user-owned fields already stored.
var response = await client.PutAsJsonAsync(ApiRoutes.For.Script(created.Id),
new SaveScriptRequest("from-code", null, code + "\n# edited"), JsonDefaults.Options);
response.EnsureSuccessStatusCode();
var updated = (await response.Content.ReadFromJsonAsync<ScriptDto>(JsonDefaults.Options))!;
Assert.Equal(ValueExpansion.Literal, updated.Parameters[0].Expansion);
Assert.Equal("Hand-written", updated.Parameters[1].Description);
// Code that does not parse keeps what the editor last read from it.
var broken = await client.PutAsJsonAsync(ApiRoutes.For.Script(created.Id),
new SaveScriptRequest("from-code", null, "param([string]$Half", [new ScriptParameter("Half", ScriptParameterType.String)]),
JsonDefaults.Options);
broken.EnsureSuccessStatusCode();
Assert.Equal(["Half"], (await broken.Content.ReadFromJsonAsync<ScriptDto>(JsonDefaults.Options))!.Parameters.Select(p => p.Name));
}
private static async Task<ScriptDto> SaveAsync(HttpClient client, SaveScriptRequest request)
{
var response = await client.PostAsJsonAsync(ApiRoutes.Scripts, request, JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<ScriptDto>(JsonDefaults.Options))!;
}
private Task<Guid> SeedScriptAsync(string name, params ScriptParameter[] parameters)
=> fixture.WithDbAsync(async db =>
{
var script = new ScriptEntity
{
Id = Guid.NewGuid(),
Name = name,
Language = "PowerShell",
Content = "param($Name, $Count)",
ParametersJson = JsonDefaults.Serialize(parameters),
CreatedUtc = DateTimeOffset.UtcNow,
UpdatedUtc = DateTimeOffset.UtcNow,
};
db.Scripts.Add(script);
await db.SaveChangesAsync();
return script.Id;
});
private Task SetParametersAsync(Guid scriptId, params ScriptParameter[] parameters)
=> fixture.WithDbAsync(async db =>
{
var script = await db.Scripts.SingleAsync(s => s.Id == scriptId);
script.ParametersJson = JsonDefaults.Serialize(parameters);
await db.SaveChangesAsync();
return 0;
});
}