Files
romanett 9b034f8291 Enable nullable reference types centrally; migrate all unset and annotations-only projects (#4700)
# Description

Nullable reference types are now enabled once, in `common.props`, and
every project in the repository builds warning-clean with them.

**Configuration**
- `<Nullable>enable</Nullable>` lives in `common.props`. All per-project
`<Nullable>` settings are removed: 178 project files (enable,
annotations, and the `disable` in the three Aot test projects).
- 419 per-file `#nullable enable`/`restore` directives and the 4
`#nullable disable` directives are removed.
- Kept on purpose:
- The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type
Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`,
`PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the
project setting in generated code, so the directive is required there.
- `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against
the 1.5.378 packages and does not import the repository props.
- `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now
describe the central setting.

**Migration** (the 43 unset and 13 annotations-only projects, roughly
10k diagnostics)
- **Production code: annotated at the declarations.** Covers
`tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the
LDS sample.
- Members, parameters and returns are nullable where null actually
flows.
- Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`,
`IsMethodTypeDesign`).
- `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take
`params object?[]`. `Template.AddReplacement` takes `string?` (rendering
already skips null replacements).
- `IRegisteredServerStore.RegisterAsync` returns
`Task<RegistrationEntry?>`: it returns null when a registration is
removed.
- Dereferences backed by an invariant (for example, the validated model)
use `!`, so runtime behaviour is unchanged.
- **Behavioural changes in production code** (small, deliberate):
- `NodeSetToModelDesign` throws `InvalidOperationException` when the
file is not a NodeSet. Before, it threw a NullReferenceException on the
next line.
- `ModelDesignValidator` starts its lookup tables empty instead of null.
A redundant `if (m_nodes == null) return;` guard is gone.
- **Test code: minimal annotations.**
  - `?` on values that can be null, `!` where the test asserts non-null.
  - `= null!` for fixture members assigned in SetUp.
- `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the
`IEncodeable` constraint.
- A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`)
folded into the adjacent `IsNull`/`Count` checks.

**Notes for reviewers**
- The diff is large (~1,500 files) but almost entirely mechanical: `?`,
`!` and directive removal. The non-annotation changes are listed above.
- Known follow-up, not done here:
`IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay
non-nullable even though the validator returns null before it loads a
dictionary. Making them nullable would ripple through every generator
call site.

## Related Issues

- Fixes #4439

## Checklist

- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [ ] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

The "no new warnings" box covers net10.0 and net48: full non-incremental
builds of `UA.slnx`, `tools/SourceGeneration.slnx`,
`tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0
warnings and 0 errors under the repository's warnings-as-errors
settings. net9.0 and net8.0 also had no nullable diagnostics, but they
were not rebuilt after the final fixes. Tests have not been run locally
yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:48:13 +02:00

779 lines
32 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
namespace Opc.Ua.Server.Tests.NodeManager
{
[TestFixture]
[Category("NodeManagerLifecycle")]
[Parallelizable(ParallelScope.All)]
public sealed class NodeManagerRoutingTableTests
{
private static readonly int[] AddNamespaceIndexes = [2, 2, 3];
private static readonly int[] ReplaceNamespaceIndexes = [3, 4];
private static readonly int[] InitialNamespaceIndexes = [2, 3];
private static readonly int[] ConcurrentNamespaceIndexes = [9];
[Test]
public void AddPublishesManagerAndNamespaceRoutesWithoutMutatingCapturedSnapshots()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
IAsyncNodeManager lifecycleManager = CreateManager();
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>>
namespaceRouteSnapshot = table.NamespaceManagers;
table.Add(lifecycleManager, AddNamespaceIndexes);
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> currentRoutes =
table.NamespaceManagers;
Assert.That(table, Has.Count.EqualTo(3));
Assert.That(table[0], Is.SameAs(firstPermanent));
Assert.That(table[1], Is.SameAs(secondPermanent));
Assert.That(table[2], Is.SameAs(lifecycleManager));
Assert.That(currentRoutes, Is.Not.SameAs(namespaceRouteSnapshot));
Assert.That(currentRoutes, Has.Count.EqualTo(2));
Assert.That(currentRoutes.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
AssertSingleManagerRoute(currentRoutes, 2, lifecycleManager);
AssertSingleManagerRoute(currentRoutes, 3, lifecycleManager);
AssertManagerSnapshot(
managerSnapshot,
firstPermanent,
secondPermanent);
Assert.That(namespaceRouteSnapshot, Is.Empty);
}
[Test]
public void ReplacePublishesReplacementRoutesWithoutMutatingCapturedSnapshots()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
IAsyncNodeManager original = CreateManager();
IAsyncNodeManager replacement = CreateManager();
table.Add(original, InitialNamespaceIndexes);
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>>
namespaceRouteSnapshot = table.NamespaceManagers;
IReadOnlyList<IAsyncNodeManager> namespaceTwoSnapshot =
namespaceRouteSnapshot[2];
IReadOnlyList<IAsyncNodeManager> namespaceThreeSnapshot =
namespaceRouteSnapshot[3];
table.Replace(original, replacement, ReplaceNamespaceIndexes);
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> currentRoutes =
table.NamespaceManagers;
Assert.That(table, Has.Count.EqualTo(3));
Assert.That(table[0], Is.SameAs(firstPermanent));
Assert.That(table[1], Is.SameAs(secondPermanent));
Assert.That(table[2], Is.SameAs(replacement));
Assert.That(table[2], Is.Not.SameAs(original));
Assert.That(currentRoutes, Is.Not.SameAs(namespaceRouteSnapshot));
Assert.That(currentRoutes, Has.Count.EqualTo(2));
Assert.That(currentRoutes.Keys, Is.EquivalentTo(ReplaceNamespaceIndexes));
Assert.That(currentRoutes.ContainsKey(2), Is.False);
AssertSingleManagerRoute(currentRoutes, 3, replacement);
AssertSingleManagerRoute(currentRoutes, 4, replacement);
Assert.That(currentRoutes[3][0], Is.Not.SameAs(original));
Assert.That(currentRoutes[4][0], Is.Not.SameAs(original));
AssertManagerSnapshot(
managerSnapshot,
firstPermanent,
secondPermanent,
original);
Assert.That(namespaceRouteSnapshot, Has.Count.EqualTo(2));
Assert.That(namespaceRouteSnapshot.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
Assert.That(namespaceRouteSnapshot[2], Is.SameAs(namespaceTwoSnapshot));
Assert.That(namespaceRouteSnapshot[3], Is.SameAs(namespaceThreeSnapshot));
AssertSingleManagerRoute(namespaceRouteSnapshot, 2, original);
AssertSingleManagerRoute(namespaceRouteSnapshot, 3, original);
}
[Test]
public void RestoreReplacementRecoversDroppedRoutePositions()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
IAsyncNodeManager original = CreateManager();
IAsyncNodeManager peer = CreateManager();
IAsyncNodeManager replacement = CreateManager();
table.Add(original, InitialNamespaceIndexes);
table.Add(peer, InitialNamespaceIndexes);
NodeManagerRoutingTable.NodeManagerRoutingPosition position =
table.Replace(
original,
replacement,
ReplaceNamespaceIndexes);
table.RestoreReplacement(
replacement,
original,
position,
visible: true);
Assert.That(table[2], Is.SameAs(original));
Assert.That(table[3], Is.SameAs(peer));
Assert.That(table.NamespaceManagers.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
Assert.That(table.NamespaceManagers[2][0], Is.SameAs(original));
Assert.That(table.NamespaceManagers[2][1], Is.SameAs(peer));
Assert.That(table.NamespaceManagers[3][0], Is.SameAs(original));
Assert.That(table.NamespaceManagers[3][1], Is.SameAs(peer));
}
[Test]
public void RemoveUnpublishesManagerWithoutMutatingCapturedSnapshots()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
IAsyncNodeManager lifecycleManager = CreateManager();
table.Add(lifecycleManager, InitialNamespaceIndexes);
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>>
namespaceRouteSnapshot = table.NamespaceManagers;
IReadOnlyList<IAsyncNodeManager> namespaceTwoSnapshot =
namespaceRouteSnapshot[2];
IReadOnlyList<IAsyncNodeManager> namespaceThreeSnapshot =
namespaceRouteSnapshot[3];
table.Remove(lifecycleManager);
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> currentRoutes =
table.NamespaceManagers;
Assert.That(table, Has.Count.EqualTo(2));
Assert.That(table[0], Is.SameAs(firstPermanent));
Assert.That(table[1], Is.SameAs(secondPermanent));
Assert.That(currentRoutes, Is.Not.SameAs(namespaceRouteSnapshot));
Assert.That(currentRoutes, Is.Empty);
AssertManagerSnapshot(
managerSnapshot,
firstPermanent,
secondPermanent,
lifecycleManager);
Assert.That(namespaceRouteSnapshot, Has.Count.EqualTo(2));
Assert.That(namespaceRouteSnapshot.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
Assert.That(namespaceRouteSnapshot[2], Is.SameAs(namespaceTwoSnapshot));
Assert.That(namespaceRouteSnapshot[3], Is.SameAs(namespaceThreeSnapshot));
AssertSingleManagerRoute(namespaceRouteSnapshot, 2, lifecycleManager);
AssertSingleManagerRoute(namespaceRouteSnapshot, 3, lifecycleManager);
}
[Test]
public void RestoreReturnsManagerToCapturedGlobalAndNamespacePositions()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
IAsyncNodeManager earlier = CreateManager();
IAsyncNodeManager first = CreateManager();
IAsyncNodeManager second = CreateManager();
table.Add(earlier, InitialNamespaceIndexes);
table.Add(first, InitialNamespaceIndexes);
table.Add(second, InitialNamespaceIndexes);
NodeManagerRoutingTable.NodeManagerRoutingPosition position =
table.RemoveAndCapturePosition(first);
table.Remove(earlier);
table.Restore(first, position);
Assert.That(table[2], Is.SameAs(first));
Assert.That(table[3], Is.SameAs(second));
Assert.That(table.NamespaceManagers[2][0], Is.SameAs(first));
Assert.That(table.NamespaceManagers[2][1], Is.SameAs(second));
Assert.That(table.NamespaceManagers[3][0], Is.SameAs(first));
Assert.That(table.NamespaceManagers[3][1], Is.SameAs(second));
}
[Test]
public void RoutingMutationsMatchAdaptersBySynchronousManagerIdentity()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
INodeManager syncManager = new Mock<INodeManager>().Object;
IAsyncNodeManager registeredAdapter =
CreateManagerWithSync(syncManager);
IAsyncNodeManager lookupAdapter =
CreateManagerWithSync(syncManager);
table.Add(registeredAdapter, [2]);
table.RegisterNamespace(3, lookupAdapter);
Assert.That(table.NamespaceManagers[3], Has.Count.EqualTo(1));
Assert.That(
table.NamespaceManagers[3][0],
Is.SameAs(registeredAdapter));
table.Remove(lookupAdapter);
Assert.That(table, Has.Count.EqualTo(2));
Assert.That(table.NamespaceManagers, Is.Empty);
}
/// <summary>
/// While one writer alternates replacing the single lifecycle-managed slot between
/// two manager instances (~200 times) and several readers loop concurrently, every
/// individually captured manager-list snapshot (via <see cref="NodeManagerRoutingTable.GetEnumerator"/>)
/// must remain structurally complete - three managers, the first two always the
/// same permanent instances, and the third always exactly one of the two lifecycle
/// generations, never anything else - and every individually captured
/// <see cref="NodeManagerRoutingTable.NamespaceManagers"/> snapshot must show exactly
/// one non-null route to the same namespace index, pointing at exactly one valid
/// lifecycle generation. The manager list and the namespace-route dictionary are
/// each read via a single, separate, atomic snapshot access; a legitimate concurrent
/// write can therefore be interleaved between the two reads, so the two are
/// deliberately never cross-correlated against each other.
/// </summary>
[Test]
public async Task ConcurrentReadersObserveOnlyCompleteRoutingSnapshotsAsync()
{
const int ReaderIterations = 100;
const int ReaderCount = 4;
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
IAsyncNodeManager generationA = CreateManager();
IAsyncNodeManager generationB = CreateManager();
table.Add(generationA, ConcurrentNamespaceIndexes);
var managerSnapshotFailures = new ConcurrentBag<string>();
var namespaceSnapshotFailures = new ConcurrentBag<string>();
using var startBarrier = new Barrier(ReaderCount + 1);
using var writerStarted = new ManualResetEventSlim();
using var readersReadyForConcurrentWrite = new CountdownEvent(ReaderCount);
using var concurrentWriteCompleted = new ManualResetEventSlim();
using var stopWriter = new CancellationTokenSource();
int writerIterations = 0;
var writerTask = Task.Run(() =>
{
IAsyncNodeManager current = generationA;
startBarrier.SignalAndWait();
ReplaceCurrent();
writerStarted.Set();
readersReadyForConcurrentWrite.Wait();
ReplaceCurrent();
concurrentWriteCompleted.Set();
while (!stopWriter.IsCancellationRequested)
{
ReplaceCurrent();
Thread.Yield();
}
void ReplaceCurrent()
{
IAsyncNodeManager next = ReferenceEquals(current, generationA)
? generationB
: generationA;
table.Replace(current, next, ConcurrentNamespaceIndexes);
current = next;
Interlocked.Increment(ref writerIterations);
}
});
Task[] readerTasks = [.. Enumerable.Range(0, ReaderCount).Select(_ => Task.Run(() =>
{
startBarrier.SignalAndWait();
writerStarted.Wait();
readersReadyForConcurrentWrite.Signal();
concurrentWriteCompleted.Wait();
for (int iteration = 0; iteration < ReaderIterations; iteration++)
{
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
var managers = new List<IAsyncNodeManager>();
while (managerSnapshot.MoveNext())
{
managers.Add(managerSnapshot.Current);
}
if (managers.Count != 3 ||
!ReferenceEquals(managers[0], firstPermanent) ||
!ReferenceEquals(managers[1], secondPermanent) ||
(!ReferenceEquals(managers[2], generationA) &&
!ReferenceEquals(managers[2], generationB)))
{
managerSnapshotFailures.Add(
$"iteration {iteration}: manager count {managers.Count}");
}
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> namespaceRoutes =
table.NamespaceManagers;
int namespaceIndex = ConcurrentNamespaceIndexes[0];
bool hasRoute = namespaceRoutes.TryGetValue(
namespaceIndex,
out IReadOnlyList<IAsyncNodeManager>? route);
if (!hasRoute ||
route!.Count != 1 ||
(!ReferenceEquals(route[0], generationA) &&
!ReferenceEquals(route[0], generationB)))
{
namespaceSnapshotFailures.Add(
$"iteration {iteration}: hasRoute {hasRoute}, " +
$"count {(hasRoute ? route!.Count : -1)}");
}
Thread.Yield();
}
}))];
try
{
await Task.WhenAll(readerTasks).ConfigureAwait(false);
}
finally
{
stopWriter.Cancel();
await writerTask.ConfigureAwait(false);
}
Assert.That(writerIterations, Is.GreaterThan(2));
Assert.That(managerSnapshotFailures, Is.Empty);
Assert.That(namespaceSnapshotFailures, Is.Empty);
}
[Test]
public void AddInitialThrowsOnNullNodeManager()
{
var table = new NodeManagerRoutingTable();
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
() => table.AddInitial(null!))!;
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
}
[Test]
public void InitializePublishesNamespaceRoutesFromDictionary()
{
var table = new NodeManagerRoutingTable();
IAsyncNodeManager manager = CreateManager();
ArgumentNullException nullEx = Assert.Throws<ArgumentNullException>(
() => table.Initialize(null!))!;
Assert.That(nullEx.ParamName, Is.EqualTo("namespaceManagers"));
table.Initialize(
new Dictionary<int, List<IAsyncNodeManager>> { [5] = [manager] });
AssertSingleManagerRoute(table.NamespaceManagers, 5, manager);
}
[Test]
public void AddThrowsOnNullNodeManager()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
() => table.Add(null!, AddNamespaceIndexes))!;
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
}
[Test]
public void AddThrowsOnNullNamespaceIndexes()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
() => table.Add(CreateManager(), null!))!;
Assert.That(ex.ParamName, Is.EqualTo("namespaceIndexes"));
}
[Test]
public void AddThrowsWhenNodeManagerAlreadyRegistered()
{
NodeManagerRoutingTable table = CreateTable(out IAsyncNodeManager firstPermanent, out _);
Assert.Throws<InvalidOperationException>(
() => table.Add(firstPermanent, AddNamespaceIndexes));
}
[Test]
public void AddWithVisibleFalseHidesManagerFromEnumerationButNotFromIndexer()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
IAsyncNodeManager hiddenManager = CreateManager();
table.Add(hiddenManager, AddNamespaceIndexes, visible: false);
Assert.That(table, Has.Count.EqualTo(3));
Assert.That(table[2], Is.SameAs(hiddenManager));
Assert.That(table.IsVisible(hiddenManager), Is.False);
using IEnumerator<IAsyncNodeManager> visibleSnapshot = table.GetEnumerator();
AssertManagerSnapshot(visibleSnapshot, firstPermanent, secondPermanent);
}
[Test]
public void ReplaceThrowsOnNullArguments()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
IAsyncNodeManager original = CreateManager();
table.Add(original, InitialNamespaceIndexes);
Assert.That(
Assert.Throws<ArgumentNullException>(
() => table.Replace(null!, CreateManager(), ReplaceNamespaceIndexes))!.ParamName,
Is.EqualTo("current"));
Assert.That(
Assert.Throws<ArgumentNullException>(
() => table.Replace(original, null!, ReplaceNamespaceIndexes))!.ParamName,
Is.EqualTo("replacement"));
Assert.That(
Assert.Throws<ArgumentNullException>(
() => table.Replace(original, CreateManager(), null!))!.ParamName,
Is.EqualTo("replacementNamespaceIndexes"));
}
[Test]
public void ReplaceThrowsWhenCurrentIsNotLifecycleManaged()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out _);
Assert.Throws<InvalidOperationException>(
() => table.Replace(firstPermanent, CreateManager(), ReplaceNamespaceIndexes));
}
[Test]
public void ReplaceThrowsWhenReplacementAlreadyRegistered()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
IAsyncNodeManager original = CreateManager();
IAsyncNodeManager other = CreateManager();
table.Add(original, InitialNamespaceIndexes);
table.Add(other, ReplaceNamespaceIndexes);
Assert.Throws<InvalidOperationException>(
() => table.Replace(original, other, ReplaceNamespaceIndexes));
}
[Test]
public void RemoveThrowsOnNullNodeManager()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
() => table.Remove(null!))!;
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
}
[Test]
public void RemoveThrowsWhenNodeManagerIsNotLifecycleManaged()
{
NodeManagerRoutingTable table = CreateTable(out IAsyncNodeManager firstPermanent, out _);
Assert.Throws<InvalidOperationException>(() => table.Remove(firstPermanent));
}
[Test]
public void RegisterNamespaceIsIdempotentForTheSameManager()
{
var table = new NodeManagerRoutingTable();
IAsyncNodeManager manager = CreateManager();
table.RegisterNamespace(7, manager);
table.RegisterNamespace(7, manager);
AssertSingleManagerRoute(table.NamespaceManagers, 7, manager);
}
[Test]
public void RegisterNamespaceAppendsToExistingRouteForDifferentManager()
{
var table = new NodeManagerRoutingTable();
IAsyncNodeManager first = CreateManager();
IAsyncNodeManager second = CreateManager();
table.RegisterNamespace(7, first);
table.RegisterNamespace(7, second);
Assert.That(table.NamespaceManagers[7], Has.Count.EqualTo(2));
Assert.That(table.NamespaceManagers[7], Does.Contain(first));
Assert.That(table.NamespaceManagers[7], Does.Contain(second));
}
[Test]
public void RegisterNamespaceWithVisibleFalseHidesManager()
{
var table = new NodeManagerRoutingTable();
IAsyncNodeManager manager = CreateManager();
table.AddInitial(manager);
table.RegisterNamespace(7, manager, visible: false);
Assert.That(table.IsVisible(manager), Is.False);
}
[Test]
public void UnregisterNamespaceReturnsFalseWhenNamespaceNotFound()
{
var table = new NodeManagerRoutingTable();
Assert.That(table.UnregisterNamespace(1, CreateManager(), null), Is.False);
}
[Test]
public void UnregisterNamespaceReturnsFalseWhenManagerNotInRoute()
{
var table = new NodeManagerRoutingTable();
table.RegisterNamespace(7, CreateManager());
Assert.That(table.UnregisterNamespace(7, CreateManager(), null), Is.False);
}
[Test]
public void UnregisterNamespaceRemovesRouteEntryWhenLastManagerRemoved()
{
var table = new NodeManagerRoutingTable();
IAsyncNodeManager manager = CreateManager();
table.RegisterNamespace(7, manager);
bool removed = table.UnregisterNamespace(7, manager, null);
Assert.That(removed, Is.True);
Assert.That(table.NamespaceManagers.ContainsKey(7), Is.False);
}
[Test]
public void UnregisterNamespaceKeepsRouteWhenOtherManagersRemain()
{
var table = new NodeManagerRoutingTable();
IAsyncNodeManager first = CreateManager();
IAsyncNodeManager second = CreateManager();
table.RegisterNamespace(7, first);
table.RegisterNamespace(7, second);
bool removed = table.UnregisterNamespace(7, first, null);
Assert.That(removed, Is.True);
AssertSingleManagerRoute(table.NamespaceManagers, 7, second);
}
[Test]
public void UnregisterNamespaceMatchesBySyncNodeManagerWhenAsyncNodeManagerIsNull()
{
var table = new NodeManagerRoutingTable();
INodeManager syncManager = new Mock<INodeManager>().Object;
IAsyncNodeManager manager = CreateManagerWithSync(syncManager);
table.RegisterNamespace(7, manager);
bool removed = table.UnregisterNamespace(7, null, syncManager);
Assert.That(removed, Is.True);
Assert.That(table.NamespaceManagers.ContainsKey(7), Is.False);
}
[Test]
public void RemoveNamespaceManagerThrowsOnNullNodeManager()
{
var table = new NodeManagerRoutingTable();
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
() => table.RemoveNamespaceManager(null!))!;
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
}
[Test]
public void RemoveNamespaceManagerRemovesAcrossAllNamespacesAndMatchesBySyncNodeManager()
{
var table = new NodeManagerRoutingTable();
INodeManager syncManager = new Mock<INodeManager>().Object;
IAsyncNodeManager registeredManager = CreateManagerWithSync(syncManager);
IAsyncNodeManager lookupManager = CreateManagerWithSync(syncManager);
IAsyncNodeManager unrelated = CreateManager();
table.RegisterNamespace(2, registeredManager);
table.RegisterNamespace(3, registeredManager);
table.RegisterNamespace(3, unrelated);
table.RemoveNamespaceManager(lookupManager);
Assert.That(table.NamespaceManagers.ContainsKey(2), Is.False);
AssertSingleManagerRoute(table.NamespaceManagers, 3, unrelated);
}
[Test]
public void IsVisibleReturnsFalseForUnregisteredManager()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
Assert.That(table.IsVisible(CreateManager()), Is.False);
}
[Test]
public void IsVisibleReturnsTrueForRegisteredVisibleManager()
{
NodeManagerRoutingTable table = CreateTable(out IAsyncNodeManager firstPermanent, out _);
Assert.That(table.IsVisible(firstPermanent), Is.True);
}
[Test]
public void SetVisibleThrowsOnNullNodeManager()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
() => table.SetVisible(null!, false))!;
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
}
[Test]
public void SetVisibleThrowsWhenManagerNotRegistered()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
Assert.Throws<InvalidOperationException>(
() => table.SetVisible(CreateManager(), false));
}
[Test]
public void SetVisibleTogglesVisibilityAffectingEnumerationAndIsVisible()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
table.SetVisible(firstPermanent, false);
Assert.That(table.IsVisible(firstPermanent), Is.False);
using (IEnumerator<IAsyncNodeManager> hiddenSnapshot = table.GetEnumerator())
{
AssertManagerSnapshot(hiddenSnapshot, secondPermanent);
}
table.SetVisible(firstPermanent, true);
Assert.That(table.IsVisible(firstPermanent), Is.True);
using IEnumerator<IAsyncNodeManager> restoredSnapshot = table.GetEnumerator();
AssertManagerSnapshot(restoredSnapshot, firstPermanent, secondPermanent);
}
[Test]
public void ClearResetsAllState()
{
NodeManagerRoutingTable table = CreateTable(out _, out _);
table.Add(CreateManager(), InitialNamespaceIndexes);
table.Clear();
Assert.That(table, Has.Count.EqualTo(0));
Assert.That(table.NamespaceManagers, Is.Empty);
}
[Test]
public void IndexerReturnsManagerAtPosition()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
Assert.That(table[0], Is.SameAs(firstPermanent));
Assert.That(table[1], Is.SameAs(secondPermanent));
}
[Test]
public void ExplicitEnumerableGetEnumeratorReturnsSameManagersAsGenericEnumerator()
{
NodeManagerRoutingTable table = CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent);
var managers = new List<IAsyncNodeManager>();
System.Collections.IEnumerable untyped = table;
System.Collections.IEnumerator enumerator = untyped.GetEnumerator();
while (enumerator.MoveNext())
{
managers.Add((IAsyncNodeManager)enumerator.Current!);
}
Assert.That(managers, Is.EqualTo([firstPermanent, secondPermanent]));
}
private static NodeManagerRoutingTable CreateTable(
out IAsyncNodeManager firstPermanent,
out IAsyncNodeManager secondPermanent)
{
firstPermanent = CreateManager();
secondPermanent = CreateManager();
var table = new NodeManagerRoutingTable();
table.AddInitial(firstPermanent);
table.AddInitial(secondPermanent);
return table;
}
private static IAsyncNodeManager CreateManager()
{
return new Mock<IAsyncNodeManager>().Object;
}
private static IAsyncNodeManager CreateManagerWithSync(INodeManager syncNodeManager)
{
var manager = new Mock<IAsyncNodeManager>();
manager.Setup(m => m.SyncNodeManager).Returns(syncNodeManager);
return manager.Object;
}
private static void AssertManagerSnapshot(
IEnumerator<IAsyncNodeManager> snapshot,
params IAsyncNodeManager[] expected)
{
foreach (IAsyncNodeManager expectedManager in expected)
{
Assert.That(snapshot.MoveNext(), Is.True);
Assert.That(snapshot.Current, Is.SameAs(expectedManager));
}
Assert.That(snapshot.MoveNext(), Is.False);
}
private static void AssertSingleManagerRoute(
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> routes,
int namespaceIndex,
IAsyncNodeManager expected)
{
Assert.That(routes.ContainsKey(namespaceIndex), Is.True);
Assert.That(routes[namespaceIndex], Has.Count.EqualTo(1));
Assert.That(routes[namespaceIndex][0], Is.SameAs(expected));
}
}
}