Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeTestDb.cs
T
Joseph Doherty 90de55535d fix(config): #1040 #1049 script FKs, unique ZTag/SAPID indexes, reservation ledger retired
One migration, ScriptForeignKeysAndExternalIdUniqueness:
- FK_VirtualTag_Script / FK_ScriptedAlarm_Script (Restrict) onto Script.ScriptId, which becomes
  NOT NULL and an alternate key (unique constraint UX_Script_LogicalId replaces the index).
- UX_Equipment_ZTag / UX_Equipment_SAPID filtered UNIQUE indexes (blank = no identifier, the
  deploy gate's reading) replace the non-unique IX_ ones.
- ExternalIdReservation + sp_ReleaseExternalIdReservation dropped (decision: retire — no writer
  since the generation model; uniqueness is gate + indexes). The /reservations page, query,
  ReservationKind, DraftSnapshot.ActiveReservations and the reservation pre-flight rule go too.
- A read-only pre-check THROWs 51049 naming every offending row class (NULL ScriptId, dangling
  VirtualTag/ScriptedAlarm script, duplicated ZTag/SAPID, any reservation row) and changes
  nothing; Down restores the previous shape.

Authoring mirrors so the constraints are never the first to say no: UnsTreeService refuses a
missing script for VirtualTag/ScriptedAlarm create/update, and a ZTag/SAPID another equipment
holds on create/update/import (owner named; import keeps the clean rows); values stored trimmed.
ScriptEdit maps a concurrent-bind FK refusal to a message. Migration pre-check, Down round-trip,
FK and index behaviour pinned against real SQL with positive controls.
2026-12-03 15:14:26 -05:00

162 lines
6.5 KiB
C#

using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// Shared in-memory fixture for <c>UnsTreeService</c> structural tests. Builds an
/// <see cref="OtOpcUaConfigDbContext"/> over a named InMemory database and seeds a small,
/// deterministic UNS hierarchy: enterprise "zb" across two clusters (MAIN populated,
/// SITE-A intentionally empty), a virtual tag on one equipment node (so the per-equipment
/// virtual-tag count join can be exercised), plus a v3 Raw-tree slice
/// (Driver→Device→Tag). Under v3, tags are Raw-only — they no longer bind to equipment — so
/// the per-equipment driver-tag count is always zero; only the virtual-tag count join remains.
/// </summary>
internal static class UnsTreeTestDb
{
/// <summary>The equipment that carries the seeded tags and virtual tag.</summary>
public const string SeededEquipmentId = "EQ-000000000001";
/// <summary>The cluster that has no areas, used to cover the empty-cluster case.</summary>
public const string EmptyClusterId = "SITE-A";
/// <summary>The populated cluster with the area→line→equipment path.</summary>
public const string PopulatedClusterId = "MAIN";
/// <summary>Creates a context over a fresh, uniquely-named InMemory database.</summary>
public static OtOpcUaConfigDbContext Create() => CreateNamed($"uns-{Guid.NewGuid():N}");
/// <summary>Creates a context bound to the supplied InMemory database name.</summary>
public static OtOpcUaConfigDbContext CreateNamed(string name) =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseInMemoryDatabase(name)
.Options);
/// <summary>
/// Returns an <see cref="IDbContextFactory{TContext}"/> whose contexts all share the
/// supplied InMemory database name, so data seeded by <see cref="SeedNamed"/> is visible
/// to the service under test.
/// </summary>
public static IDbContextFactory<OtOpcUaConfigDbContext> Factory(string name) => new NamedFactory(name);
/// <summary>Seeds the fixture into the supplied (already-bound) context and saves.</summary>
public static void Seed(OtOpcUaConfigDbContext db)
{
// Two clusters under the same enterprise; only MAIN gets a hierarchy.
db.ServerClusters.Add(new ServerCluster
{
ClusterId = PopulatedClusterId,
Name = "Main",
Enterprise = "zb",
Site = "warsaw-west",
RedundancyMode = RedundancyMode.None,
CreatedBy = "test",
});
db.ServerClusters.Add(new ServerCluster
{
ClusterId = EmptyClusterId,
Name = "Site A",
Enterprise = "zb",
Site = "site-a",
RedundancyMode = RedundancyMode.None,
CreatedBy = "test",
});
// MAIN: one area → one line → one equipment.
db.UnsAreas.Add(new UnsArea
{
UnsAreaId = "AREA-1",
ClusterId = PopulatedClusterId,
Name = "assembly",
});
db.UnsLines.Add(new UnsLine
{
UnsLineId = "LINE-1",
UnsAreaId = "AREA-1",
Name = "line-a",
});
db.Equipment.Add(new Equipment
{
EquipmentId = SeededEquipmentId,
EquipmentUuid = Guid.NewGuid(),
UnsLineId = "LINE-1",
Name = "machine-1",
MachineCode = "machine_001",
});
// v3 Raw tree: a device → two raw tags. Tags are Raw-only and no longer bind to equipment,
// so they do NOT contribute to any per-equipment count. The owning DriverInstance is left
// unseeded on purpose — no structural test reads it, and seeding one would pollute the
// per-cluster driver-list assertions in UnsTreeServiceLoadEditTests (EF InMemory does not
// enforce the Device→Driver FK).
db.Devices.Add(new Device
{
DeviceId = "DEV-1",
DriverInstanceId = "DRV-1",
Name = "device-1",
DeviceConfig = "{}",
});
db.Tags.Add(new Tag
{
TagId = "TAG-1",
DeviceId = "DEV-1",
Name = "speed",
DataType = "Float",
AccessLevel = TagAccessLevel.Read,
TagConfig = "{}",
});
db.Tags.Add(new Tag
{
TagId = "TAG-2",
DeviceId = "DEV-1",
Name = "running",
DataType = "Boolean",
AccessLevel = TagAccessLevel.Read,
TagConfig = "{}",
});
// The script the seeded virtual tag (and the scripted-alarm tests) name — FK_VirtualTag_Script /
// FK_ScriptedAlarm_Script (lmxopcua#1040) and the service's script-existence check require it.
db.Scripts.Add(new Script
{
ScriptId = "SCRIPT-1", Name = "seeded", SourceCode = "return 1;", SourceHash = new string('0', 64),
});
// One virtual tag on the seeded equipment → per-equipment virtual-tag ChildCount 1.
db.VirtualTags.Add(new VirtualTag
{
VirtualTagId = "VTAG-1",
EquipmentId = SeededEquipmentId,
Name = "computed",
DataType = "Double",
ScriptId = "SCRIPT-1",
});
db.SaveChanges();
}
/// <summary>Seeds the fixture into a context bound to the supplied InMemory database name.</summary>
public static void SeedNamed(string name)
{
using var db = CreateNamed(name);
Seed(db);
}
/// <summary>
/// Minimal <see cref="IDbContextFactory{TContext}"/> that hands back contexts sharing a
/// single InMemory database name — the test-side stand-in for the runtime factory, which IS
/// pooled (<c>AddPooledDbContextFactory</c> in <c>ServiceCollectionExtensions.AddOtOpcUaConfigDb</c>).
/// This stand-in builds a fresh context per call rather than renting one: pooling is a
/// construction-cost optimisation, and nothing under test can observe the difference.
/// </summary>
private sealed class NamedFactory(string name) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public OtOpcUaConfigDbContext CreateDbContext() => CreateNamed(name);
public Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default) =>
Task.FromResult(CreateNamed(name));
}
}