using NSubstitute; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates; using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening; using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation; namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests; /// /// Pins PreviewAsync: the Create Instance page must see exactly the attribute /// set a freshly created, un-overridden instance flattens to — including composed /// module members — without any instance row existing. /// public class FlatteningPipelinePreviewTests { private const int TemplateId = 10, ModuleTemplateId = 11, SiteId = 20, InstanceId = 30; private readonly ITemplateEngineRepository _templateRepo = Substitute.For(); private readonly ISiteRepository _siteRepo = Substitute.For(); private readonly ISharedSchemaRepository _sharedSchemaRepo = Substitute.For(); private readonly FlatteningPipeline _sut; /// Initializes the test class with in-memory repositories and the pipeline under test. public FlatteningPipelinePreviewTests() { _sharedSchemaRepo.ListAsync(Arg.Any()).Returns([]); _sut = new FlatteningPipeline(_templateRepo, _siteRepo, new FlatteningService(), new ValidationService(), new RevisionHashService(), _sharedSchemaRepo, new TemplateGraphWatermark()); // Parent template with one direct data-sourced attribute, composing a module with one. var module = new Template("Receiver") { Id = ModuleTemplateId }; module.Attributes.Add(new TemplateAttribute("MoveInFlag") { DataType = DataType.Boolean, DataSourceReference = "MoveInFlag" }); var parent = new Template("Line") { Id = TemplateId }; parent.Attributes.Add(new TemplateAttribute("Running") { DataType = DataType.Boolean, DataSourceReference = "Running" }); var composition = new TemplateComposition("Left") { TemplateId = TemplateId, ComposedTemplateId = ModuleTemplateId }; _templateRepo.GetTemplateWithChildrenAsync(TemplateId, Arg.Any()).Returns(parent); _templateRepo.GetTemplateWithChildrenAsync(ModuleTemplateId, Arg.Any()).Returns(module); // Compositions ride on the loaded template (GetTemplateWithChildrenAsync Includes them). parent.Compositions.Add(composition); _templateRepo.GetAllSharedScriptsAsync(Arg.Any()).Returns([]); _templateRepo.GetInstanceByIdAsync(InstanceId, Arg.Any()) .Returns(new Instance("Line-01") { Id = InstanceId, TemplateId = TemplateId, SiteId = SiteId }); _siteRepo.GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any()) .Returns([new DataConnection("MxGateway", "MxGateway", SiteId) { Id = 1 }]); } /// Verifies that previewing matches flattening a freshly created instance. /// A task that represents the asynchronous operation. [Fact] public async Task Preview_matches_flatten_of_fresh_instance() { var preview = await _sut.PreviewAsync(TemplateId, SiteId); var real = await _sut.FlattenAndValidateAsync(InstanceId, validateScripts: false); // Result.Error throws on a success, so the message is only read on failure. Assert.True(preview.IsSuccess, preview.IsSuccess ? "" : preview.Error); Assert.True(real.IsSuccess, real.IsSuccess ? "" : real.Error); var expected = real.Value.Configuration.Attributes .Select(a => (a.CanonicalName, a.DefaultDataSourceReference ?? a.DataSourceReference)) .OrderBy(x => x.Item1, StringComparer.Ordinal).ToList(); var actual = preview.Value.Attributes .Select(a => (a.CanonicalName, a.DefaultDataSourceReference ?? a.DataSourceReference)) .OrderBy(x => x.Item1, StringComparer.Ordinal).ToList(); Assert.Equal(expected, actual); Assert.Contains(actual, a => a.Item1 == "Left.MoveInFlag"); } /// Verifies that previewing an unknown template fails. /// A task that represents the asynchronous operation. [Fact] public async Task Preview_unknown_template_fails() { var r = await _sut.PreviewAsync(999, SiteId); Assert.True(r.IsFailure); } /// Verifies that previewing never touches the instance repository. /// A task that represents the asynchronous operation. [Fact] public async Task Preview_never_touches_instance_repository() { await _sut.PreviewAsync(TemplateId, SiteId); await _templateRepo.DidNotReceive().GetInstanceByIdAsync(Arg.Any(), Arg.Any()); } /// /// review 2026-10-21 04/U5: the composition walk reads compositions off the already-loaded /// template (GetTemplateWithChildrenAsync Includes them) and issues no separate /// per-template composition query — while still resolving the composed module. /// /// A task that represents the asynchronous operation. [Fact] public async Task Flatten_reads_compositions_from_loaded_template_without_extra_query() { var result = await _sut.FlattenAndValidateAsync(InstanceId, validateScripts: false); Assert.True(result.IsSuccess, result.IsSuccess ? "" : result.Error); Assert.Contains(result.Value.Configuration.Attributes, a => a.CanonicalName == "Left.MoveInFlag"); await _templateRepo.DidNotReceive().GetCompositionsByTemplateIdAsync( Arg.Any(), Arg.Any()); } /// /// review 2026-10-21 04/P2: the hash-only entry point returns exactly the hash the /// validating entry point does (so staleness verdicts cannot drift from the deploy and /// comparison paths), without the validation-only shared-script and schema-library loads. /// /// A task that represents the asynchronous operation. [Fact] public async Task ComputeRevisionHash_matches_validating_flatten_without_validation_loads() { var hashOnly = await _sut.ComputeRevisionHashAsync(InstanceId); await _templateRepo.DidNotReceive().GetAllSharedScriptsAsync(Arg.Any()); await _sharedSchemaRepo.DidNotReceive().ListAsync(Arg.Any()); var full = await _sut.FlattenAndValidateAsync(InstanceId, validateScripts: false); Assert.True(hashOnly.IsSuccess, hashOnly.IsSuccess ? "" : hashOnly.Error); Assert.True(full.IsSuccess, full.IsSuccess ? "" : full.Error); Assert.Equal(full.Value.RevisionHash, hashOnly.Value); } /// The hash-only entry point fails like the validating one for an unknown instance. /// A task that represents the asynchronous operation. [Fact] public async Task ComputeRevisionHash_unknown_instance_fails() { var r = await _sut.ComputeRevisionHashAsync(999_999); Assert.True(r.IsFailure); } }