using System.Text.Json;
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
///
/// CLI-2 (WP2 task 2.8): the site, data-connection and api-method update handlers are
/// preserve-if-null. A null command field keeps the stored value; an empty string
/// clears an optional field. Before the fix every field was assigned unconditionally,
/// so site update --id 3 --name X nulled both gRPC addresses and
/// api-method update --script … reset the timeout to 30 and dropped both
/// definitions.
///
public class PartialUpdateHandlerTests : TestKit, IDisposable
{
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
private readonly ISiteRepository _siteRepo = Substitute.For();
private readonly IInboundApiRepository _apiRepo = Substitute.For();
/// Initializes the harness with stubbed repositories.
public PartialUpdateHandlerTests()
{
_services.AddScoped(_ => _siteRepo);
_services.AddScoped(_ => _apiRepo);
_services.AddScoped(_ => Substitute.For());
_apiRepo.SaveChangesAsync(Arg.Any()).Returns(1);
}
///
void IDisposable.Dispose() => Shutdown();
private IActorRef CreateActor() =>
Sys.ActorOf(Props.Create(() => new ManagementActor(
_services.BuildServiceProvider(), NullLogger.Instance)));
private static ManagementEnvelope Admin(object command) =>
new(new AuthenticatedUser("admin", "Admin", new[] { "Administrator", "Designer" }, Array.Empty()),
command, Guid.NewGuid().ToString("N"));
private static Site StoredSite() => new("Plant", "site-3")
{
Id = 3,
Description = "desc",
NodeAAddress = "akka.tcp://scadabridge@a:8081",
NodeBAddress = "akka.tcp://scadabridge@b:8081",
GrpcNodeAAddress = "http://a:8083",
GrpcNodeBAddress = "http://b:8083",
};
/// A name-only site update keeps the description and all four addresses.
[Fact]
public void UpdateSite_NameOnly_PreservesEveryOtherField()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, "Plant 3", null)));
ExpectMsg(TimeSpan.FromSeconds(10));
Assert.Equal("Plant 3", site.Name);
Assert.Equal("desc", site.Description);
Assert.Equal("akka.tcp://scadabridge@a:8081", site.NodeAAddress);
Assert.Equal("akka.tcp://scadabridge@b:8081", site.NodeBAddress);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
Assert.Equal("http://b:8083", site.GrpcNodeBAddress);
}
/// An address-only site update keeps the name; an empty string clears a field.
[Fact]
public void UpdateSite_EmptyString_ClearsField_NullNameKeepsName()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, "", GrpcNodeBAddress: "")));
ExpectMsg(TimeSpan.FromSeconds(10));
Assert.Equal("Plant", site.Name);
Assert.Null(site.Description);
Assert.Null(site.GrpcNodeBAddress);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// A preserved address is still validated; a malformed incoming one is refused.
[Fact]
public void UpdateSite_MalformedIncomingAddress_IsRefused()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, null, GrpcNodeAAddress: "a:8083")));
var error = ExpectMsg(TimeSpan.FromSeconds(10));
Assert.Contains("GrpcNodeAAddress", error.Error);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// A name-only data-connection update keeps protocol, both configs and the retry count.
[Fact]
public void UpdateDataConnection_NameOnly_PreservesConfigsAndRetryCount()
{
var conn = new DataConnection("c1", "OpcUa", 1)
{
Id = 7,
PrimaryConfiguration = """{"Endpoint":"opc.tcp://p","UserIdentity":{"Password":"pw"}}""",
BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""",
FailoverRetryCount = 9,
};
_siteRepo.GetDataConnectionByIdAsync(7, Arg.Any()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, "renamed", null, null)));
ExpectMsg(TimeSpan.FromSeconds(10));
Assert.Equal("renamed", conn.Name);
Assert.Equal("OpcUa", conn.Protocol);
Assert.Contains("\"pw\"", conn.PrimaryConfiguration);
Assert.Equal("""{"Endpoint":"opc.tcp://b"}""", conn.BackupConfiguration);
Assert.Equal(9, conn.FailoverRetryCount);
}
/// An empty backup configuration removes the backup endpoint.
[Fact]
public void UpdateDataConnection_EmptyBackup_RemovesBackup()
{
var conn = new DataConnection("c1", "OpcUa", 1)
{
Id = 7,
PrimaryConfiguration = """{"Endpoint":"opc.tcp://p"}""",
BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""",
};
_siteRepo.GetDataConnectionByIdAsync(7, Arg.Any()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, null, null, null, "", 3)));
ExpectMsg(TimeSpan.FromSeconds(10));
Assert.Null(conn.BackupConfiguration);
Assert.Equal("""{"Endpoint":"opc.tcp://p"}""", conn.PrimaryConfiguration);
Assert.Equal(3, conn.FailoverRetryCount);
}
/// A script-only api-method update keeps the timeout and both definitions.
[Fact]
public void UpdateApiMethod_ScriptOnly_PreservesTimeoutAndDefinitions()
{
var method = new ApiMethod("M", "return 1;")
{
Id = 5,
TimeoutSeconds = 120,
ParameterDefinitions = """[{"name":"x","type":"Integer"}]""",
ReturnDefinition = """[{"name":"y","type":"Integer"}]""",
};
_apiRepo.GetApiMethodByIdAsync(5, Arg.Any()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, "return 2;", null, null, null)));
ExpectMsg(TimeSpan.FromSeconds(10));
Assert.Equal("return 2;", method.Script);
Assert.Equal(120, method.TimeoutSeconds);
Assert.Equal("""[{"name":"x","type":"Integer"}]""", method.ParameterDefinitions);
Assert.Equal("""[{"name":"y","type":"Integer"}]""", method.ReturnDefinition);
}
/// A timeout-only api-method update keeps the script; "" clears a definition.
[Fact]
public void UpdateApiMethod_TimeoutOnly_KeepsScript_EmptyClearsDefinition()
{
var method = new ApiMethod("M", "return 1;")
{
Id = 5,
TimeoutSeconds = 30,
ParameterDefinitions = """[{"name":"x","type":"Integer"}]""",
};
_apiRepo.GetApiMethodByIdAsync(5, Arg.Any()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, null, 90, "", null)));
ExpectMsg(TimeSpan.FromSeconds(10));
Assert.Equal("return 1;", method.Script);
Assert.Equal(90, method.TimeoutSeconds);
Assert.Null(method.ParameterDefinitions);
}
///
/// Wire compatibility: an older CLI always sends every field (non-null ints included);
/// that payload must still deserialize into the now-nullable records with its values.
///
[Fact]
public void OlderClientPayloads_StillDeserialize()
{
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var dc = JsonSerializer.Deserialize(
"""{"DataConnectionId":7,"Name":"X","Protocol":"OpcUa","PrimaryConfiguration":"{}","BackupConfiguration":null,"FailoverRetryCount":3}""",
options)!;
Assert.Equal(new UpdateDataConnectionCommand(7, "X", "OpcUa", "{}", null, 3), dc);
var api = JsonSerializer.Deserialize(
"""{"ApiMethodId":5,"Script":"return 1;","TimeoutSeconds":30,"ParameterDefinitions":null,"ReturnDefinition":null}""",
options)!;
Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", 30, null, null), api);
var site = JsonSerializer.Deserialize(
"""{"SiteId":3,"Name":"S","Description":null}""", options)!;
Assert.Equal(new UpdateSiteCommand(3, "S", null), site);
}
}