using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ScadaLink.Commons.Entities.Deployment;
using ScadaLink.Commons.Entities.Instances;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Interfaces.Services;
using ScadaLink.Commons.Messages.Deployment;
using ScadaLink.Commons.Messages.Lifecycle;
using ScadaLink.Commons.Types;
using ScadaLink.Commons.Types.Enums;
using ScadaLink.Commons.Types.Flattening;
using ScadaLink.Communication;
using ScadaLink.TemplateEngine.Flattening;
namespace ScadaLink.DeploymentManager.Tests;
///
/// WP-1/2/4/5/6/8/16: Tests for central-side DeploymentService.
///
public class DeploymentServiceTests : TestKit
{
private readonly IDeploymentManagerRepository _repo;
private readonly IFlatteningPipeline _pipeline;
private readonly CommunicationService _comms;
private readonly OperationLockManager _lockManager;
private readonly IAuditService _audit;
private readonly DeploymentService _service;
public DeploymentServiceTests()
{
_repo = Substitute.For();
_pipeline = Substitute.For();
_comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger.Instance);
_lockManager = new OperationLockManager();
_audit = Substitute.For();
var options = Options.Create(new DeploymentManagerOptions
{
OperationLockTimeout = TimeSpan.FromSeconds(5)
});
var siteRepo = Substitute.For();
_service = new DeploymentService(
_repo, siteRepo, _pipeline, _comms, _lockManager, _audit,
new DiffService(),
new DeploymentStatusNotifier(NullLogger.Instance),
options,
NullLogger.Instance);
}
// ── WP-1: Deployment flow ──
[Fact]
public async Task DeployInstanceAsync_InstanceNotFound_ReturnsFailure()
{
_repo.GetInstanceByIdAsync(1).Returns((Instance?)null);
var result = await _service.DeployInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not found", result.Error);
}
[Fact]
public async Task DeployInstanceAsync_ValidationFails_ReturnsFailure()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(1).Returns(instance);
var validationResult = new ValidationResult
{
Errors = [ValidationEntry.Error(ValidationCategory.ScriptCompilation, "Compile error")]
};
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(new FlattenedConfiguration(), "hash1", validationResult)));
var result = await _service.DeployInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.Contains("validation failed", result.Error);
}
[Fact]
public async Task DeployInstanceAsync_FlatteningFails_ReturnsFailure()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(1).Returns(instance);
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Failure("Template chain empty"));
var result = await _service.DeployInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.Contains("Validation failed", result.Error);
}
// ── WP-2: Deployment identity ──
[Fact]
public async Task DeployInstanceAsync_CreatesUniqueDeploymentId()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(1).Returns(instance);
// Pipeline succeeds
var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
var validResult = ValidationResult.Success();
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(config, "sha256:abc", validResult)));
// Capture the deployment record
DeploymentRecord? captured = null;
await _repo.AddDeploymentRecordAsync(Arg.Do(r => captured = r), Arg.Any());
// CommunicationService will throw because actor not set -- this tests the flow up to that point
try
{
await _service.DeployInstanceAsync(1, "admin");
}
catch (InvalidOperationException)
{
// Expected -- CommunicationService not initialized
}
Assert.NotNull(captured);
Assert.False(string.IsNullOrEmpty(captured!.DeploymentId));
Assert.Equal(32, captured.DeploymentId.Length); // GUID without hyphens
Assert.Equal("sha256:abc", captured.RevisionHash);
}
// ── WP-4: State transition validation ──
[Fact]
public async Task DeployInstanceAsync_EnabledInstance_AllowsDeploy()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.Enabled };
_repo.GetInstanceByIdAsync(1).Returns(instance);
var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(config, "hash", ValidationResult.Success())));
// Will fail at communication layer, but passes state validation
try { await _service.DeployInstanceAsync(1, "admin"); } catch (InvalidOperationException) { }
// If we got past state validation, the deployment record was created
await _repo.Received().AddDeploymentRecordAsync(Arg.Any(), Arg.Any());
}
// ── DeploymentManager-001: unexpected exception must not leave record InProgress ──
[Fact]
public async Task DeployInstanceAsync_CommunicationThrowsUnexpectedException_RecordMarkedFailed()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(1).Returns(instance);
var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(config, "sha256:abc", ValidationResult.Success())));
// Capture the deployment record so we can inspect its final state.
DeploymentRecord? captured = null;
await _repo.AddDeploymentRecordAsync(
Arg.Do(r => captured = r), Arg.Any());
// _comms has no actor set, so DeployInstanceAsync throws
// InvalidOperationException -- a non-timeout, non-cancellation exception.
var result = await _service.DeployInstanceAsync(1, "admin");
// The exception must be handled, not escape.
Assert.True(result.IsFailure);
Assert.Contains("Deployment failed", result.Error);
// The record must not be left stuck in InProgress.
Assert.NotNull(captured);
Assert.Equal(DeploymentStatus.Failed, captured!.Status);
Assert.NotNull(captured.ErrorMessage);
Assert.NotNull(captured.CompletedAt);
}
// ── DeploymentManager-002: failure write must not use a cancelled token ──
[Fact]
public async Task DeployInstanceAsync_FailureWrite_UsesNonCancellableToken()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(Arg.Any(), Arg.Any()).Returns(instance);
var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
_pipeline.FlattenAndValidateAsync(Arg.Any(), Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(config, "sha256:abc", ValidationResult.Success())));
DeploymentRecord? captured = null;
await _repo.AddDeploymentRecordAsync(
Arg.Do(r => captured = r), Arg.Any());
// Simulate a repository that rejects already-cancelled tokens (the
// real EF Core behaviour when the operation token is cancelled). If the
// catch block passes the operation's cancelled token, the Failed-status
// write throws and the record stays InProgress -- the exact bug.
_repo.UpdateDeploymentRecordAsync(
Arg.Is(r => r.Status == DeploymentStatus.Failed),
Arg.Is(ct => ct.IsCancellationRequested))
.Returns(_ => throw new OperationCanceledException());
_repo.SaveChangesAsync(Arg.Is(ct => ct.IsCancellationRequested))
.Returns>(_ => throw new OperationCanceledException());
// The communication call fails (no actor set). The catch block must
// persist the Failed status with a non-cancellable token, so cleanup
// succeeds even when the caller's token is cancelled.
var result = await _service.DeployInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.NotNull(captured);
Assert.Equal(DeploymentStatus.Failed, captured!.Status);
// The Failed-status write happened with a non-cancelled token.
await _repo.Received().UpdateDeploymentRecordAsync(
Arg.Is(r => r.Status == DeploymentStatus.Failed),
Arg.Is(ct => !ct.IsCancellationRequested));
}
// ── WP-6: Lifecycle commands ──
[Fact]
public async Task DisableInstanceAsync_InstanceNotFound_ReturnsFailure()
{
_repo.GetInstanceByIdAsync(1).Returns((Instance?)null);
var result = await _service.DisableInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not found", result.Error);
}
[Fact]
public async Task DisableInstanceAsync_WhenDisabled_ReturnsTransitionError()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.Disabled };
_repo.GetInstanceByIdAsync(1).Returns(instance);
var result = await _service.DisableInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not allowed", result.Error);
}
[Fact]
public async Task EnableInstanceAsync_WhenEnabled_ReturnsTransitionError()
{
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.Enabled };
_repo.GetInstanceByIdAsync(1).Returns(instance);
var result = await _service.EnableInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not allowed", result.Error);
}
[Fact]
public async Task DeleteInstanceAsync_InstanceNotFound_ReturnsFailure()
{
_repo.GetInstanceByIdAsync(1).Returns((Instance?)null);
var result = await _service.DeleteInstanceAsync(1, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not found", result.Error);
}
// ── DeploymentManager-004: site-success but central-delete-failure must not escape uncaught ──
[Fact]
public async Task DeleteInstanceAsync_SiteSucceeds_CentralDeleteFails_ReturnsDistinctFailure()
{
// The site destroys the Instance Actor and removes its config (response
// Success), but the central record removal throws. The exception must
// NOT propagate uncaught -- it must be surfaced as a distinct failure so
// an operator can reconcile the orphaned central record.
var instance = new Instance("OrphanInst") { Id = 30, SiteId = 1, State = InstanceState.Enabled };
_repo.GetInstanceByIdAsync(30, Arg.Any()).Returns(instance);
_repo.DeleteInstanceAsync(30, Arg.Any())
.Returns(_ => throw new InvalidOperationException("db unavailable"));
var commActor = Sys.ActorOf(Props.Create(() =>
new ReconcileProbeActor(siteHash: "sha256:x", failQuery: false)));
var service = CreateServiceWithCommActor(commActor);
var result = await service.DeleteInstanceAsync(30, "admin");
// The failure is surfaced (not thrown) and clearly says the site
// succeeded but the central record could not be removed.
Assert.True(result.IsFailure);
Assert.Contains("site", result.Error, StringComparison.OrdinalIgnoreCase);
Assert.Contains("central", result.Error, StringComparison.OrdinalIgnoreCase);
}
// ── WP-8: Deployment comparison ──
[Fact]
public async Task GetDeploymentComparisonAsync_NoSnapshot_ReturnsFailure()
{
_repo.GetDeployedSnapshotByInstanceIdAsync(1).Returns((DeployedConfigSnapshot?)null);
var result = await _service.GetDeploymentComparisonAsync(1);
Assert.True(result.IsFailure);
Assert.Contains("No deployed snapshot", result.Error);
}
[Fact]
public async Task GetDeploymentComparisonAsync_SameHash_NotStale()
{
var snapshot = new DeployedConfigSnapshot("dep1", "sha256:abc", "{}")
{
InstanceId = 1,
DeployedAt = DateTimeOffset.UtcNow
};
_repo.GetDeployedSnapshotByInstanceIdAsync(1).Returns(snapshot);
var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(config, "sha256:abc", ValidationResult.Success())));
var result = await _service.GetDeploymentComparisonAsync(1);
Assert.True(result.IsSuccess);
Assert.False(result.Value.IsStale);
}
[Fact]
public async Task GetDeploymentComparisonAsync_DifferentHash_IsStale()
{
var snapshot = new DeployedConfigSnapshot("dep1", "sha256:abc", "{}")
{
InstanceId = 1,
DeployedAt = DateTimeOffset.UtcNow
};
_repo.GetDeployedSnapshotByInstanceIdAsync(1).Returns(snapshot);
var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(config, "sha256:xyz", ValidationResult.Success())));
var result = await _service.GetDeploymentComparisonAsync(1);
Assert.True(result.IsSuccess);
Assert.True(result.Value.IsStale);
}
// ── DeploymentManager-007: comparison must produce a structured diff ──
[Fact]
public async Task GetDeploymentComparisonAsync_ProducesStructuredDiff()
{
// The deployed snapshot has one attribute; the current template-derived
// config has a different attribute. The comparison must surface a real
// Added/Removed diff via the TemplateEngine DiffService, not just a
// boolean staleness flag.
var deployedConfig = new FlattenedConfiguration
{
InstanceUniqueName = "DiffInst",
Attributes = [new ResolvedAttribute { CanonicalName = "OldAttr", DataType = "Int" }]
};
var snapshot = new DeployedConfigSnapshot(
"dep1", "sha256:old", System.Text.Json.JsonSerializer.Serialize(deployedConfig))
{
InstanceId = 40,
DeployedAt = DateTimeOffset.UtcNow
};
_repo.GetDeployedSnapshotByInstanceIdAsync(40, Arg.Any()).Returns(snapshot);
var currentConfig = new FlattenedConfiguration
{
InstanceUniqueName = "DiffInst",
Attributes = [new ResolvedAttribute { CanonicalName = "NewAttr", DataType = "Int" }]
};
_pipeline.FlattenAndValidateAsync(40, Arg.Any())
.Returns(Result.Success(
new FlatteningPipelineResult(currentConfig, "sha256:new", ValidationResult.Success())));
var result = await _service.GetDeploymentComparisonAsync(40);
Assert.True(result.IsSuccess);
Assert.True(result.Value.IsStale);
// A structured diff is present with the added and removed attributes.
Assert.NotNull(result.Value.Diff);
Assert.True(result.Value.Diff!.HasChanges);
Assert.Contains(result.Value.Diff.AttributeChanges,
c => c.CanonicalName == "NewAttr" && c.ChangeType == DiffChangeType.Added);
Assert.Contains(result.Value.Diff.AttributeChanges,
c => c.CanonicalName == "OldAttr" && c.ChangeType == DiffChangeType.Removed);
}
// ── WP-2: GetDeploymentStatusAsync ──
[Fact]
public async Task GetDeploymentStatusAsync_ReturnsRecordByDeploymentId()
{
var record = new DeploymentRecord("dep1", "admin")
{
Status = DeploymentStatus.Success
};
_repo.GetDeploymentByDeploymentIdAsync("dep1").Returns(record);
var result = await _service.GetDeploymentStatusAsync("dep1");
Assert.NotNull(result);
Assert.Equal("dep1", result!.DeploymentId);
Assert.Equal(DeploymentStatus.Success, result.Status);
}
// ── Audit logging ──
[Fact]
public async Task DeployInstanceAsync_FlatteningFails_DoesNotReachAudit()
{
// DeploymentManager-011: this test previously asserted nothing. A
// flatten failure returns before any site communication, so no audit
// entry is written.
var instance = new Instance("TestInst") { Id = 1, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(1).Returns(instance);
_pipeline.FlattenAndValidateAsync(1, Arg.Any())
.Returns(Result.Failure("Error"));
await _service.DeployInstanceAsync(1, "admin");
await _audit.DidNotReceive().LogAsync(
Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(),
Arg.Any(), Arg.Any