Files
Marc Schier 5795e50b58 Source-generated, NativeAOT-clean fluent server API with event-source publish (#3765)
* Add async read/write hooks to BaseVariableState and AsyncCustomNodeManager

Introduces an end-to-end async path for variable Value-attribute reads
and writes that does not require holding lock(this) while the user
callback executes:

* New AttributeReadResult, AttributeSimpleReadResult and AttributeWriteResult
  readonly record structs in NodeState carry the typed result of an async
  Value-attribute hook (no ref/out params across await).
* Four new async delegates (NodeValueEventHandlerAsync,
  NodeValueSimpleEventHandlerAsync, NodeValueWriteEventHandlerAsync,
  NodeValueSimpleWriteEventHandlerAsync) sit alongside the existing sync
  hooks.
* NodeState gains virtual ReadAttributeAsync / WriteAttributeAsync methods.
  The default implementation wraps the synchronous call in lock(this) so
  callers that have not opted into async hooks see bit-identical behaviour.
* BaseVariableState exposes OnReadValueAsync, OnSimpleReadValueAsync,
  OnWriteValueAsync and OnSimpleWriteValueAsync slots and overrides the new
  virtuals to dispatch to them WITHOUT holding the lock during the await.
  On simple-read the framework still applies index range, data encoding and
  copy policy; on simple-write the cached value/status/timestamp are
  updated under lock after the hook completes.
* AsyncCustomNodeManager.ReadAsync and WriteAsync now await the new
  ReadAttributeAsync / WriteAttributeAsync entry points instead of taking
  lock(source) around the synchronous call. Existing per-source locking
  semantics are preserved by the default async wrappers.
* The fluent INodeBuilder surface gains four new async OnRead/OnWrite
  overloads that wire to the new BaseVariableState slots, with the same
  ThrowIfSlotOccupied + null-check pattern as the sync overloads.

* Add typed IVariableBuilder<T> fluent surface

Adds typed sub-interfaces and impls so the existing fluent surface

can expose simple Func<T> / Action<T> / Func<CancellationToken,

ValueTask<T>> overloads for variables — without losing the lower-level

Variant-based overloads on INodeBuilder.

* IVariableBuilder<TValue> + VariableBuilder<TValue> derive from

  INodeBuilder<BaseVariableState> / NodeBuilder<BaseVariableState>

  (NodeBuilder<TState> unsealed).

* Marshalling uses Variant.AsBoxedObject(BoxingBehavior.Legacy) for

  reads and Variant(object) for writes; the AOT-unsafe write path is

  scoped-suppressed with a TODO pointing at the planned per-type

  generated walker.

* INodeManagerBuilder gains Variable<T>(string),

  Variable<T>(NodeId), VariableFromTypeId<T>(NodeId),

  VariableFromTypeId<T>(NodeId, QualifiedName).

Server library builds clean across all 6 TFMs.

* Add relative-child traversal API on INodeBuilder

Adds INodeBuilder.Child(QualifiedName), Child<TState>(QualifiedName)

and Variable<TValue>(QualifiedName) so source-generated typed

wrappers can walk one segment at a time without re-resolving from

the manager root. Resolution uses NodeState.FindChild and reuses

NodeManagerBuilder.ToVariableBuilder to keep the typed-variable

marshalling story consistent.

Adds 7 NUnit cases (Fluent category) covering the happy path,

type-mismatch, null/missing browse-name, and non-variable

rejection. All 66 fluent tests pass.

* Mix old + new fluent APIs in MinimalBoilerServer demo

BoilerNodeManager.Configure now exercises five wiring styles:

  (1) browse-path with the legacy ref-Variant callback

  (2) absolute NodeId with the legacy ref-Variant callback

  (3) typed Variable<double>(NodeId) + simple Func<double> sync getter

  (4) typed Variable<double>(NodeId) + Func<CancellationToken, ValueTask<double>>

      async getter — exercises the BaseVariableState.OnReadValueAsync

      slot end-to-end through AsyncCustomNodeManager.ReadAsync

  (5) NodeFromTypeId with OnNodeAdded lifecycle hook

All five styles compose against the same INodeManagerBuilder, with

the typed and async callbacks pulling in the new IVariableBuilder<T>

surface (committed at e557ecdd9) and the BaseVariableState async

path (committed at 2e2efb4ad).

* Add async-hook tests for BaseVariableState

15 NUnit cases covering the new On{Read,Write}ValueAsync and On
Simple{Read,Write}ValueAsync slots plus the
ReadAttributeAsync/WriteAttributeAsync overrides on
BaseVariableState:

* full async slot routes Value reads/writes
* lock(this) is released around the awaited handler
* simple async slot reapplies cached StatusCode and respects index
  ranges (BadIndexRangeInvalid for non-null ranges)
* exceptions and OperationCanceledException from the hook are
  caught and surfaced as BadUnexpectedError, mirroring the sync flow
* CancellationToken propagates to the hook
* cache (m_value, m_statusCode, m_timestamp) is updated on success
  and skipped on Bad return
* fallback to base sync ReadAttribute/WriteAttribute when no async
  slot is set (preserves today's lock(this) semantics)
* non-Value attributes never invoke the async hook
* CurrentRead/CurrentWrite access checks short-circuit before the
  hook runs

All 596 State tests pass on net10.0.

* Add round-trip tests for typed IVariableBuilder<T>

Covers the typed Func<T>/Action<T>/Func<...,ValueTask<T>> overloads
on IVariableBuilder<TValue>: each registers the appropriate hook
slot on the underlying BaseDataVariableState, and driving the
variable through ReadAttribute/WriteAttribute (sync) and
ReadAttributeAsync/WriteAttributeAsync (async) reproduces the
typed values the user supplied.

* Add typed model-traversal source generator

Adds FluentBuilderGenerator that walks the design's predefined-instance tree and emits a typed sibling for every NodeManagerBuilder. Each generated wrapper exposes IntelliSense-friendly accessors for child instances, variables (IVariableBuilder<T>) and methods (sync/async OnCall) so wiring sites become builder.Boilers.Boiler__1.LCX001.Measurement.OnRead(...) instead of a stringly typed browse path. The NodeManager template now also emits a Configure(I{Manager}NodeManagerBuilder) partial alongside the existing Configure(INodeManagerBuilder); both partials run, both are optional, and the typed surface is fully AOT-safe (no dynamic, no MakeGenericType, no reflection).

* Add tests for the typed model-traversal source generator

Adds 9 snapshot tests in Tests/Opc.Ua.SourceGeneration.Core.Tests covering the FluentBuilderGenerator's opt-in flag, typed-manager-interface and proxy emission, internal-sealed visibility, lazy child resolution via Context.NamespaceUris.GetIndexOrAppend, IVariableBuilder<TValue> accessors, sync+async OnCall overloads on method wrappers, and the dual Configure(INodeManagerBuilder)/Configure(I{Manager}NodeManagerBuilder) partial wiring in the NodeManager template. Adds 2 end-to-end AOT tests in Tests/Opc.Ua.Aot.Tests that exercise typed-traversal sync read on LCX001/Measurement and typed-traversal async OnCall on Simulation/Halt through the AOT-compiled MinimalBoilerServer fixture.

* Document the typed model-traversal Configure(I{Manager}NodeManagerBuilder) partial
2026-05-15 07:52:49 +02:00

399 lines
20 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2025 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.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using Opc.Ua.Tests;
namespace Opc.Ua.SourceGeneration.Generator.Tests
{
/// <summary>
/// Snapshot tests for the <see cref="FluentBuilderGenerator"/>: verify
/// the opt-in flag, the type-and-instance wrapper shape, the typed
/// IVariableBuilder accessors, and the typed sync/async OnCall
/// overloads on method wrappers.
/// </summary>
[TestFixture]
[Category("Generator")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[Parallelizable(ParallelScope.All)]
public class FluentBuilderGeneratorTests
{
[Test]
public void Emit_WithoutOptIn_ProducesNoFluentBuildersFile()
{
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: false);
Assert.That(files.Keys, Has.None.EndsWith(".FluentBuilders.g.cs"));
}
[Test]
public void Emit_WithOptIn_ProducesFluentBuildersFile()
{
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: true);
Assert.That(files.Keys, Has.Some.EndsWith(".FluentBuilders.g.cs"),
"Generator should emit a FluentBuilders file when GenerateNodeManager=true");
}
[Test]
public void EmittedFluentBuilders_HasTypedManagerInterfaceAndProxy()
{
string fb = GetFluentBuilders();
Assert.That(fb, Does.Match(
@"internal\s+interface\s+I\w+NodeManagerBuilder\s*:\s*global::Opc\.Ua\.Server\.Fluent\.INodeManagerBuilder"),
"A typed IBuilder interface extending INodeManagerBuilder must be emitted");
Assert.That(fb, Does.Match(
@"internal\s+sealed\s+class\s+\w+NodeManagerTypedBuilder\s*:\s*I\w+NodeManagerBuilder"),
"A typed proxy implementing the IBuilder must be emitted");
Assert.That(fb, Does.Contain("private readonly global::Opc.Ua.Server.Fluent.INodeManagerBuilder __inner"),
"The proxy must wrap an INodeManagerBuilder");
}
[Test]
public void EmittedFluentBuilders_AreAutoGenerated_AndUseGlobalQualifiedTypes()
{
string fb = GetFluentBuilders();
Assert.That(fb, Does.StartWith("// <auto-generated />"),
"FluentBuilders file must start with the auto-generated marker");
Assert.That(fb, Does.Contain("[global::System.CodeDom.Compiler.GeneratedCodeAttribute("),
"FluentBuilders file must carry the GeneratedCode attribute");
Assert.That(fb, Does.Contain("#pragma warning disable"),
"FluentBuilders file must suppress warnings to survive strict consumer projects");
}
[Test]
public void EmittedFluentBuilders_WrappersAreInternalSealed()
{
string fb = GetFluentBuilders();
// Per design decision #8 — wrappers are internal sealed because
// Configure is a private partial. Public exposure would add a
// surface that can never be called outside the assembly.
Assert.That(fb, Does.Match(@"internal\s+sealed\s+class\s+\w+Builder\b"),
"Wrapper classes should be 'internal sealed'");
Assert.That(fb, Does.Not.Match(@"public\s+(sealed\s+)?class\s+\w+Builder\b"),
"Wrapper classes must not be public");
}
[Test]
public void EmittedFluentBuilders_VariableAccessorsReturnTypedIVariableBuilder()
{
string fb = GetFluentBuilders();
// TestModel's RestrictedObjectType has a Mandatory variable child
// 'Red' of type RestrictedVariableType (Int32). The wrapper for
// the predefined TestObject instance must surface that variable
// through a typed IVariableBuilder<int> accessor.
Assert.That(fb, Does.Match(
@"public\s+global::Opc\.Ua\.Server\.Fluent\.IVariableBuilder<\w+>\s+\w+\s*\{"),
"Variable children should expose IVariableBuilder<TValue> accessors");
// Each accessor lazily resolves the namespace index to support
// cross-namespace browse names (NamespaceUris.GetIndexOrAppend).
Assert.That(fb, Does.Contain("Context.NamespaceUris.GetIndexOrAppend("),
"Variable accessors should resolve the namespace via GetIndexOrAppend");
Assert.That(fb, Does.Match(
@"return\s+__node\.Variable<\w+>\(new global::Opc\.Ua\.QualifiedName\("),
"Variable accessors should fall back to INodeBuilder.Variable<T>()");
}
[Test]
public void EmittedFluentBuilders_MethodWrappersExposeSyncAndAsyncOnCall()
{
string fb = GetFluentBuilders();
// Every method wrapper must offer BOTH sync and async OnCall
// overloads so user code-behind can choose the natural shape.
Assert.That(fb, Does.Match(
@"public\s+\w+MethodBuilder\s+OnCall\s*\(\s*global::System\.Action\s+handler\s*\)"),
"Method wrappers should expose a sync OnCall(Action) overload");
Assert.That(fb, Does.Match(
@"public\s+\w+MethodBuilder\s+OnCall\s*\(\s*global::System\.Func<global::System\.Threading\.CancellationToken,\s*global::System\.Threading\.Tasks\.ValueTask>\s+handler\s*\)"),
"Method wrappers should expose an async OnCall(Func<CT,ValueTask>) overload");
}
[Test]
public void EmittedFluentBuilders_InstanceAccessorsAreLazyAndAllocateChildBuilder()
{
string fb = GetFluentBuilders();
// Child accessors should never cache — each get materializes a
// fresh wrapper around an INodeBuilder<TChildState>. Caching
// would be unsafe because INodeBuilder identity is per-resolution.
Assert.That(fb, Does.Not.Match(@"private\s+\w+Builder\s+__child"),
"Child accessors must not cache the wrapper");
Assert.That(fb, Does.Match(
@"return\s+new\s+\w+Builder\s*\(\s*__node\.Child<\w+"),
"Object child accessors should resolve via INodeBuilder.Child<T>()");
}
[Test]
public void EmittedFluentBuilders_TopLevelInstanceWrapperLivesAtNamespaceScope()
{
string fb = GetFluentBuilders();
// Top-level wrappers must sit directly under the namespace
// body — i.e. at column 4 (one level into the namespace block
// emitted by FluentBuilderTemplates.File). Use TestObject as
// an exemplar — TestModel.xml declares it as a top-level
// instance.
Assert.That(fb, Does.Match(@"(?m)^ internal sealed class TestObjectBuilder\b"),
"Top-level wrappers must be declared at namespace scope (column 4)");
}
[Test]
public void EmittedFluentBuilders_MethodWrapperIsNestedInsideOwningObject()
{
string fb = GetFluentBuilders();
// TestObject's RestrictedObjectType has a Mandatory Method
// child 'Blue'. Its wrapper class must be nested one level
// inside TestObjectBuilder — i.e. declared at column 8.
Assert.That(fb, Does.Match(
@"(?m)^ internal sealed class BlueMethodBuilder\b"),
"Method wrappers must be nested inside the owning object's wrapper (column 8)");
}
[Test]
public void EmittedFluentBuilders_ChildAccessorReturnsSimpleLeafName()
{
string fb = GetFluentBuilders();
// Child accessors should return the simple leaf name only
// (e.g. 'BlueMethodBuilder') because the wrapper is nested
// inside the parent, not the old flat
// 'TestObject_BlueMethodBuilder' identifier.
Assert.That(fb, Does.Not.Match(@"public\s+TestObject_\w+Builder\s+\w+"),
"Child accessors must reference the simple leaf-name wrapper, not a flat dotted identifier");
Assert.That(fb, Does.Match(@"public\s+BlueMethodBuilder\s+Blue\b"),
"Child accessor for 'Blue' should return the simple-leaf-name 'BlueMethodBuilder'");
}
[Test]
public void MethodWithIntInputAndOutputEmitsTypedSyncOverload()
{
string fb = GetFluentBuilders();
// TestModel's MathInstance has a Mandatory method 'Compute'
// declared inline with InputArguments(x: Int32) and
// OutputArguments(result: Int32). The generator must surface
// a typed sync OnCall overload that maps Variant<-> int both
// ways without requiring the user to touch ArrayOf<Variant>.
Assert.That(fb, Does.Match(
@"public\s+ComputeMethodBuilder\s+OnCall\s*\(\s*global::System\.Func<int,\s*int>\s+handler\s*\)"),
"Compute(Int32 -> Int32) should expose a sync OnCall(Func<int,int>) overload");
}
[Test]
public void MethodWithIntInputAndOutputEmitsTypedAsyncOverload()
{
string fb = GetFluentBuilders();
// The async overload threads CancellationToken between the
// unpacked inputs and the ValueTask<TResult> return type.
Assert.That(fb, Does.Match(
@"public\s+ComputeMethodBuilder\s+OnCall\s*\(\s*global::System\.Func<int,\s*global::System\.Threading\.CancellationToken,\s*global::System\.Threading\.Tasks\.ValueTask<int>>\s+handler\s*\)"),
"Compute(Int32 -> Int32) should expose an async OnCall(Func<int,CT,ValueTask<int>>) overload");
}
[Test]
public void MethodInputUnpackUsesVariantTryGetValue()
{
string fb = GetFluentBuilders();
// Inputs flow through Variant.TryGetValue<T>(out T) so the
// generated lambda short-circuits with BadInvalidArgument when
// the caller sends the wrong wire type.
Assert.That(fb, Does.Match(
@"if\s*\(!__inputs\[0\]\.TryGetValue\(out\s+int\s+__a0\)\)"),
"Input unpack should use Variant.TryGetValue<T>(out T) for primitive inputs");
Assert.That(fb, Does.Contain(
"return new global::Opc.Ua.ServiceResult(global::Opc.Ua.StatusCodes.BadInvalidArgument);"),
"Failed input unpack should return BadInvalidArgument");
Assert.That(fb, Does.Contain(
"return new global::Opc.Ua.ServiceResult(global::Opc.Ua.StatusCodes.BadArgumentsMissing);"),
"Missing input arg count should return BadArgumentsMissing");
}
[Test]
public void MethodOutputBoxUsesVariantFrom()
{
string fb = GetFluentBuilders();
// Outputs are boxed back through Variant.From<T>(value) and
// assigned by index into the __outputs list which the base
// MethodState dispatcher pre-populates with default values
// (one slot per declared output argument). Single-output
// methods bind the user handler's return value to '__r'.
Assert.That(fb, Does.Contain(
"__outputs[0] = global::Opc.Ua.Variant.From(__r);"),
"Single-output methods should box the handler result via __outputs[0] = Variant.From(__r)");
}
[Test]
public void MethodWithMultipleInputArgsEmitsCorrectArity()
{
string fb = GetFluentBuilders();
// TestModel's MathInstance.Add(a: Int32, b: Int32 -> sum: Int32)
// must produce a sync OnCall overload whose handler arity
// matches the input count (Func<int,int,int>) and an async
// overload that appends CancellationToken + ValueTask<int>.
Assert.That(fb, Does.Match(
@"public\s+AddMethodBuilder\s+OnCall\s*\(\s*global::System\.Func<int,\s*int,\s*int>\s+handler\s*\)"),
"Add(Int32,Int32 -> Int32) should expose a sync OnCall(Func<int,int,int>) overload");
Assert.That(fb, Does.Match(
@"public\s+AddMethodBuilder\s+OnCall\s*\(\s*global::System\.Func<int,\s*int,\s*global::System\.Threading\.CancellationToken,\s*global::System\.Threading\.Tasks\.ValueTask<int>>\s+handler\s*\)"),
"Add(Int32,Int32 -> Int32) should expose an async OnCall(Func<int,int,CT,ValueTask<int>>) overload");
// Unpack arity: index 0 and index 1 must both be present.
Assert.That(fb, Does.Match(
@"if\s*\(!__inputs\[1\]\.TryGetValue\(out\s+int\s+__a1\)\)"),
"Multi-input methods should unpack each Variant by index (e.g. __inputs[1] -> __a1)");
}
[Test]
public void EmittedNodeManager_InvokesBothPlainAndTypedConfigurePartials()
{
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: true);
string mgr = files.Single(kv => kv.Key.EndsWith(".NodeManager.g.cs", StringComparison.Ordinal)).Value;
// Both partials must be declared so users can implement either.
Assert.That(mgr, Does.Contain("partial void Configure(global::Opc.Ua.Server.Fluent.INodeManagerBuilder builder);"),
"Plain Configure(INodeManagerBuilder) partial declaration must be emitted");
Assert.That(mgr, Does.Match(@"partial\s+void\s+Configure\s*\(\s*I\w+NodeManagerBuilder\s+builder\s*\);"),
"Typed Configure(I{Manager}NodeManagerBuilder) partial declaration must be emitted");
// Both must also be invoked so a user that only implements one
// gets their wiring run; the runtime treats unimplemented
// partials as no-ops.
Assert.That(mgr, Does.Contain("Configure(__m_builder);"),
"Plain Configure call must be present in CreateAddressSpaceAsync");
Assert.That(mgr, Does.Match(@"Configure\(\s*new\s+\w+NodeManagerTypedBuilder\(__m_builder\)\s*\)"),
"Typed Configure call must be present in CreateAddressSpaceAsync");
}
[Test]
public void EmittedFluentBuilders_PublishOverloadEmittedOnSupportsEventsWrapper()
{
string fb = GetFluentBuilders();
// TestModel declares NotifierObject with SupportsEvents="true"
// (the design-XML form of EventNotifier=SubscribeToEvents). Its
// wrapper must expose typed Publish<TEvent> overloads bound to
// the wrapper's underlying state type and constrained to
// BaseEventState.
Assert.That(fb, Does.Match(
@"internal\s+sealed\s+class\s+NotifierObjectBuilder\b"),
"NotifierObject must produce a wrapper class");
Assert.That(fb, Does.Match(
@"public\s+global::Opc\.Ua\.Server\.Fluent\.INodeBuilder<global::Opc\.Ua\.BaseObjectState>\s+Publish<TEvent>\(\s*global::System\.Collections\.Generic\.IAsyncEnumerable<TEvent>\s+source"),
"NotifierObjectBuilder must expose Publish<TEvent>(IAsyncEnumerable<TEvent>, EventPublishOptions)");
Assert.That(fb, Does.Match(
@"public\s+global::Opc\.Ua\.Server\.Fluent\.INodeBuilder<global::Opc\.Ua\.BaseObjectState>\s+Publish<TEvent>\(\s*global::System\.Func<global::Opc\.Ua\.BaseObjectState,\s*global::Opc\.Ua\.ISystemContext,\s*global::System\.Threading\.CancellationToken,\s*global::System\.Collections\.Generic\.IAsyncEnumerable<TEvent>>\s+factory"),
"NotifierObjectBuilder must expose the factory-style Publish<TEvent> overload");
Assert.That(fb, Does.Contain(
"where TEvent : global::Opc.Ua.BaseEventState"),
"Publish<TEvent> must be constrained to BaseEventState");
Assert.That(fb, Does.Contain(
"global::Opc.Ua.Server.Fluent.EventNotifierBuilderExtensions.Publish<global::Opc.Ua.BaseObjectState, TEvent>(__node,"),
"Publish overload must forward to EventNotifierBuilderExtensions.Publish with the wrapper's state type as TNotifier");
}
[Test]
public void EmittedFluentBuilders_PublishOverloadEmittedOnGeneratesEventWrapper()
{
string fb = GetFluentBuilders();
// EventEmittingObject does not set SupportsEvents but declares
// a forward GeneratesEvent reference. The wrapper must still
// expose Publish<TEvent>; the qualification logic walks both
// the SupportsEvents flag and outgoing GeneratesEvent /
// AlwaysGeneratesEvent references.
Assert.That(fb, Does.Match(
@"(?ms)internal\s+sealed\s+class\s+EventEmittingObjectBuilder\b.*?Publish<TEvent>"),
"EventEmittingObjectBuilder must expose Publish<TEvent> because of the GeneratesEvent reference");
}
[Test]
public void EmittedFluentBuilders_PublishOverloadAbsentOnPlainObjectWrapper()
{
string fb = GetFluentBuilders();
// TestObject (RestrictedObjectType) is a plain object: no
// SupportsEvents, no GeneratesEvent. It must NOT carry a
// typed Publish overload — the surface stays clean and only
// notifier candidates become discoverable through intellisense.
Assert.That(fb, Does.Not.Match(
@"(?ms)internal\s+sealed\s+class\s+TestObjectBuilder\b(?:(?!internal\s+sealed\s+class).)*?Publish<TEvent>"),
"TestObjectBuilder must not expose Publish<TEvent> — it's not a notifier");
}
private static string GetFluentBuilders()
{
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: true);
return files.Single(kv => kv.Key.EndsWith(".FluentBuilders.g.cs", StringComparison.Ordinal)).Value;
}
private static Dictionary<string, string> GenerateForTestModel(bool generateNodeManager)
{
const string designFile = "TestModel.xml";
ITelemetryContext telemetry = NUnitTelemetryContext.Create(logLevel: LogLevel.Error);
using var fileSystem = new VirtualFileSystem();
string resources = Path.Combine(Directory.GetCurrentDirectory(), "Resources");
Generators.GenerateCode(new DesignFileCollection
{
Targets = [Path.Combine(resources, designFile)],
IdentifierFilePath = Path.Combine(
resources,
Path.GetFileNameWithoutExtension(designFile) + ".csv"),
Options = new DesignFileOptions
{
GenerateNodeManager = generateNodeManager
}
}, fileSystem, string.Empty, telemetry);
return fileSystem.CreatedFiles
.Where(c => Path.GetExtension(c) == ".cs")
.ToDictionary(c => c, c => Encoding.UTF8.GetString(fileSystem.Get(c)));
}
}
}