using System.Collections;
using System.Reflection;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
///
/// Gitea #977 (U-2 / U-3 — "omitting a field silently reopens staleness"). The planner's job is to notice EVERY
/// difference between two compositions; anything it does not see produces an EMPTY plan, and an empty plan returns
/// before a single sink call. Scripted-alarm Enabled/AlarmType/Severity/Name and a UNS
/// Line's parent Area were exactly that: fields on the composition no diff ever looked at.
/// This test is the guard against the next one. It REFLECTS over every list on
/// and every property of each element record, builds two compositions
/// differing in exactly that one property (or in the presence of one element), and requires a non-empty plan. A
/// field added to a composition record — or a new list added to the composition — that the planner does not diff
/// fails here by name, instead of shipping as a deploy that changes nothing.
///
public sealed class AddressSpacePlannerFieldCoverageTests
{
/// Composition lists deliberately outside the diff, each with the reason. Keep this list short.
private static readonly IReadOnlyDictionary ExemptLists = new Dictionary(StringComparer.Ordinal)
{
// The retired v2 equipment-namespace tag path: structurally empty in v3 (both the composer and the artifact
// decode emit an empty array), materialised by nothing. Device values reach equipment as UnsReferenceVariables.
[nameof(AddressSpaceComposition.EquipmentTags)] = "retired v2 equipment-tag path, always empty in v3",
};
public static TheoryData CompositionLists()
{
var data = new TheoryData();
foreach (var p in ListProperties()) data.Add(p.Name);
return data;
}
public static TheoryData CompositionFields()
{
var data = new TheoryData();
foreach (var list in ListProperties())
{
if (ExemptLists.ContainsKey(list.Name)) continue;
foreach (var field in RecordFields(ElementType(list))) data.Add(list.Name, field.Name!);
}
return data;
}
[Theory]
[MemberData(nameof(CompositionLists))]
public void Adding_or_removing_one_element_of_every_composition_list_is_seen_by_the_planner(string listName)
{
if (ExemptLists.ContainsKey(listName)) return;
var list = ListProperties().Single(p => p.Name == listName);
var element = Sample(ElementType(list));
var without = Composition();
var with = Composition((list, element));
AddressSpacePlanner.Compute(without, with).IsEmpty.ShouldBeFalse($"adding one {listName} element");
AddressSpacePlanner.Compute(with, without).IsEmpty.ShouldBeFalse($"removing one {listName} element");
// Positive control: the SAME content twice (fresh instances) is not a change, or every check above is vacuous.
AddressSpacePlanner.Compute(with, Composition((list, Sample(ElementType(list))))).IsEmpty
.ShouldBeTrue($"an unchanged {listName} element must diff empty");
}
[Theory]
[MemberData(nameof(CompositionFields))]
public void Changing_any_single_field_of_any_composition_record_is_seen_by_the_planner(string listName, string fieldName)
{
var list = ListProperties().Single(p => p.Name == listName);
var type = ElementType(list);
var baseline = Sample(type);
var mutated = Mutate(baseline, fieldName);
mutated.ShouldNotBe(baseline, $"{type.Name}'s record equality ignores {fieldName} (or the test could not mutate it)");
var plan = AddressSpacePlanner.Compute(Composition((list, baseline)), Composition((list, mutated)));
plan.IsEmpty.ShouldBeFalse(
$"{type.Name}.{fieldName} changed but the planner produced an EMPTY plan — the deploy would change nothing. " +
"Diff the field in AddressSpacePlanner.Compute (and decide in AddressSpaceChangeClassifier whether it is surgical).");
}
[Fact]
public void Every_composition_list_is_either_covered_or_explicitly_exempt()
{
// A list nobody wired into the theories would never run them. ListProperties is the same reflection both use,
// so this pins the shape: lists, of records, all reachable.
var lists = ListProperties().ToList();
lists.Count.ShouldBeGreaterThanOrEqualTo(11);
foreach (var exempt in ExemptLists.Keys) lists.ShouldContain(p => p.Name == exempt);
}
// ----- reflection helpers -----
private static IEnumerable ListProperties() =>
typeof(AddressSpaceComposition)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>))
.OrderBy(p => p.Name, StringComparer.Ordinal);
private static Type ElementType(PropertyInfo list) => list.PropertyType.GetGenericArguments()[0];
/// The positional members of a record: the parameters of its widest constructor.
private static IEnumerable RecordFields(Type t) => PrimaryCtor(t).GetParameters();
private static ConstructorInfo PrimaryCtor(Type t) =>
t.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
.Where(c => !(c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == t)) // copy ctor
.OrderByDescending(c => c.GetParameters().Length)
.First();
private static AddressSpaceComposition Composition(params (PropertyInfo List, object Element)[] items)
{
var c = new AddressSpaceComposition(
Array.Empty(), Array.Empty(), Array.Empty(),
Array.Empty(), Array.Empty());
foreach (var (list, element) in items)
{
var array = Array.CreateInstance(ElementType(list), 1);
array.SetValue(element, 0);
c = With(c, list, array);
}
return c;
}
/// Sets one list on a copy of the composition — the positional ones through the ctor, the init-only
/// ones through their setter on the record's clone.
private static AddressSpaceComposition With(AddressSpaceComposition c, PropertyInfo list, object value)
{
var clone = (AddressSpaceComposition)typeof(AddressSpaceComposition)
.GetMethod("$", BindingFlags.Public | BindingFlags.Instance)!.Invoke(c, null)!;
var backing = typeof(AddressSpaceComposition).GetField($"<{list.Name}>k__BackingField",
BindingFlags.NonPublic | BindingFlags.Instance)!;
backing.SetValue(clone, value);
return clone;
}
private static object Sample(Type t)
{
var ctor = PrimaryCtor(t);
var args = ctor.GetParameters().Select(p => SampleValue(p.ParameterType, p.Name!)).ToArray();
return ctor.Invoke(args);
}
private static object Mutate(object record, string fieldName)
{
var t = record.GetType();
var ctor = PrimaryCtor(t);
var args = ctor.GetParameters()
.Select(p =>
{
var current = t.GetProperty(p.Name!)!.GetValue(record);
return p.Name == fieldName ? MutatedValue(p.ParameterType, current) : current;
})
.ToArray();
return ctor.Invoke(args);
}
private static object? SampleValue(Type t, string name)
{
var underlying = Nullable.GetUnderlyingType(t);
if (t == typeof(string)) return $"{name}-v";
if (t == typeof(bool)) return false;
if (t == typeof(int)) return 1;
if (t == typeof(uint)) return 1u;
if (underlying is not null) return null; // int?, uint?, bool? ⇒ start null
if (t.IsEnum) return Enum.GetValues(t).GetValue(0);
if (t == typeof(IReadOnlyList)) return new[] { $"{name}-a" };
if (t.IsClass) return null; // nested records (e.g. alarm info) ⇒ start null
throw new NotSupportedException($"no sample for {t} ({name}) — extend the field-coverage test");
}
private static object? MutatedValue(Type t, object? current)
{
var underlying = Nullable.GetUnderlyingType(t);
if (t == typeof(string)) return (string?)current + "-x";
if (t == typeof(bool)) return !(bool)current!;
if (t == typeof(int)) return (int)current! + 1;
if (t == typeof(uint)) return (uint)current! + 1;
if (underlying is not null)
return current is null ? Convert.ChangeType(underlying == typeof(bool) ? true : 7, underlying) : null;
if (t.IsEnum)
{
var values = Enum.GetValues(t);
return values.GetValue((Array.IndexOf(values, current) + 1) % values.Length);
}
if (t == typeof(IReadOnlyList)) return ((IEnumerable)current!).Cast().Append("extra").ToArray();
if (t.IsClass) return current is null ? Sample(t) : null;
throw new NotSupportedException($"cannot mutate {t} — extend the field-coverage test");
}
}