mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-21 17:16:16 +08:00
e61ad4b306
# Description Part 16 §B.3 places `HasSubStateMachine` on the parent **state** node, but the fluent builder attached it to the state-machine **root** because `FluentFiniteStateMachineState` never materialized state nodes at all. Investigating #3821 showed the gap was wider than the reference placement: 1. **No state nodes existed.** The NodeId written into `CurrentState/Id` — `new NodeId(stateId, ElementNamespaceIndex)` — was **dangling**: no node with that id was in the address space. 2. **`AvailableStates` was never populated**, so `GetAvailableStatesAsync` returned empty against a fluent-built server. 3. **The whole client discovery chain was therefore dead.** `ObserveEffectiveStateAsync` enumerates `AvailableStates` and browses `HasSubStateMachine` from each state node — it found nothing. The client side was already spec-correct; only the server deviated. 4. **`HasSubStateMachine` is non-hierarchical** (a subtype of `NonHierarchicalReferences`, `i=32`). Using it as the sub-SM's `BaseInstanceState.ReferenceTypeId` left the sub-SM unreachable from a hierarchical browse of the machine. ## What changed **Element nodes are materialized.** Definition-mode machines now create one `StateType` node per declared state and one `TransitionType` node per declared transition — each a `HasComponent` child carrying `StateNumber` / `TransitionNumber`, with the §B.4 `FromState` / `ToState` / `HasEffect` references and `HasCause` added by `WithCause`. `AvailableStates`, `AvailableTransitions` and `LastTransition` are populated, so `CurrentState/Id` and `LastTransition/Id` resolve to real, browsable nodes. NodeIds are per-instance, so several machines built from one definition coexist. **`HasSubStateMachine` moved to the state node**, with the inverse `SubStateMachineOf`, and the sub-SM is attached as a `HasComponent` child (fixing 4). **Core gains element-id mapping hooks.** `GetCurrentStateId` / `UpdateStateVariable` / `UpdateTransitionVariable` hard-coded the numeric form and were non-virtual, so a subclass could not redirect them. They now route through `public virtual` `GetStateNodeId` / `GetStateId` / `GetTransitionNodeId` / `GetTransitionId`, whose defaults reproduce the previous `(elementId, ElementNamespaceIndex)` convention **exactly** — every stack-shipped and generator-emitted machine is unaffected, and there is a regression test asserting that. **Generated machines report their model namespace.** The generator now emits an `ElementNamespaceUri` override on `FiniteStateMachineType` subtypes, taken from the nearest type that actually *declares* state children — a subtype that only adds behaviour inherits its elements, and their namespace, from its base. **Ordering and validation fixes.** `WithSubStateMachine` and `WithInitialState` are now order-independent (previously, attaching a sub-SM before setting the initial state left the child suspended until the parent left and re-entered the state — silently). `WithSubStateMachine` validates `parentStateId`, and the builder rejects duplicate element browse names, since element NodeIds are now derived from them. ## A defect this surfaced Code that assembles nodes with the generated `CreateInstanceOf<Type>` factories never calls `NodeState.CreateAsPredefinedNode`, so `OnBeforeCreate` / `OnAfterCreate` are skipped for the entire subtree — and `OnAfterCreate` is the only place a state machine resolves its element namespace. It is also where `ConditionState` binds its `Enable` / `Disable` / `AddComment` handlers and `AlarmConditionState` binds the shelving methods, so the impact is broader than state machines. This PR fixes only the two call sites it depends on — DI's `SoftwareUpdateFacetWiring` and Robotics' `RoboticsOperationBuilder`. **The repository-wide audit is deliberately left out of scope and tracked in #4320** (24 files call these factories; none completed the lifecycle). The Robotics regression had no test coverage at all, so an assertion on `CurrentState/Id` was added and verified to fail without the fix. ## Breaking changes - Sub-state machines are **no longer browsable from the state-machine root**. Callers passing a machine's `ObjectId` to `GetSubStateMachineAsync` must pass a state NodeId instead — from `GetAvailableStatesAsync` or a snapshot's `CurrentStateId`. - `CurrentState/Id` for fluent machines changes from the numeric form to the materialized node's id. Code reading a numeric id out of it should call `FiniteStateMachineState.GetStateId` rather than parsing the identifier. - Generated machines qualify `CurrentState/Id` / `LastTransition/Id` with their companion-spec namespace instead of the OPC UA one. Documented in `docs/WhatsNewIn2.0.md` and `docs/StateMachines.md`. ## Notes for reviewers - Adding `virtual` to the `FiniteStateMachineState` members is a binary (not source) breaking change — assumed acceptable on the 2.0 line, but worth confirming against the compatibility policy. - Address-space cost is one node plus one property per declared state and transition, per machine instance; called out in the docs for servers instantiating many machines. - `AvailableTransitions` is modelled as a `HasComponent` `BaseDataVariable` (matching the standard NodeSet and what the client's browse path expects), not a Property. ## Related Issues - Fixes #3821 - Surfaced #4320 (node create lifecycle audit — not addressed here) ## 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. - [x] 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. ### Test runs (net10.0) | Suite | Result | |---|---| | `Opc.Ua.Server.Tests` (full) | 4734 passed, 5 skipped | | `Opc.Ua.SourceGeneration.Core.Tests` | 3780 passed | | `Opc.Ua.SourceGeneration.Tests` | 132 passed | | `Opc.Ua.SourceGeneration.Stack.Tests` | 94 passed | | `Opc.Ua.Types.Tests` | 8763 passed | | `Opc.Ua.Robotics.Tests` | 540 passed | | `Opc.Ua.Robotics.Intent.Tests` | 22 passed | | `Opc.Ua.Di.Tests` | 424 passed | | `Opc.Ua.ISA95.Tests` | 136 passed | | `Opc.Ua.Aas.Tests` | 670 passed | | `Opc.Ua.Positioning.Tests` | 69 passed | | `Opc.Ua.Client.Tests` (StateMachines) | 36 passed | Only net10.0 was run locally; the .NET Framework leg is left to CI, hence the unchecked box above. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
526 lines
20 KiB
C#
526 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.Threading;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Server.StateMachines;
|
|
|
|
namespace Opc.Ua.Server.Tests.StateMachines
|
|
{
|
|
/// <summary>
|
|
/// Unit tests for lifecycle-mode behavior on the unified
|
|
/// <see cref="StateMachineBuilder{TState}"/> — exercises
|
|
/// <c>WithInitialState</c>, <c>OnEnterState</c>, <c>OnExitState</c>,
|
|
/// <c>OnTransition</c>, <c>OnBeforeTransition</c>, <c>WithCause</c>,
|
|
/// <c>WithTimedTransition</c>, and <c>ConfigureStateMachine</c>.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Server")]
|
|
[Category("StateMachines")]
|
|
[Parallelizable]
|
|
public sealed class StateMachineBuilderLifecycleTests
|
|
{
|
|
private ServerSystemContext m_context = null!;
|
|
|
|
[SetUp]
|
|
public void SetUp()
|
|
{
|
|
m_context = StateMachineTestFixtures.CreateContext();
|
|
}
|
|
|
|
[Test]
|
|
public void WithInitialStateSetsCurrentState()
|
|
{
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.StateMachine;
|
|
|
|
Assert.That(CurrentStateId(sm), Is.EqualTo(1u));
|
|
}
|
|
|
|
[Test]
|
|
public void WithInitialStateRejectsUndeclaredStateId()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
|
|
Assert.That(() => b.WithInitialState(99),
|
|
Throws.InvalidOperationException);
|
|
}
|
|
|
|
[Test]
|
|
public void OnEnterStateFiresWhenStateChanges()
|
|
{
|
|
int enterCount = 0;
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnEnterState(2, (ctx, m) => enterCount++)
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(enterCount, Is.EqualTo(1));
|
|
Assert.That(CurrentStateId(sm), Is.EqualTo(2u));
|
|
}
|
|
|
|
[Test]
|
|
public void OnExitStateFiresWhenLeavingState()
|
|
{
|
|
int exitCount = 0;
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnExitState(1, (ctx, m) => exitCount++)
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(exitCount, Is.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public void OnTransitionReceivesFromAndToIds()
|
|
{
|
|
uint observedFrom = 0;
|
|
uint observedTo = 0;
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnTransition((ctx, m, from, to) =>
|
|
{
|
|
observedFrom = from;
|
|
observedTo = to;
|
|
})
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(observedFrom, Is.EqualTo(1u));
|
|
Assert.That(observedTo, Is.EqualTo(2u));
|
|
}
|
|
|
|
[Test]
|
|
public void OnBeforeTransitionCanVetoTransition()
|
|
{
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnBeforeTransition((ctx, m, transitionId, causeId)
|
|
=> StatusCodes.BadUserAccessDenied)
|
|
.StateMachine;
|
|
|
|
ServiceResult result = sm.DoTransition(m_context,
|
|
transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(ServiceResult.IsBad(result), Is.True);
|
|
Assert.That(CurrentStateId(sm), Is.EqualTo(1u),
|
|
"veto must keep machine in the original state");
|
|
}
|
|
|
|
[Test]
|
|
public void OnBeforeTransitionReceivesTransitionAndCauseIds()
|
|
{
|
|
uint observedTransition = 0;
|
|
uint observedCause = 0;
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnBeforeTransition((ctx, m, transitionId, causeId) =>
|
|
{
|
|
observedTransition = transitionId;
|
|
observedCause = causeId;
|
|
return ServiceResult.Good;
|
|
})
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 100,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(observedTransition, Is.EqualTo(10u));
|
|
Assert.That(observedCause, Is.EqualTo(100u));
|
|
}
|
|
|
|
[Test]
|
|
public void WithCauseRejectsNullOrNonNumericNodeId()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
|
|
Assert.That(() => b.WithCause(NodeId.Null),
|
|
Throws.ArgumentException);
|
|
Assert.That(() => b.WithCause(new NodeId("text-id", 0)),
|
|
Throws.ArgumentException);
|
|
}
|
|
|
|
[Test]
|
|
public void WithCauseRejectsUnknownMethodNodeId()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() => b.WithCause(new NodeId(99999u, 0)),
|
|
Throws.ArgumentException);
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimedTransitionFiresAfterTimeout()
|
|
{
|
|
using var done = new ManualResetEventSlim(false);
|
|
_ = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnEnterState(2, (ctx, m) => done.Set())
|
|
.WithTimedTransition(
|
|
fromStateId: 1,
|
|
timeout: TimeSpan.FromMilliseconds(50),
|
|
transitionId: 10)
|
|
.StateMachine;
|
|
|
|
Assert.That(done.Wait(TimeSpan.FromSeconds(2)), Is.True,
|
|
"timed transition should fire within 2 s");
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimedTransitionArmsOnEntryAfterTransition()
|
|
{
|
|
using var done = new ManualResetEventSlim(false);
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(2)
|
|
.OnEnterState(2, (ctx, m) => done.Set())
|
|
.WithTimedTransition(
|
|
fromStateId: 1,
|
|
timeout: TimeSpan.FromMilliseconds(50),
|
|
transitionId: 10)
|
|
.StateMachine;
|
|
|
|
// Now move to state 1 — this should arm the timer (via
|
|
// DispatchAfter), which fires the transition back to state 2.
|
|
sm.DoTransition(m_context, transitionId: 20, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(done.Wait(TimeSpan.FromSeconds(2)), Is.True,
|
|
"timed transition should fire within 2 s of state-1 entry");
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimedTransitionArmsWhenInitialStateIsSetAfterwards()
|
|
{
|
|
// WithInitialState goes through SetState (no transition),
|
|
// so the initial-state synchronizer is the only chance to
|
|
// arm the timer for the state entered that way.
|
|
using var done = new ManualResetEventSlim(false);
|
|
_ = BuildOnOffMachine()
|
|
.OnEnterState(2, (ctx, m) => done.Set())
|
|
.WithTimedTransition(
|
|
fromStateId: 1,
|
|
timeout: TimeSpan.FromMilliseconds(50),
|
|
transitionId: 10)
|
|
.WithInitialState(1)
|
|
.StateMachine;
|
|
|
|
Assert.That(done.Wait(TimeSpan.FromSeconds(2)), Is.True,
|
|
"timed transition should fire when WithInitialState " +
|
|
"follows WithTimedTransition");
|
|
}
|
|
|
|
[Test]
|
|
public void AddStateFailureLeavesTheDefinitionUnchanged()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b =
|
|
StateMachineTestFixtures.NewBuilder(m_context)
|
|
.AddState(1, "A", isInitial: true)
|
|
.AddState(2, "B")
|
|
.AddTransition(10, "AToB", from: 1, to: 2);
|
|
|
|
Assert.That(() => b.AddState(3, "C", isInitial: true),
|
|
Throws.InvalidOperationException);
|
|
|
|
// The rejected state must not linger in the definition —
|
|
// it would be materialized but invisible to the tables.
|
|
FluentFiniteStateMachineState sm = b.StateMachine;
|
|
Assert.That(sm.Definition.States, Has.Count.EqualTo(2));
|
|
Assert.That(sm.GetStateNodeId(3), Is.EqualTo(NodeId.Null));
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimedTransitionRejectsNonPositiveTimeout()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() =>
|
|
b.WithTimedTransition(1, TimeSpan.Zero, 10),
|
|
Throws.TypeOf<ArgumentOutOfRangeException>());
|
|
Assert.That(() =>
|
|
b.WithTimedTransition(1, TimeSpan.FromMilliseconds(-1), 10),
|
|
Throws.TypeOf<ArgumentOutOfRangeException>());
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimedTransitionRejectsUnknownFromStateInDefinitionMode()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() =>
|
|
b.WithTimedTransition(99, TimeSpan.FromMilliseconds(10), 10),
|
|
Throws.InvalidOperationException);
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimedTransitionRejectsUnknownTransitionInDefinitionMode()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() =>
|
|
b.WithTimedTransition(1, TimeSpan.FromMilliseconds(10), 999),
|
|
Throws.InvalidOperationException);
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimedTransitionRejectsTransitionWithMismatchedFromState()
|
|
{
|
|
// Transition 20 has from=2; passing fromStateId=1 should fail.
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() =>
|
|
b.WithTimedTransition(1, TimeSpan.FromMilliseconds(10), 20),
|
|
Throws.InvalidOperationException);
|
|
}
|
|
|
|
[Test]
|
|
public void WithInitialStateDoesNotFireOnEnterState()
|
|
{
|
|
int enterCount = 0;
|
|
_ = BuildOnOffMachine()
|
|
.OnEnterState(1, (ctx, m) => enterCount++)
|
|
.WithInitialState(1)
|
|
.StateMachine;
|
|
|
|
Assert.That(enterCount, Is.Zero,
|
|
"WithInitialState must not fire lifecycle handlers — " +
|
|
"initial state assignment is not a transition.");
|
|
}
|
|
|
|
[Test]
|
|
public void ConfigureStateMachineRunsCallback()
|
|
{
|
|
FluentFiniteStateMachineState captured = null!;
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.ConfigureStateMachine(s => captured = s)
|
|
.StateMachine;
|
|
|
|
Assert.That(captured, Is.SameAs(sm));
|
|
}
|
|
|
|
[Test]
|
|
public void ConfigureStateMachineRejectsNullCallback()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() => b.ConfigureStateMachine(null!),
|
|
Throws.ArgumentNullException);
|
|
}
|
|
|
|
[Test]
|
|
public void ExistingOnAfterTransitionRunsBeforeBuilderHandlers()
|
|
{
|
|
// Build a machine, then install a pre-existing OnAfter
|
|
// BEFORE handing it to a lifecycle builder. Verify the
|
|
// existing handler fires first and the builder handlers
|
|
// see the same final state.
|
|
FluentFiniteStateMachineState sm =
|
|
StateMachineTestFixtures.NewBuilder(m_context)
|
|
.AddState(1, "Off", isInitial: true)
|
|
.AddState(2, "On")
|
|
.AddTransition(10, "OffToOn", from: 1, to: 2)
|
|
.StateMachine;
|
|
sm.SetState(m_context, 1);
|
|
|
|
var order = new List<string>();
|
|
sm.OnAfterTransition = (ctx, m, t, c, ins, outs) =>
|
|
{
|
|
order.Add("original");
|
|
return ServiceResult.Good;
|
|
};
|
|
|
|
StateMachineBuilder.For(sm, m_context)
|
|
.OnTransition((ctx, m, from, to) => order.Add("builder"));
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(order, Is.EqualTo(s_originalThenBuilder));
|
|
}
|
|
|
|
[Test]
|
|
public void LifecycleOrderIsExitTransitionEnter()
|
|
{
|
|
var order = new List<string>();
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnExitState(1, (ctx, m) => order.Add("exit-1"))
|
|
.OnTransition((ctx, m, from, to) => order.Add($"trans-{from}-{to}"))
|
|
.OnEnterState(2, (ctx, m) => order.Add("enter-2"))
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(order, Is.EqualTo(s_lifecycleOrder));
|
|
}
|
|
|
|
private static readonly string[] s_originalThenBuilder = ["original", "builder"];
|
|
private static readonly string[] s_lifecycleOrder = ["exit-1", "trans-1-2", "enter-2"];
|
|
|
|
[Test]
|
|
public void HandlerExceptionsDoNotBreakSubsequentHandlers()
|
|
{
|
|
int laterCount = 0;
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnEnterState(2, (ctx, m) =>
|
|
throw new InvalidOperationException("simulated"))
|
|
.OnEnterState(2, (ctx, m) => laterCount++)
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
Assert.That(laterCount, Is.EqualTo(1),
|
|
"second handler should run even if the first threw");
|
|
}
|
|
|
|
[Test]
|
|
public async System.Threading.Tasks.Task OnEnterStateAsyncFiresWhenStateChanges()
|
|
{
|
|
var signaled = new System.Threading.Tasks.TaskCompletionSource<bool>(
|
|
System.Threading.Tasks.TaskCreationOptions.RunContinuationsAsynchronously);
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnEnterStateAsync(2, async (ctx, m, ct) =>
|
|
{
|
|
await System.Threading.Tasks.Task.Yield();
|
|
signaled.TrySetResult(true);
|
|
})
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
cts.Token.Register(() => signaled.TrySetCanceled());
|
|
await signaled.Task.ConfigureAwait(false);
|
|
Assert.That(CurrentStateId(sm), Is.EqualTo(2u));
|
|
}
|
|
|
|
[Test]
|
|
public async System.Threading.Tasks.Task OnExitStateAsyncFiresWhenLeavingState()
|
|
{
|
|
var signaled = new System.Threading.Tasks.TaskCompletionSource<bool>(
|
|
System.Threading.Tasks.TaskCreationOptions.RunContinuationsAsynchronously);
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnExitStateAsync(1, async (ctx, m, ct) =>
|
|
{
|
|
await System.Threading.Tasks.Task.Yield();
|
|
signaled.TrySetResult(true);
|
|
})
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
cts.Token.Register(() => signaled.TrySetCanceled());
|
|
await signaled.Task.ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async System.Threading.Tasks.Task OnTransitionAsyncReceivesFromAndToIds()
|
|
{
|
|
var signaled = new System.Threading.Tasks.TaskCompletionSource<(uint from, uint to)>(
|
|
System.Threading.Tasks.TaskCreationOptions.RunContinuationsAsynchronously);
|
|
FluentFiniteStateMachineState sm = BuildOnOffMachine()
|
|
.WithInitialState(1)
|
|
.OnTransitionAsync(async (ctx, m, from, to, ct) =>
|
|
{
|
|
await System.Threading.Tasks.Task.Yield();
|
|
signaled.TrySetResult((from, to));
|
|
})
|
|
.StateMachine;
|
|
|
|
sm.DoTransition(m_context, transitionId: 10, causeId: 0,
|
|
inputArguments: default, outputArguments: []);
|
|
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
cts.Token.Register(() => signaled.TrySetCanceled());
|
|
(uint from, uint to) = await signaled.Task.ConfigureAwait(false);
|
|
Assert.That(from, Is.EqualTo(1u));
|
|
Assert.That(to, Is.EqualTo(2u));
|
|
}
|
|
|
|
[Test]
|
|
public void OnEnterStateAsyncRejectsNullHandler()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() => b.OnEnterStateAsync(1, null!),
|
|
Throws.ArgumentNullException);
|
|
}
|
|
|
|
[Test]
|
|
public void OnExitStateAsyncRejectsNullHandler()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() => b.OnExitStateAsync(1, null!),
|
|
Throws.ArgumentNullException);
|
|
}
|
|
|
|
[Test]
|
|
public void OnTransitionAsyncRejectsNullHandler()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> b = BuildOnOffMachine();
|
|
Assert.That(() => b.OnTransitionAsync(null!),
|
|
Throws.ArgumentNullException);
|
|
}
|
|
|
|
private StateMachineBuilder<FluentFiniteStateMachineState> BuildOnOffMachine()
|
|
{
|
|
return StateMachineTestFixtures.NewBuilder(m_context)
|
|
.AddState(1, "Off", isInitial: true)
|
|
.AddState(2, "On")
|
|
.AddTransition(10, "OffToOn", from: 1, to: 2)
|
|
.AddTransition(20, "OnToOff", from: 2, to: 1)
|
|
.OnCause(100, from: 1, transition: 10)
|
|
.OnCause(200, from: 2, transition: 20);
|
|
}
|
|
|
|
private static uint CurrentStateId(FluentFiniteStateMachineState sm)
|
|
{
|
|
if (sm.CurrentState?.Id?.Value is { } id && !id.IsNull)
|
|
{
|
|
// Resolve through the machine's own mapping so
|
|
// materialized state NodeIds are understood too.
|
|
return sm.GetStateId(id);
|
|
}
|
|
return 0;
|
|
}
|
|
}
|
|
}
|