Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataContractsTests.cs
T
2026-11-23 09:55:03 -05:00

215 lines
11 KiB
C#

using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P01")]
public sealed class GrpcDataContractsTests
{
[Fact]
public void Realm_and_serving_provenance_are_part_of_view_identity()
{
var address = new DataAddress("cluster", "urn:test", "string", "same/path");
var raw = new DataView(address, DataRealm.Raw, "mapping", 1, "subject");
var uns = raw with { Realm = DataRealm.Uns };
raw.ShouldNotBe(uns);
var first = new ServingIdentity("node-a", "incarnation", "primary", 1, 2);
var second = first with { NodeId = "node-b" };
first.ShouldNotBe(second);
new DataTarget(DataTargetMode.Node, "cluster", "node-a").Validate();
Should.Throw<ArgumentException>(() => new DataTarget(DataTargetMode.Node, "cluster", null).Validate());
}
[Fact]
public void Required_enums_reject_unspecified_and_unknown_values()
{
Should.Throw<ArgumentOutOfRangeException>(() => DataContractValidation.Required(DataRealm.Unspecified));
Should.Throw<ArgumentOutOfRangeException>(() => DataContractValidation.Required((DataTargetMode)99));
Should.Throw<ArgumentOutOfRangeException>(() => new DataWriteOutcome(DataWriteState.Unspecified, 0, null).Validate());
}
[Fact]
public void Only_driver_confirmed_success_is_success()
{
new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null).IsConfirmedSuccess.ShouldBeTrue();
new DataWriteOutcome(DataWriteState.AcceptedUnconfirmed, 0, null).IsConfirmedSuccess.ShouldBeFalse();
new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0, null).IsConfirmedSuccess.ShouldBeFalse();
}
[Fact]
public void Sample_preserves_optional_timestamps_and_owned_bytes()
{
var bytes = new byte[] { 1, 2 };
using var value = DataValue.FromBytes(bytes);
bytes[0] = 9;
value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2 });
using var sample = new DataSample(value.Retain(), 0x80000001, null, null,
new ServingIdentity("node", "incarnation", "primary", 1, 2), 3);
sample.SourceTimestampUtc.ShouldBeNull();
sample.ServerTimestampUtc.ShouldBeNull();
sample.StatusCode.ShouldBe(0x80000001u);
}
[Fact]
public void Retained_size_covers_payload_and_shape_without_returning_mutable_storage()
{
using var bytes = DataValue.FromBytes(new byte[10]);
using var text = DataValue.FromScalar(DataValueKind.String, "abcd");
using var array = DataValue.FromArray(DataValueKind.String, new object[] { "abc", "de" }, new[] { 2 });
bytes.EstimatedRetainedBytes.ShouldBe(298);
text.EstimatedRetainedBytes.ShouldBe(296);
array.EstimatedRetainedBytes.ShouldBe(498);
using var lease = array.Retain();
lease.EstimatedRetainedBytes.ShouldBe(array.EstimatedRetainedBytes);
lease.Dispose();
Should.Throw<ObjectDisposedException>(() => lease.EstimatedRetainedBytes);
}
[Fact]
public void Lease_deadline_is_anchored_to_request_start_and_bounded()
{
var lease = new MetadataLease(2, 3, TimeSpan.FromSeconds(15));
lease.Deadline(100, TimeSpan.FromSeconds(1), TimeProvider.System).ShouldBeLessThan(
100 + (long)(15 * TimeProvider.System.TimestampFrequency));
Should.Throw<ArgumentOutOfRangeException>(() => new MetadataLease(2, 3, TimeSpan.Zero).Validate());
}
[Fact]
public void Compact_handle_is_scoped_to_stream_and_item_revision()
{
var first = new DataItemHandle("stream", 1, 10, 1);
first.ShouldNotBe(first with { StreamEpoch = 2 });
first.ShouldNotBe(first with { ItemRevision = 2 });
Should.Throw<ArgumentOutOfRangeException>(() => (first with { Handle = 0 }).Validate());
}
[Fact]
public void Write_admission_keeps_original_credential_separate_from_principal()
{
var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"),
DataRealm.Raw, null, 0, "subject");
var expiry = DateTimeOffset.UtcNow.AddMinutes(1);
var ticket = new DataWriteAdmission("principal", view, 1, 2, "node-incarnation",
"driver-incarnation", "operation", 100, "key-a", expiry, "fingerprint");
ticket.Validate();
ticket.PrincipalId.ShouldBe("principal");
ticket.ApiKeyId.ShouldBe("key-a");
ticket.CredentialVersion.ShouldBe("fingerprint");
ticket.CredentialExpiresUtc.ShouldBe(expiry);
Should.Throw<ArgumentException>(() => (ticket with { ApiKeyId = "" }).Validate());
Should.Throw<ArgumentException>(() => (ticket with { CredentialVersion = "" }).Validate());
}
[Fact]
public void Empty_array_metadata_retains_its_element_type()
{
var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"),
DataRealm.Raw, null, 0, "subject");
var integerArray = new DataMetadata(view, "tag", "variable", DataValueKind.Array, 1,
new[] { 0 }, false, DataOperations.Read, 1, null, null, false, DataValueKind.Int32);
var stringArray = integerArray with { ArrayElementKind = DataValueKind.String };
integerArray.Validate();
stringArray.Validate();
integerArray.ShouldNotBe(stringArray);
Should.Throw<ArgumentException>(() => (integerArray with { ArrayElementKind = null }).Validate());
Should.Throw<ArgumentException>(() => (integerArray with { ArrayElementKind = DataValueKind.Array }).Validate());
Should.Throw<ArgumentException>(() => (integerArray with { ValueKind = DataValueKind.Int32 }).Validate());
}
[Fact]
public void Capabilities_bind_expected_cluster_and_validate_required_discovery_fields()
{
var limits = new DataLimits(10, 10, 1024, 10, 1, 1024,
TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilities(1, 0,
new ServingIdentity("node", "incarnation", "primary", 1, 1), DataReadiness.Ready,
DataOperations.Read, new HashSet<DataValueKind> { DataValueKind.Int32 }, limits, false, 0, "cluster-a");
capabilities.Validate();
capabilities.ClusterId.ShouldBe("cluster-a");
Should.Throw<ArgumentException>(() => (capabilities with { ClusterId = "" }).Validate());
Should.Throw<ArgumentOutOfRangeException>(() => (capabilities with { Readiness = DataReadiness.Unspecified }).Validate());
Should.Throw<ArgumentException>(() => (capabilities with { Serving = capabilities.Serving with { NodeId = "" } }).Validate());
Should.Throw<ArgumentOutOfRangeException>(() => (capabilities with { ProtocolMajor = 0 }).Validate());
Should.Throw<ArgumentOutOfRangeException>(() => (capabilities with { Limits = limits with { MaxBatchItems = 0 } }).Validate());
}
[Fact]
public void Wire_enum_numbers_are_stable()
{
Enum.GetNames<DataValueKind>().ShouldBe(new[] { "Unspecified", "Null", "Boolean", "Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16", "UInt32", "UInt64", "Float", "Double", "String", "Bytes", "Timestamp", "Guid", "Array" });
Enum.GetValues<DataValueKind>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 18));
Enum.GetNames<DataItemStatus>().ShouldBe(new[] { "Unspecified", "Good", "Denied", "NotFound", "Unsupported", "InvalidArgument", "Unavailable", "WaitingForInitialData", "Stale", "LimitExceeded", "InvalidContinuation", "TypeMismatch", "ResourceExhausted" });
Enum.GetValues<DataItemStatus>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 13));
Enum.GetNames<DataReadiness>().ShouldBe(new[] { "Unspecified", "Ready", "WaitingForInitialData", "Unavailable", "Invalidated" });
Enum.GetValues<DataReadiness>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 5));
Enum.GetNames<DataWriteState>().ShouldBe(new[] { "Unspecified", "RejectedBeforeDispatch", "DriverConfirmedSuccess", "DriverConfirmedFailure", "AcceptedUnconfirmed", "OutcomeUnknown" });
Enum.GetValues<DataWriteState>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 6));
Enum.GetNames<DataChangeTrigger>().ShouldBe(new[] { "Unspecified", "Status", "StatusValue", "StatusValueTimestamp" });
Enum.GetValues<DataChangeTrigger>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 4));
Enum.GetNames<DataStreamControlKind>().ShouldBe(new[] { "Unspecified", "SnapshotBegin", "SnapshotEnd", "CatalogInvalidated", "AuthorityInvalidated", "Heartbeat", "Reset", "Coalesced" });
Enum.GetValues<DataStreamControlKind>().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 8));
((int)DataRealm.Raw).ShouldBe(1);
((int)DataRealm.Uns).ShouldBe(2);
((int)DataTargetMode.Node).ShouldBe(1);
((int)DataTargetMode.Cluster).ShouldBe(2);
((int)DataConsistency.Primary).ShouldBe(1);
((int)DataConsistency.ReadyReplica).ShouldBe(2);
}
[Fact]
public void Settings_and_versioned_samples_reject_malformed_values()
{
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
DataChangeTrigger.StatusValue, 1);
settings.Validate();
Should.Throw<ArgumentOutOfRangeException>(() => (settings with { Deadband = double.NaN }).Validate());
Should.Throw<ArgumentOutOfRangeException>(() => (settings with { SamplingInterval = TimeSpan.FromSeconds(-1) }).Validate());
using var sample = new DataSample(DataValue.Null(), 0, null, null,
new ServingIdentity("node", "incarnation", "primary", 1, 1), 1);
sample.Validate();
Should.Throw<ArgumentOutOfRangeException>(() => (sample with { Version = 0 }).Validate());
Should.Throw<ArgumentOutOfRangeException>(() => (sample with { Serving = sample.Serving with { CatalogEpoch = 0 } }).Validate());
}
[Fact]
public void Limits_advertise_a_positive_per_value_element_budget()
{
var limits = new DataLimits(10, 10, 1024, 10, 1, 1024,
TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
limits.MaxValueElements.ShouldBe(100_000);
limits.Validate();
Should.Throw<ArgumentOutOfRangeException>(() => (limits with { MaxValueElements = 0 }).Validate());
}
[Fact]
public void Authenticated_context_binds_the_original_credential_and_authority()
{
var expiry = DateTimeOffset.UtcNow.AddMinutes(1);
var context = new DataAuthenticatedContext("principal", "key", "fingerprint", expiry, 7);
context.Validate();
context.CredentialVersion.ShouldBe("fingerprint");
Should.Throw<ArgumentException>(() => (context with { CredentialVersion = "" }).Validate());
Should.Throw<ArgumentOutOfRangeException>(() => (context with { AuthorityEpoch = 0 }).Validate());
typeof(IDataConnectionFactory).GetMethod(nameof(IDataConnectionFactory.Create))!.ReturnType.ShouldBe(typeof(IDataConnection));
}
[Fact]
public void Unmapped_view_rejects_a_mapping_revision()
{
var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"),
DataRealm.Raw, null, 1, "untrusted-subject");
Should.Throw<ArgumentException>(() => view.Validate());
}
}