up
Some checks failed
Docs CI / lint-and-preview (push) Has been cancelled
AOC Guard CI / aoc-guard (push) Has been cancelled
AOC Guard CI / aoc-verify (push) Has been cancelled
Concelier Attestation Tests / attestation-tests (push) Has been cancelled
Export Center CI / export-ci (push) Has been cancelled
Notify Smoke Test / Notify Unit Tests (push) Has been cancelled
Notify Smoke Test / Notifier Service Tests (push) Has been cancelled
Notify Smoke Test / Notification Smoke Test (push) Has been cancelled
Policy Lint & Smoke / policy-lint (push) Has been cancelled
Scanner Analyzers / Discover Analyzers (push) Has been cancelled
Scanner Analyzers / Build Analyzers (push) Has been cancelled
Scanner Analyzers / Test Language Analyzers (push) Has been cancelled
Scanner Analyzers / Validate Test Fixtures (push) Has been cancelled
Scanner Analyzers / Verify Deterministic Output (push) Has been cancelled
Signals CI & Image / signals-ci (push) Has been cancelled
Signals Reachability Scoring & Events / reachability-smoke (push) Has been cancelled
Signals Reachability Scoring & Events / sign-and-upload (push) Has been cancelled

This commit is contained in:
StellaOps Bot
2025-12-13 00:20:26 +02:00
parent e1f1bef4c1
commit 564df71bfb
2376 changed files with 334389 additions and 328032 deletions

View File

@@ -1,39 +1,39 @@
namespace StellaOps.Scheduler.Models.Tests;
public sealed class AuditRecordTests
{
[Fact]
public void AuditRecordNormalizesMetadataAndIdentifiers()
{
var actor = new AuditActor(actorId: "user_admin", displayName: "Cluster Admin", kind: "user");
var metadata = new[]
{
new KeyValuePair<string, string>("details", "schedule paused"),
new KeyValuePair<string, string>("Details", "should be overridden"), // duplicate with different casing
new KeyValuePair<string, string>("reason", "maintenance"),
};
var record = new AuditRecord(
id: "audit_001",
tenantId: "tenant-alpha",
category: "scheduler",
action: "pause",
occurredAt: DateTimeOffset.Parse("2025-10-18T05:00:00Z"),
actor: actor,
scheduleId: "sch_001",
runId: null,
correlationId: "corr-123",
metadata: metadata,
message: "Paused via API");
Assert.Equal("tenant-alpha", record.TenantId);
Assert.Equal("scheduler", record.Category);
Assert.Equal(2, record.Metadata.Count);
Assert.Equal("schedule paused", record.Metadata["details"]);
Assert.Equal("maintenance", record.Metadata["reason"]);
var json = CanonicalJsonSerializer.Serialize(record);
Assert.Contains("\"category\":\"scheduler\"", json, StringComparison.Ordinal);
Assert.Contains("\"metadata\":{\"details\":\"schedule paused\",\"reason\":\"maintenance\"}", json, StringComparison.Ordinal);
}
}
namespace StellaOps.Scheduler.Models.Tests;
public sealed class AuditRecordTests
{
[Fact]
public void AuditRecordNormalizesMetadataAndIdentifiers()
{
var actor = new AuditActor(actorId: "user_admin", displayName: "Cluster Admin", kind: "user");
var metadata = new[]
{
new KeyValuePair<string, string>("details", "schedule paused"),
new KeyValuePair<string, string>("Details", "should be overridden"), // duplicate with different casing
new KeyValuePair<string, string>("reason", "maintenance"),
};
var record = new AuditRecord(
id: "audit_001",
tenantId: "tenant-alpha",
category: "scheduler",
action: "pause",
occurredAt: DateTimeOffset.Parse("2025-10-18T05:00:00Z"),
actor: actor,
scheduleId: "sch_001",
runId: null,
correlationId: "corr-123",
metadata: metadata,
message: "Paused via API");
Assert.Equal("tenant-alpha", record.TenantId);
Assert.Equal("scheduler", record.Category);
Assert.Equal(2, record.Metadata.Count);
Assert.Equal("schedule paused", record.Metadata["details"]);
Assert.Equal("maintenance", record.Metadata["reason"]);
var json = CanonicalJsonSerializer.Serialize(record);
Assert.Contains("\"category\":\"scheduler\"", json, StringComparison.Ordinal);
Assert.Contains("\"metadata\":{\"details\":\"schedule paused\",\"reason\":\"maintenance\"}", json, StringComparison.Ordinal);
}
}

View File

@@ -1,171 +1,171 @@
namespace StellaOps.Scheduler.Models.Tests;
public sealed class GraphJobStateMachineTests
{
[Theory]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Pending, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Queued, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Running, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Completed, false)]
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Running, true)]
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Completed, false)]
[InlineData(GraphJobStatus.Running, GraphJobStatus.Completed, true)]
[InlineData(GraphJobStatus.Running, GraphJobStatus.Pending, false)]
[InlineData(GraphJobStatus.Completed, GraphJobStatus.Failed, false)]
public void CanTransition_ReturnsExpectedResult(GraphJobStatus from, GraphJobStatus to, bool expected)
{
Assert.Equal(expected, GraphJobStateMachine.CanTransition(from, to));
}
[Fact]
public void EnsureTransition_UpdatesBuildJobLifecycle()
{
var createdAt = new DateTimeOffset(2025, 10, 26, 12, 0, 0, TimeSpan.Zero);
var job = new GraphBuildJob(
id: "gbj_1",
tenantId: "tenant-alpha",
sbomId: "sbom_1",
sbomVersionId: "sbom_ver_1",
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: createdAt);
var queuedAt = createdAt.AddSeconds(5);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Queued, queuedAt);
Assert.Equal(GraphJobStatus.Queued, job.Status);
Assert.Null(job.StartedAt);
Assert.Null(job.CompletedAt);
var runningAt = queuedAt.AddSeconds(5);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Running, runningAt, attempts: job.Attempts + 1);
Assert.Equal(GraphJobStatus.Running, job.Status);
Assert.Equal(runningAt, job.StartedAt);
Assert.Null(job.CompletedAt);
var completedAt = runningAt.AddSeconds(30);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Completed, completedAt);
Assert.Equal(GraphJobStatus.Completed, job.Status);
Assert.Equal(runningAt, job.StartedAt);
Assert.Equal(completedAt, job.CompletedAt);
Assert.Null(job.Error);
}
[Fact]
public void EnsureTransition_ToFailedRequiresError()
{
var job = new GraphBuildJob(
id: "gbj_1",
tenantId: "tenant-alpha",
sbomId: "sbom_1",
sbomVersionId: "sbom_ver_1",
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
status: GraphJobStatus.Running,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: DateTimeOffset.UtcNow,
startedAt: DateTimeOffset.UtcNow);
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.EnsureTransition(
job,
GraphJobStatus.Failed,
DateTimeOffset.UtcNow));
}
[Fact]
public void EnsureTransition_ToFailedSetsError()
{
var job = new GraphOverlayJob(
id: "goj_1",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_1",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@latest",
status: GraphJobStatus.Running,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow,
startedAt: DateTimeOffset.UtcNow);
var failed = GraphJobStateMachine.EnsureTransition(
job,
GraphJobStatus.Failed,
DateTimeOffset.UtcNow,
errorMessage: "cartographer timeout");
Assert.Equal(GraphJobStatus.Failed, failed.Status);
Assert.NotNull(failed.CompletedAt);
Assert.Equal("cartographer timeout", failed.Error);
}
[Fact]
public void Validate_RequiresCompletedAtForTerminalState()
{
var job = new GraphOverlayJob(
id: "goj_1",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_1",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@latest",
status: GraphJobStatus.Completed,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow);
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.Validate(job));
}
[Fact]
public void GraphOverlayJob_NormalizesSubjectsAndMetadata()
{
var createdAt = DateTimeOffset.UtcNow;
var job = new GraphOverlayJob(
id: "goj_norm",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_norm",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@norm",
status: GraphJobStatus.Pending,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: createdAt,
subjects: new[]
{
"artifact/service-api",
"artifact/service-ui",
"artifact/service-api"
},
metadata: new[]
{
new KeyValuePair<string, string>("PolicyRunId", "run-123"),
new KeyValuePair<string, string>("policyRunId", "run-123")
});
Assert.Equal(2, job.Subjects.Length);
Assert.Collection(
job.Subjects,
subject => Assert.Equal("artifact/service-api", subject),
subject => Assert.Equal("artifact/service-ui", subject));
Assert.Single(job.Metadata);
Assert.Equal("run-123", job.Metadata["policyrunid"]);
}
[Fact]
public void GraphBuildJob_NormalizesDigestAndMetadata()
{
var job = new GraphBuildJob(
id: "gbj_norm",
tenantId: "tenant-alpha",
sbomId: "sbom_norm",
sbomVersionId: "sbom_ver_norm",
sbomDigest: "SHA256:ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890",
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.Manual,
createdAt: DateTimeOffset.UtcNow,
metadata: new[]
{
new KeyValuePair<string, string>("SBoMEventId", "evt-42")
});
Assert.Equal("sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", job.SbomDigest);
Assert.Single(job.Metadata);
Assert.Equal("evt-42", job.Metadata["sbomeventid"]);
}
}
namespace StellaOps.Scheduler.Models.Tests;
public sealed class GraphJobStateMachineTests
{
[Theory]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Pending, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Queued, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Running, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Completed, false)]
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Running, true)]
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Completed, false)]
[InlineData(GraphJobStatus.Running, GraphJobStatus.Completed, true)]
[InlineData(GraphJobStatus.Running, GraphJobStatus.Pending, false)]
[InlineData(GraphJobStatus.Completed, GraphJobStatus.Failed, false)]
public void CanTransition_ReturnsExpectedResult(GraphJobStatus from, GraphJobStatus to, bool expected)
{
Assert.Equal(expected, GraphJobStateMachine.CanTransition(from, to));
}
[Fact]
public void EnsureTransition_UpdatesBuildJobLifecycle()
{
var createdAt = new DateTimeOffset(2025, 10, 26, 12, 0, 0, TimeSpan.Zero);
var job = new GraphBuildJob(
id: "gbj_1",
tenantId: "tenant-alpha",
sbomId: "sbom_1",
sbomVersionId: "sbom_ver_1",
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: createdAt);
var queuedAt = createdAt.AddSeconds(5);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Queued, queuedAt);
Assert.Equal(GraphJobStatus.Queued, job.Status);
Assert.Null(job.StartedAt);
Assert.Null(job.CompletedAt);
var runningAt = queuedAt.AddSeconds(5);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Running, runningAt, attempts: job.Attempts + 1);
Assert.Equal(GraphJobStatus.Running, job.Status);
Assert.Equal(runningAt, job.StartedAt);
Assert.Null(job.CompletedAt);
var completedAt = runningAt.AddSeconds(30);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Completed, completedAt);
Assert.Equal(GraphJobStatus.Completed, job.Status);
Assert.Equal(runningAt, job.StartedAt);
Assert.Equal(completedAt, job.CompletedAt);
Assert.Null(job.Error);
}
[Fact]
public void EnsureTransition_ToFailedRequiresError()
{
var job = new GraphBuildJob(
id: "gbj_1",
tenantId: "tenant-alpha",
sbomId: "sbom_1",
sbomVersionId: "sbom_ver_1",
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
status: GraphJobStatus.Running,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: DateTimeOffset.UtcNow,
startedAt: DateTimeOffset.UtcNow);
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.EnsureTransition(
job,
GraphJobStatus.Failed,
DateTimeOffset.UtcNow));
}
[Fact]
public void EnsureTransition_ToFailedSetsError()
{
var job = new GraphOverlayJob(
id: "goj_1",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_1",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@latest",
status: GraphJobStatus.Running,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow,
startedAt: DateTimeOffset.UtcNow);
var failed = GraphJobStateMachine.EnsureTransition(
job,
GraphJobStatus.Failed,
DateTimeOffset.UtcNow,
errorMessage: "cartographer timeout");
Assert.Equal(GraphJobStatus.Failed, failed.Status);
Assert.NotNull(failed.CompletedAt);
Assert.Equal("cartographer timeout", failed.Error);
}
[Fact]
public void Validate_RequiresCompletedAtForTerminalState()
{
var job = new GraphOverlayJob(
id: "goj_1",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_1",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@latest",
status: GraphJobStatus.Completed,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow);
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.Validate(job));
}
[Fact]
public void GraphOverlayJob_NormalizesSubjectsAndMetadata()
{
var createdAt = DateTimeOffset.UtcNow;
var job = new GraphOverlayJob(
id: "goj_norm",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_norm",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@norm",
status: GraphJobStatus.Pending,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: createdAt,
subjects: new[]
{
"artifact/service-api",
"artifact/service-ui",
"artifact/service-api"
},
metadata: new[]
{
new KeyValuePair<string, string>("PolicyRunId", "run-123"),
new KeyValuePair<string, string>("policyRunId", "run-123")
});
Assert.Equal(2, job.Subjects.Length);
Assert.Collection(
job.Subjects,
subject => Assert.Equal("artifact/service-api", subject),
subject => Assert.Equal("artifact/service-ui", subject));
Assert.Single(job.Metadata);
Assert.Equal("run-123", job.Metadata["policyrunid"]);
}
[Fact]
public void GraphBuildJob_NormalizesDigestAndMetadata()
{
var job = new GraphBuildJob(
id: "gbj_norm",
tenantId: "tenant-alpha",
sbomId: "sbom_norm",
sbomVersionId: "sbom_ver_norm",
sbomDigest: "SHA256:ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890",
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.Manual,
createdAt: DateTimeOffset.UtcNow,
metadata: new[]
{
new KeyValuePair<string, string>("SBoMEventId", "evt-42")
});
Assert.Equal("sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", job.SbomDigest);
Assert.Single(job.Metadata);
Assert.Equal("evt-42", job.Metadata["sbomeventid"]);
}
}

View File

@@ -1,55 +1,55 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ImpactSetTests
{
[Fact]
public void ImpactSetSortsImagesByDigest()
{
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
var images = new[]
{
new ImpactImage(
imageDigest: "sha256:bbbb",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod", "latest" },
usedByEntrypoint: true,
labels: new Dictionary<string, string>
{
["env"] = "prod",
}),
new ImpactImage(
imageDigest: "sha256:aaaa",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod" },
usedByEntrypoint: false),
};
var impactSet = new ImpactSet(
selector,
images,
usageOnly: true,
generatedAt: DateTimeOffset.Parse("2025-10-18T05:04:03Z"),
total: 2,
snapshotId: "snap-001");
Assert.Equal(SchedulerSchemaVersions.ImpactSet, impactSet.SchemaVersion);
Assert.Equal(new[] { "sha256:aaaa", "sha256:bbbb" }, impactSet.Images.Select(i => i.ImageDigest));
Assert.True(impactSet.UsageOnly);
Assert.Equal(2, impactSet.Total);
var json = CanonicalJsonSerializer.Serialize(impactSet);
Assert.Contains("\"snapshotId\":\"snap-001\"", json, StringComparison.Ordinal);
}
[Fact]
public void ImpactImageRejectsInvalidDigest()
{
Assert.Throws<ArgumentException>(() => new ImpactImage("sha1:not-supported", "registry", "repo"));
}
}
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ImpactSetTests
{
[Fact]
public void ImpactSetSortsImagesByDigest()
{
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
var images = new[]
{
new ImpactImage(
imageDigest: "sha256:bbbb",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod", "latest" },
usedByEntrypoint: true,
labels: new Dictionary<string, string>
{
["env"] = "prod",
}),
new ImpactImage(
imageDigest: "sha256:aaaa",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod" },
usedByEntrypoint: false),
};
var impactSet = new ImpactSet(
selector,
images,
usageOnly: true,
generatedAt: DateTimeOffset.Parse("2025-10-18T05:04:03Z"),
total: 2,
snapshotId: "snap-001");
Assert.Equal(SchedulerSchemaVersions.ImpactSet, impactSet.SchemaVersion);
Assert.Equal(new[] { "sha256:aaaa", "sha256:bbbb" }, impactSet.Images.Select(i => i.ImageDigest));
Assert.True(impactSet.UsageOnly);
Assert.Equal(2, impactSet.Total);
var json = CanonicalJsonSerializer.Serialize(impactSet);
Assert.Contains("\"snapshotId\":\"snap-001\"", json, StringComparison.Ordinal);
}
[Fact]
public void ImpactImageRejectsInvalidDigest()
{
Assert.Throws<ArgumentException>(() => new ImpactImage("sha1:not-supported", "registry", "repo"));
}
}

View File

@@ -1,31 +1,31 @@
using System.Collections.Immutable;
using System.Text.Json;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class PolicyRunModelsTests
{
[Fact]
public void PolicyRunInputs_NormalizesEnvironmentKeys()
{
var inputs = new PolicyRunInputs(
sbomSet: new[] { "sbom:two", "sbom:one" },
env: new[]
{
new KeyValuePair<string, object?>("Sealed", true),
new KeyValuePair<string, object?>("Exposure", "internet"),
new KeyValuePair<string, object?>("region", JsonSerializer.SerializeToElement("global"))
},
captureExplain: true);
Assert.Equal(new[] { "sbom:one", "sbom:two" }, inputs.SbomSet);
Assert.True(inputs.CaptureExplain);
Assert.Equal(3, inputs.Environment.Count);
Assert.True(inputs.Environment.ContainsKey("sealed"));
Assert.Equal(JsonValueKind.True, inputs.Environment["sealed"].ValueKind);
Assert.Equal("internet", inputs.Environment["exposure"].GetString());
Assert.Equal("global", inputs.Environment["region"].GetString());
using System.Collections.Immutable;
using System.Text.Json;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class PolicyRunModelsTests
{
[Fact]
public void PolicyRunInputs_NormalizesEnvironmentKeys()
{
var inputs = new PolicyRunInputs(
sbomSet: new[] { "sbom:two", "sbom:one" },
env: new[]
{
new KeyValuePair<string, object?>("Sealed", true),
new KeyValuePair<string, object?>("Exposure", "internet"),
new KeyValuePair<string, object?>("region", JsonSerializer.SerializeToElement("global"))
},
captureExplain: true);
Assert.Equal(new[] { "sbom:one", "sbom:two" }, inputs.SbomSet);
Assert.True(inputs.CaptureExplain);
Assert.Equal(3, inputs.Environment.Count);
Assert.True(inputs.Environment.ContainsKey("sealed"));
Assert.Equal(JsonValueKind.True, inputs.Environment["sealed"].ValueKind);
Assert.Equal("internet", inputs.Environment["exposure"].GetString());
Assert.Equal("global", inputs.Environment["region"].GetString());
}
[Fact]
@@ -90,56 +90,56 @@ public sealed class PolicyRunModelsTests
CancelledAt: status == PolicyRunJobStatus.Cancelled ? timestamp : null);
}
[Fact]
public void PolicyRunStatus_ThrowsOnNegativeAttempts()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PolicyRunStatus(
runId: "run:test",
tenantId: "tenant-alpha",
policyId: "P-1",
policyVersion: 1,
mode: PolicyRunMode.Full,
status: PolicyRunExecutionStatus.Queued,
priority: PolicyRunPriority.Normal,
queuedAt: DateTimeOffset.UtcNow,
attempts: -1));
}
[Fact]
public void PolicyDiffSummary_NormalizesSeverityKeys()
{
var summary = new PolicyDiffSummary(
added: 1,
removed: 2,
unchanged: 3,
bySeverity: new[]
{
new KeyValuePair<string, PolicyDiffSeverityDelta>("critical", new PolicyDiffSeverityDelta(1, 0)),
new KeyValuePair<string, PolicyDiffSeverityDelta>("HIGH", new PolicyDiffSeverityDelta(0, 1))
});
Assert.True(summary.BySeverity.ContainsKey("Critical"));
Assert.True(summary.BySeverity.ContainsKey("High"));
}
[Fact]
public void PolicyExplainTrace_LowercasesMetadataKeys()
{
var trace = new PolicyExplainTrace(
findingId: "finding:alpha",
policyId: "P-1",
policyVersion: 1,
tenantId: "tenant-alpha",
runId: "run:test",
verdict: new PolicyExplainVerdict(PolicyVerdictStatus.Passed, SeverityRank.Low, quiet: false, score: 0, rationale: "ok"),
evaluatedAt: DateTimeOffset.UtcNow,
metadata: ImmutableSortedDictionary.CreateRange(new[]
{
new KeyValuePair<string, string>("TraceId", "trace-1"),
new KeyValuePair<string, string>("ComponentPurl", "pkg:npm/a@1.0.0")
}));
Assert.Equal("trace-1", trace.Metadata["traceid"]);
Assert.Equal("pkg:npm/a@1.0.0", trace.Metadata["componentpurl"]);
}
}
[Fact]
public void PolicyRunStatus_ThrowsOnNegativeAttempts()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PolicyRunStatus(
runId: "run:test",
tenantId: "tenant-alpha",
policyId: "P-1",
policyVersion: 1,
mode: PolicyRunMode.Full,
status: PolicyRunExecutionStatus.Queued,
priority: PolicyRunPriority.Normal,
queuedAt: DateTimeOffset.UtcNow,
attempts: -1));
}
[Fact]
public void PolicyDiffSummary_NormalizesSeverityKeys()
{
var summary = new PolicyDiffSummary(
added: 1,
removed: 2,
unchanged: 3,
bySeverity: new[]
{
new KeyValuePair<string, PolicyDiffSeverityDelta>("critical", new PolicyDiffSeverityDelta(1, 0)),
new KeyValuePair<string, PolicyDiffSeverityDelta>("HIGH", new PolicyDiffSeverityDelta(0, 1))
});
Assert.True(summary.BySeverity.ContainsKey("Critical"));
Assert.True(summary.BySeverity.ContainsKey("High"));
}
[Fact]
public void PolicyExplainTrace_LowercasesMetadataKeys()
{
var trace = new PolicyExplainTrace(
findingId: "finding:alpha",
policyId: "P-1",
policyVersion: 1,
tenantId: "tenant-alpha",
runId: "run:test",
verdict: new PolicyExplainVerdict(PolicyVerdictStatus.Passed, SeverityRank.Low, quiet: false, score: 0, rationale: "ok"),
evaluatedAt: DateTimeOffset.UtcNow,
metadata: ImmutableSortedDictionary.CreateRange(new[]
{
new KeyValuePair<string, string>("TraceId", "trace-1"),
new KeyValuePair<string, string>("ComponentPurl", "pkg:npm/a@1.0.0")
}));
Assert.Equal("trace-1", trace.Metadata["traceid"]);
Assert.Equal("pkg:npm/a@1.0.0", trace.Metadata["componentpurl"]);
}
}

View File

@@ -1,59 +1,59 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using StellaOps.Notify.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RescanDeltaEventSampleTests
{
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
[Fact]
public void RescanDeltaEventSampleAlignsWithContracts()
{
const string fileName = "scheduler.rescan.delta@1.sample.json";
var json = LoadSample(fileName);
var notifyEvent = JsonSerializer.Deserialize<NotifyEvent>(json, SerializerOptions);
Assert.NotNull(notifyEvent);
Assert.Equal(NotifyEventKinds.SchedulerRescanDelta, notifyEvent!.Kind);
Assert.NotEqual(Guid.Empty, notifyEvent.EventId);
Assert.NotNull(notifyEvent.Payload);
Assert.Null(notifyEvent.Scope);
var payload = Assert.IsType<JsonObject>(notifyEvent.Payload);
var scheduleId = Assert.IsAssignableFrom<JsonValue>(payload["scheduleId"]).GetValue<string>();
Assert.Equal("rescan-weekly-critical", scheduleId);
var digests = Assert.IsType<JsonArray>(payload["impactedDigests"]);
Assert.Equal(2, digests.Count);
foreach (var digestNode in digests)
{
var digest = Assert.IsAssignableFrom<JsonValue>(digestNode).GetValue<string>();
Assert.StartsWith("sha256:", digest, StringComparison.Ordinal);
}
var summary = Assert.IsType<JsonObject>(payload["summary"]);
Assert.Equal(0, summary["newCritical"]!.GetValue<int>());
Assert.Equal(1, summary["newHigh"]!.GetValue<int>());
Assert.Equal(4, summary["total"]!.GetValue<int>());
var canonicalJson = NotifyCanonicalJsonSerializer.Serialize(notifyEvent);
var canonicalNode = JsonNode.Parse(canonicalJson) ?? throw new InvalidOperationException("Canonical JSON null.");
var sampleNode = JsonNode.Parse(json) ?? throw new InvalidOperationException("Sample JSON null.");
Assert.True(JsonNode.DeepEquals(sampleNode, canonicalNode), "Rescan delta event sample must remain canonical.");
}
private static string LoadSample(string fileName)
{
var path = Path.Combine(AppContext.BaseDirectory, fileName);
if (!File.Exists(path))
{
throw new FileNotFoundException($"Unable to locate sample '{fileName}'.", path);
}
return File.ReadAllText(path);
}
}
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using StellaOps.Notify.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RescanDeltaEventSampleTests
{
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
[Fact]
public void RescanDeltaEventSampleAlignsWithContracts()
{
const string fileName = "scheduler.rescan.delta@1.sample.json";
var json = LoadSample(fileName);
var notifyEvent = JsonSerializer.Deserialize<NotifyEvent>(json, SerializerOptions);
Assert.NotNull(notifyEvent);
Assert.Equal(NotifyEventKinds.SchedulerRescanDelta, notifyEvent!.Kind);
Assert.NotEqual(Guid.Empty, notifyEvent.EventId);
Assert.NotNull(notifyEvent.Payload);
Assert.Null(notifyEvent.Scope);
var payload = Assert.IsType<JsonObject>(notifyEvent.Payload);
var scheduleId = Assert.IsAssignableFrom<JsonValue>(payload["scheduleId"]).GetValue<string>();
Assert.Equal("rescan-weekly-critical", scheduleId);
var digests = Assert.IsType<JsonArray>(payload["impactedDigests"]);
Assert.Equal(2, digests.Count);
foreach (var digestNode in digests)
{
var digest = Assert.IsAssignableFrom<JsonValue>(digestNode).GetValue<string>();
Assert.StartsWith("sha256:", digest, StringComparison.Ordinal);
}
var summary = Assert.IsType<JsonObject>(payload["summary"]);
Assert.Equal(0, summary["newCritical"]!.GetValue<int>());
Assert.Equal(1, summary["newHigh"]!.GetValue<int>());
Assert.Equal(4, summary["total"]!.GetValue<int>());
var canonicalJson = NotifyCanonicalJsonSerializer.Serialize(notifyEvent);
var canonicalNode = JsonNode.Parse(canonicalJson) ?? throw new InvalidOperationException("Canonical JSON null.");
var sampleNode = JsonNode.Parse(json) ?? throw new InvalidOperationException("Sample JSON null.");
Assert.True(JsonNode.DeepEquals(sampleNode, canonicalNode), "Rescan delta event sample must remain canonical.");
}
private static string LoadSample(string fileName)
{
var path = Path.Combine(AppContext.BaseDirectory, fileName);
if (!File.Exists(path))
{
throw new FileNotFoundException($"Unable to locate sample '{fileName}'.", path);
}
return File.ReadAllText(path);
}
}

View File

@@ -1,108 +1,108 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RunStateMachineTests
{
[Fact]
public void EnsureTransition_FromQueuedToRunningSetsStartedAt()
{
var run = new Run(
id: "run-queued",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"));
var transitionTime = DateTimeOffset.Parse("2025-10-18T03:05:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Running,
transitionTime,
mutateStats: builder => builder.SetQueued(1));
Assert.Equal(RunState.Running, updated.State);
Assert.Equal(transitionTime.ToUniversalTime(), updated.StartedAt);
Assert.Equal(1, updated.Stats.Queued);
Assert.Null(updated.Error);
}
[Fact]
public void EnsureTransition_ToCompletedPopulatesFinishedAt()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var completedAt = DateTimeOffset.Parse("2025-10-18T03:10:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Completed,
completedAt,
mutateStats: builder =>
{
builder.SetQueued(1);
builder.SetCompleted(1);
});
Assert.Equal(RunState.Completed, updated.State);
Assert.Equal(completedAt.ToUniversalTime(), updated.FinishedAt);
Assert.Equal(1, updated.Stats.Completed);
}
[Fact]
public void EnsureTransition_ErrorRequiresMessage()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var timestamp = DateTimeOffset.Parse("2025-10-18T03:06:00Z");
var ex = Assert.Throws<InvalidOperationException>(
() => RunStateMachine.EnsureTransition(run, RunState.Error, timestamp));
Assert.Contains("requires a non-empty error message", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void Validate_ThrowsWhenTerminalWithoutFinishedAt()
{
var run = new Run(
id: "run-bad",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Completed,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
Assert.Throws<InvalidOperationException>(() => RunStateMachine.Validate(run));
}
[Fact]
public void RunReasonExtension_NormalizesImpactWindow()
{
var reason = new RunReason(manualReason: "delta");
var from = DateTimeOffset.Parse("2025-10-18T01:00:00+02:00");
var to = DateTimeOffset.Parse("2025-10-18T03:30:00+02:00");
var updated = reason.WithImpactWindow(from, to);
Assert.Equal(from.ToUniversalTime().ToString("O"), updated.ImpactWindowFrom);
Assert.Equal(to.ToUniversalTime().ToString("O"), updated.ImpactWindowTo);
}
}
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RunStateMachineTests
{
[Fact]
public void EnsureTransition_FromQueuedToRunningSetsStartedAt()
{
var run = new Run(
id: "run-queued",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"));
var transitionTime = DateTimeOffset.Parse("2025-10-18T03:05:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Running,
transitionTime,
mutateStats: builder => builder.SetQueued(1));
Assert.Equal(RunState.Running, updated.State);
Assert.Equal(transitionTime.ToUniversalTime(), updated.StartedAt);
Assert.Equal(1, updated.Stats.Queued);
Assert.Null(updated.Error);
}
[Fact]
public void EnsureTransition_ToCompletedPopulatesFinishedAt()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var completedAt = DateTimeOffset.Parse("2025-10-18T03:10:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Completed,
completedAt,
mutateStats: builder =>
{
builder.SetQueued(1);
builder.SetCompleted(1);
});
Assert.Equal(RunState.Completed, updated.State);
Assert.Equal(completedAt.ToUniversalTime(), updated.FinishedAt);
Assert.Equal(1, updated.Stats.Completed);
}
[Fact]
public void EnsureTransition_ErrorRequiresMessage()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var timestamp = DateTimeOffset.Parse("2025-10-18T03:06:00Z");
var ex = Assert.Throws<InvalidOperationException>(
() => RunStateMachine.EnsureTransition(run, RunState.Error, timestamp));
Assert.Contains("requires a non-empty error message", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void Validate_ThrowsWhenTerminalWithoutFinishedAt()
{
var run = new Run(
id: "run-bad",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Completed,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
Assert.Throws<InvalidOperationException>(() => RunStateMachine.Validate(run));
}
[Fact]
public void RunReasonExtension_NormalizesImpactWindow()
{
var reason = new RunReason(manualReason: "delta");
var from = DateTimeOffset.Parse("2025-10-18T01:00:00+02:00");
var to = DateTimeOffset.Parse("2025-10-18T03:30:00+02:00");
var updated = reason.WithImpactWindow(from, to);
Assert.Equal(from.ToUniversalTime().ToString("O"), updated.ImpactWindowFrom);
Assert.Equal(to.ToUniversalTime().ToString("O"), updated.ImpactWindowTo);
}
}

View File

@@ -145,13 +145,13 @@ public sealed class SamplePayloadTests
var canonical = CanonicalJsonSerializer.Serialize(trace);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void PolicyRunJob_RoundtripsThroughCanonicalSerializer()
{
var metadata = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
metadata["source"] = "cli";
metadata["trigger"] = "manual";
[Fact]
public void PolicyRunJob_RoundtripsThroughCanonicalSerializer()
{
var metadata = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
metadata["source"] = "cli";
metadata["trigger"] = "manual";
var job = new PolicyRunJob(
SchemaVersion: SchedulerSchemaVersions.PolicyRunJob,
Id: "job_20251026T140500Z",
@@ -185,7 +185,7 @@ public sealed class SamplePayloadTests
CancellationRequestedAt: null,
CancellationReason: null,
CancelledAt: null);
var canonical = CanonicalJsonSerializer.Serialize(job);
var roundtrip = CanonicalJsonSerializer.Deserialize<PolicyRunJob>(canonical);
@@ -195,8 +195,8 @@ public sealed class SamplePayloadTests
Assert.Equal(job.Status, roundtrip.Status);
Assert.Equal(job.RunId, roundtrip.RunId);
Assert.Equal("cli", roundtrip.Metadata!["source"]);
}
}
private static string ReadSample(string fileName)
{

View File

@@ -1,113 +1,113 @@
using System.Text.Json;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ScheduleSerializationTests
{
[Fact]
public void ScheduleSerialization_IsDeterministicRegardlessOfInputOrdering()
{
var selectionA = new Selector(
SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-b", "team-a" },
repositories: new[] { "app/service-api", "app/service-web" },
digests: new[] { "sha256:bb", "sha256:aa" },
includeTags: new[] { "prod", "canary" },
labels: new[]
{
new LabelSelector("env", new[] { "prod", "staging" }),
new LabelSelector("app", new[] { "web", "api" }),
},
resolvesTags: true);
var selectionB = new Selector(
scope: SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-a", "team-b" },
repositories: new[] { "app/service-web", "app/service-api" },
digests: new[] { "sha256:aa", "sha256:bb" },
includeTags: new[] { "canary", "prod" },
labels: new[]
{
new LabelSelector("app", new[] { "api", "web" }),
new LabelSelector("env", new[] { "staging", "prod" }),
},
resolvesTags: true);
var scheduleA = new Schedule(
id: "sch_001",
tenantId: "tenant-alpha",
name: "Nightly Prod",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: selectionA,
onlyIf: new ScheduleOnlyIf(lastReportOlderThanDays: 7, policyRevision: "policy@42"),
notify: new ScheduleNotify(onNewFindings: true, SeverityRank.High, includeKev: true),
limits: new ScheduleLimits(maxJobs: 1000, ratePerSecond: 25, parallelism: 4),
createdAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
createdBy: "svc_scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
updatedBy: "svc_scheduler");
var scheduleB = new Schedule(
id: scheduleA.Id,
tenantId: scheduleA.TenantId,
name: scheduleA.Name,
enabled: scheduleA.Enabled,
cronExpression: scheduleA.CronExpression,
timezone: scheduleA.Timezone,
mode: scheduleA.Mode,
selection: selectionB,
onlyIf: scheduleA.OnlyIf,
notify: scheduleA.Notify,
limits: scheduleA.Limits,
createdAt: scheduleA.CreatedAt,
createdBy: scheduleA.CreatedBy,
updatedAt: scheduleA.UpdatedAt,
updatedBy: scheduleA.UpdatedBy,
subscribers: scheduleA.Subscribers);
var jsonA = CanonicalJsonSerializer.Serialize(scheduleA);
var jsonB = CanonicalJsonSerializer.Serialize(scheduleB);
Assert.Equal(jsonA, jsonB);
using var doc = JsonDocument.Parse(jsonA);
var root = doc.RootElement;
Assert.Equal(SchedulerSchemaVersions.Schedule, root.GetProperty("schemaVersion").GetString());
Assert.Equal("analysis-only", root.GetProperty("mode").GetString());
Assert.Equal("tenant-alpha", root.GetProperty("tenantId").GetString());
var namespaces = root.GetProperty("selection").GetProperty("namespaces").EnumerateArray().Select(e => e.GetString()).ToArray();
Assert.Equal(new[] { "team-a", "team-b" }, namespaces);
}
[Theory]
[InlineData("")]
[InlineData("not-a-timezone")]
public void Schedule_ThrowsWhenTimezoneInvalid(string timezone)
{
var selection = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
Assert.ThrowsAny<Exception>(() => new Schedule(
id: "sch_002",
tenantId: "tenant-alpha",
name: "Invalid timezone",
enabled: true,
cronExpression: "0 3 * * *",
timezone: timezone,
mode: ScheduleMode.AnalysisOnly,
selection: selection,
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.UtcNow,
createdBy: "svc",
updatedAt: DateTimeOffset.UtcNow,
updatedBy: "svc"));
}
}
using System.Text.Json;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ScheduleSerializationTests
{
[Fact]
public void ScheduleSerialization_IsDeterministicRegardlessOfInputOrdering()
{
var selectionA = new Selector(
SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-b", "team-a" },
repositories: new[] { "app/service-api", "app/service-web" },
digests: new[] { "sha256:bb", "sha256:aa" },
includeTags: new[] { "prod", "canary" },
labels: new[]
{
new LabelSelector("env", new[] { "prod", "staging" }),
new LabelSelector("app", new[] { "web", "api" }),
},
resolvesTags: true);
var selectionB = new Selector(
scope: SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-a", "team-b" },
repositories: new[] { "app/service-web", "app/service-api" },
digests: new[] { "sha256:aa", "sha256:bb" },
includeTags: new[] { "canary", "prod" },
labels: new[]
{
new LabelSelector("app", new[] { "api", "web" }),
new LabelSelector("env", new[] { "staging", "prod" }),
},
resolvesTags: true);
var scheduleA = new Schedule(
id: "sch_001",
tenantId: "tenant-alpha",
name: "Nightly Prod",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: selectionA,
onlyIf: new ScheduleOnlyIf(lastReportOlderThanDays: 7, policyRevision: "policy@42"),
notify: new ScheduleNotify(onNewFindings: true, SeverityRank.High, includeKev: true),
limits: new ScheduleLimits(maxJobs: 1000, ratePerSecond: 25, parallelism: 4),
createdAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
createdBy: "svc_scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
updatedBy: "svc_scheduler");
var scheduleB = new Schedule(
id: scheduleA.Id,
tenantId: scheduleA.TenantId,
name: scheduleA.Name,
enabled: scheduleA.Enabled,
cronExpression: scheduleA.CronExpression,
timezone: scheduleA.Timezone,
mode: scheduleA.Mode,
selection: selectionB,
onlyIf: scheduleA.OnlyIf,
notify: scheduleA.Notify,
limits: scheduleA.Limits,
createdAt: scheduleA.CreatedAt,
createdBy: scheduleA.CreatedBy,
updatedAt: scheduleA.UpdatedAt,
updatedBy: scheduleA.UpdatedBy,
subscribers: scheduleA.Subscribers);
var jsonA = CanonicalJsonSerializer.Serialize(scheduleA);
var jsonB = CanonicalJsonSerializer.Serialize(scheduleB);
Assert.Equal(jsonA, jsonB);
using var doc = JsonDocument.Parse(jsonA);
var root = doc.RootElement;
Assert.Equal(SchedulerSchemaVersions.Schedule, root.GetProperty("schemaVersion").GetString());
Assert.Equal("analysis-only", root.GetProperty("mode").GetString());
Assert.Equal("tenant-alpha", root.GetProperty("tenantId").GetString());
var namespaces = root.GetProperty("selection").GetProperty("namespaces").EnumerateArray().Select(e => e.GetString()).ToArray();
Assert.Equal(new[] { "team-a", "team-b" }, namespaces);
}
[Theory]
[InlineData("")]
[InlineData("not-a-timezone")]
public void Schedule_ThrowsWhenTimezoneInvalid(string timezone)
{
var selection = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
Assert.ThrowsAny<Exception>(() => new Schedule(
id: "sch_002",
tenantId: "tenant-alpha",
name: "Invalid timezone",
enabled: true,
cronExpression: "0 3 * * *",
timezone: timezone,
mode: ScheduleMode.AnalysisOnly,
selection: selection,
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.UtcNow,
createdBy: "svc",
updatedAt: DateTimeOffset.UtcNow,
updatedBy: "svc"));
}
}

View File

@@ -1,70 +1,70 @@
using System.Text.Json.Nodes;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class SchedulerSchemaMigrationTests
{
[Fact]
public void UpgradeSchedule_DefaultsSchemaVersionWhenMissing()
{
var schedule = new Schedule(
id: "sch-01",
tenantId: "tenant-alpha",
name: "Nightly",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
createdBy: "svc-scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
updatedBy: "svc-scheduler");
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(schedule))!.AsObject();
json.Remove("schemaVersion");
var result = SchedulerSchemaMigration.UpgradeSchedule(json);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.Value.SchemaVersion);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.ToVersion);
Assert.Empty(result.Warnings);
}
[Fact]
public void UpgradeRun_StrictModeRemovesUnknownProperties()
{
var run = new Run(
id: "run-01",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T01:10:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(run))!.AsObject();
json["extraField"] = "to-be-removed";
var result = SchedulerSchemaMigration.UpgradeRun(json, strict: true);
Assert.Contains(result.Warnings, warning => warning.Contains("extraField", StringComparison.Ordinal));
}
[Fact]
using System.Text.Json.Nodes;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class SchedulerSchemaMigrationTests
{
[Fact]
public void UpgradeSchedule_DefaultsSchemaVersionWhenMissing()
{
var schedule = new Schedule(
id: "sch-01",
tenantId: "tenant-alpha",
name: "Nightly",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
createdBy: "svc-scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
updatedBy: "svc-scheduler");
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(schedule))!.AsObject();
json.Remove("schemaVersion");
var result = SchedulerSchemaMigration.UpgradeSchedule(json);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.Value.SchemaVersion);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.ToVersion);
Assert.Empty(result.Warnings);
}
[Fact]
public void UpgradeRun_StrictModeRemovesUnknownProperties()
{
var run = new Run(
id: "run-01",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T01:10:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(run))!.AsObject();
json["extraField"] = "to-be-removed";
var result = SchedulerSchemaMigration.UpgradeRun(json, strict: true);
Assert.Contains(result.Warnings, warning => warning.Contains("extraField", StringComparison.Ordinal));
}
[Fact]
public void UpgradeImpactSet_ThrowsForUnsupportedVersion()
{
var impactSet = new ImpactSet(
selector: new Selector(SelectorScope.AllImages, "tenant-alpha"),
images: Array.Empty<ImpactImage>(),
usageOnly: false,
generatedAt: DateTimeOffset.Parse("2025-10-18T02:00:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(impactSet))!.AsObject();
json["schemaVersion"] = "scheduler.impact-set@99";
usageOnly: false,
generatedAt: DateTimeOffset.Parse("2025-10-18T02:00:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(impactSet))!.AsObject();
json["schemaVersion"] = "scheduler.impact-set@99";
var ex = Assert.Throws<NotSupportedException>(() => SchedulerSchemaMigration.UpgradeImpactSet(json));
Assert.Contains("Unsupported scheduler schema version", ex.Message, StringComparison.Ordinal);