mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-24 02:58:36 +08:00
# 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>
512 lines
22 KiB
C#
512 lines
22 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 NUnit.Framework;
|
|
using Opc.Ua.Server.StateMachines;
|
|
|
|
namespace Opc.Ua.Server.Tests.StateMachines
|
|
{
|
|
/// <summary>
|
|
/// Unit tests for <see cref="StateMachineBuilder{TState}.WithSubStateMachine"/>
|
|
/// — the hierarchical state-machine builder sugar. Verifies the
|
|
/// HasSubStateMachine wiring, parent-state-entry activation, the
|
|
/// suspend-on-exit semantics, and the per-parent-state reset
|
|
/// behavior (with the <c>preserveOnReentry</c> opt-out).
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Server")]
|
|
[Category("StateMachines")]
|
|
[Parallelizable]
|
|
public sealed class StateMachineBuilderSubStateTests
|
|
{
|
|
private ServerSystemContext m_context = null!;
|
|
|
|
[SetUp]
|
|
public void SetUp()
|
|
{
|
|
m_context = StateMachineTestFixtures.CreateContext();
|
|
}
|
|
|
|
[Test]
|
|
public void WithSubStateMachineAddsHasComponentChild()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(1)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddState(11, "ChildRunning")
|
|
.AddTransition(100, "IdleToRunning", from: 10, to: 11))
|
|
.StateMachine;
|
|
|
|
var children = new List<BaseInstanceState>();
|
|
parent.GetChildren(m_context, children);
|
|
BaseInstanceState child = children.Find(c => c.BrowseName.Name == "ChildSm")!;
|
|
|
|
Assert.That(child, Is.Not.Null);
|
|
// HasSubStateMachine is non-hierarchical, so the parent /
|
|
// child relationship uses HasComponent — matching the
|
|
// standard NodeSets.
|
|
Assert.That(child.ReferenceTypeId,
|
|
Is.EqualTo(ReferenceTypeIds.HasComponent));
|
|
Assert.That(child, Is.InstanceOf<FluentFiniteStateMachineState>());
|
|
}
|
|
|
|
[Test]
|
|
public void WithSubStateMachineReferencesSubMachineFromParentStateNode()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(1)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddTransition(100, "Loop", from: 10, to: 10))
|
|
.StateMachine;
|
|
|
|
BaseInstanceState child = GetChild(parent, "ChildSm");
|
|
BaseInstanceState stateNode = GetChild(parent, "ParentA");
|
|
|
|
// Part 16 §4.4.16: the reference hangs off the parent STATE
|
|
// node, not the state machine root.
|
|
var forward = new List<IReference>();
|
|
stateNode.GetReferences(
|
|
m_context, forward, ReferenceTypeIds.HasSubStateMachine, false);
|
|
Assert.That(forward, Has.Count.EqualTo(1));
|
|
Assert.That(forward[0].TargetId, Is.EqualTo((ExpandedNodeId)child.NodeId));
|
|
|
|
// ... and the inverse (SubStateMachineOf) browses back.
|
|
var inverse = new List<IReference>();
|
|
child.GetReferences(
|
|
m_context, inverse, ReferenceTypeIds.HasSubStateMachine, true);
|
|
Assert.That(inverse, Has.Count.EqualTo(1));
|
|
Assert.That(inverse[0].TargetId, Is.EqualTo((ExpandedNodeId)stateNode.NodeId));
|
|
|
|
// The state machine root must NOT carry the reference.
|
|
var fromRoot = new List<IReference>();
|
|
parent.GetReferences(
|
|
m_context, fromRoot, ReferenceTypeIds.HasSubStateMachine, false);
|
|
Assert.That(fromRoot, Is.Empty);
|
|
}
|
|
|
|
[Test]
|
|
public void SubStateMachineIsDiscoverableThroughTheNodeBrowser()
|
|
{
|
|
// Drives the real NodeBrowser along the exact path a client
|
|
// takes: hierarchical browse of the machine to reach the
|
|
// state node and the sub-SM, then HasSubStateMachine from
|
|
// the state node. HasSubStateMachine is non-hierarchical,
|
|
// so using it as the parent/child reference would leave the
|
|
// sub-SM invisible to the first of those browses.
|
|
//
|
|
// NodeState.PopulateBrowser only walks children when the
|
|
// TypeTable can tell it the browsed reference type is
|
|
// hierarchical, so the bare test table needs that one fact.
|
|
var typeTable = (TypeTable)m_context.TypeTable;
|
|
typeTable.AddReferenceSubtype(
|
|
ReferenceTypeIds.HierarchicalReferences,
|
|
NodeId.Null,
|
|
new QualifiedName(BrowseNames.HierarchicalReferences));
|
|
typeTable.AddReferenceSubtype(
|
|
ReferenceTypeIds.HasComponent,
|
|
ReferenceTypeIds.HierarchicalReferences,
|
|
new QualifiedName(BrowseNames.HasComponent));
|
|
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(1)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddTransition(100, "Loop", from: 10, to: 10))
|
|
.StateMachine;
|
|
|
|
List<NodeId> components = BrowseTargets(
|
|
parent, ReferenceTypeIds.HasComponent, BrowseDirection.Forward);
|
|
NodeId stateNodeId = GetChild(parent, "ParentA").NodeId;
|
|
NodeId childNodeId = GetChild(parent, "ChildSm").NodeId;
|
|
|
|
Assert.That(components, Does.Contain(stateNodeId));
|
|
Assert.That(components, Does.Contain(childNodeId));
|
|
|
|
List<NodeId> subMachines = BrowseTargets(
|
|
GetChild(parent, "ParentA"),
|
|
ReferenceTypeIds.HasSubStateMachine,
|
|
BrowseDirection.Forward);
|
|
|
|
Assert.That(subMachines, Is.EqualTo(new[] { childNodeId }));
|
|
}
|
|
|
|
private List<NodeId> BrowseTargets(
|
|
NodeState node,
|
|
NodeId referenceTypeId,
|
|
BrowseDirection direction)
|
|
{
|
|
var targets = new List<NodeId>();
|
|
using INodeBrowser browser = node.CreateBrowser(
|
|
m_context,
|
|
null,
|
|
referenceTypeId,
|
|
false,
|
|
direction,
|
|
default,
|
|
null,
|
|
false);
|
|
for (IReference reference = browser.Next();
|
|
reference != null;
|
|
reference = browser.Next())
|
|
{
|
|
targets.Add(ExpandedNodeId.ToNodeId(
|
|
reference.TargetId, m_context.NamespaceUris));
|
|
}
|
|
return targets;
|
|
}
|
|
|
|
[Test]
|
|
public void WithSubStateMachineRejectsBrowseNameCollidingWithState()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> builder =
|
|
BuildParent().WithInitialState(1);
|
|
|
|
// The sub-SM NodeId is composed like the element NodeIds,
|
|
// so a browse name shared with a state would collide.
|
|
Assert.Throws<ArgumentException>(() =>
|
|
builder.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ParentA", 1),
|
|
configure: c => c.AddState(10, "ChildIdle", isInitial: true)));
|
|
}
|
|
|
|
[Test]
|
|
public void WithSubStateMachineRejectsUnknownParentState()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> builder =
|
|
BuildParent().WithInitialState(1);
|
|
|
|
Assert.Throws<InvalidOperationException>(() =>
|
|
builder.WithSubStateMachine(
|
|
parentStateId: 99,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c.AddState(10, "ChildIdle", isInitial: true)));
|
|
}
|
|
|
|
[Test]
|
|
public void SubStateMachineActivatesWhenInitialStateIsSetAfterwards()
|
|
{
|
|
// WithInitialState goes through SetState, which fires no
|
|
// enter handler — the sub-SM must still activate, so this
|
|
// call order behaves the same as the reverse one.
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddState(11, "ChildRunning")
|
|
.AddTransition(100, "IdleToRunning", from: 10, to: 11))
|
|
.WithInitialState(1)
|
|
.StateMachine;
|
|
|
|
var child = (FluentFiniteStateMachineState)GetChild(parent, "ChildSm");
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(child.IsSuspended, Is.False);
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(10u));
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void SubStateMachineStaysSuspendedWhenInitialStateIsElsewhere()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddTransition(100, "Loop", from: 10, to: 10))
|
|
.WithInitialState(2)
|
|
.StateMachine;
|
|
|
|
var child = (FluentFiniteStateMachineState)GetChild(parent, "ChildSm");
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(child.IsSuspended, Is.True);
|
|
// Part 16: an inactive sub-state machine publishes no
|
|
// current state — its declared initial state is only
|
|
// applied once the parent enters the attached state.
|
|
Assert.That(child.CurrentState!.Value.IsNullOrEmpty, Is.True);
|
|
// ... and OPC 10000-16 §4.4.6: CurrentState and
|
|
// LastTransition of an inactive sub-SM read with
|
|
// Bad_StateNotActive.
|
|
Assert.That(child.CurrentState.StatusCode,
|
|
Is.EqualTo((StatusCode)StatusCodes.BadStateNotActive));
|
|
Assert.That(child.LastTransition!.StatusCode,
|
|
Is.EqualTo((StatusCode)StatusCodes.BadStateNotActive));
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void ResumedSubStateMachineReadsGoodAgain()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddTransition(100, "Loop", from: 10, to: 10))
|
|
.WithInitialState(2)
|
|
.StateMachine;
|
|
var child = (FluentFiniteStateMachineState)GetChild(parent, "ChildSm");
|
|
Assert.That(child.CurrentState!.StatusCode,
|
|
Is.EqualTo((StatusCode)StatusCodes.BadStateNotActive));
|
|
|
|
// Parent enters the attached state → the sub-SM activates
|
|
// and its state variables read Good with the seeded state.
|
|
parent.DoTransition(m_context, 21, 0, default, []);
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(child.IsSuspended, Is.False);
|
|
Assert.That(child.CurrentState.StatusCode,
|
|
Is.EqualTo((StatusCode)StatusCodes.Good));
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(10u));
|
|
});
|
|
}
|
|
|
|
[Test]
|
|
public void PreserveOnReentryChildSurvivesALaterWithInitialState()
|
|
{
|
|
StateMachineBuilder<FluentFiniteStateMachineState> builder =
|
|
BuildParent()
|
|
.WithInitialState(1)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddState(11, "ChildRunning")
|
|
.AddTransition(100, "IdleToRunning", from: 10, to: 11),
|
|
preserveOnReentry: true);
|
|
FluentFiniteStateMachineState parent = builder.StateMachine;
|
|
var child = (FluentFiniteStateMachineState)GetChild(parent, "ChildSm");
|
|
|
|
// Move the child off its initial state, then re-apply the
|
|
// parent's initial state — a preserveOnReentry child must
|
|
// keep its state instead of being reset.
|
|
child.DoTransition(m_context, 100, 0, default, []);
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(11u));
|
|
|
|
builder.WithInitialState(1);
|
|
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(11u));
|
|
}
|
|
|
|
[Test]
|
|
public void WithSubStateMachineActivatesOnParentStateEntry()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(2) // parent starts in state 2 (sub-SM is NOT attached here)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddTransition(100, "Loop", from: 10, to: 10))
|
|
.StateMachine;
|
|
|
|
var child = (FluentFiniteStateMachineState)
|
|
GetChild(parent, "ChildSm");
|
|
|
|
// Sub-SM starts suspended (parent is in state 2, not 1).
|
|
Assert.That(child.IsSuspended, Is.True);
|
|
|
|
// Move parent to state 1 → sub-SM activates.
|
|
parent.DoTransition(m_context, 21, 0, default, []);
|
|
Assert.That(child.IsSuspended, Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void WithSubStateMachineSuspendsOnParentStateExit()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(1)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddTransition(100, "Loop", from: 10, to: 10))
|
|
.StateMachine;
|
|
|
|
var child = (FluentFiniteStateMachineState)
|
|
GetChild(parent, "ChildSm");
|
|
Assert.That(child.IsSuspended, Is.False);
|
|
|
|
// Move parent OFF state 1 → sub-SM suspended.
|
|
parent.DoTransition(m_context, 12, 0, default, []);
|
|
Assert.That(child.IsSuspended, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public void SuspendedSubStateMachineRejectsTransitionsWithBadStateNotActive()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(2) // parent in state 2, sub-SM suspended
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddTransition(100, "Loop", from: 10, to: 10))
|
|
.StateMachine;
|
|
|
|
var child = (FluentFiniteStateMachineState)
|
|
GetChild(parent, "ChildSm");
|
|
|
|
ServiceResult result = child.DoTransition(m_context, 100, 0, default, []);
|
|
|
|
Assert.That(ServiceResult.IsBad(result), Is.True);
|
|
Assert.That(result.Code, Is.EqualTo(StatusCodes.BadStateNotActive));
|
|
}
|
|
|
|
[Test]
|
|
public void ResetOnReentryRestoresInitialState()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(1)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddState(11, "ChildRunning")
|
|
.AddTransition(100, "IdleToRunning", from: 10, to: 11)
|
|
.OnCause(1000, from: 10, transition: 100))
|
|
.StateMachine;
|
|
|
|
var child = (FluentFiniteStateMachineState)
|
|
GetChild(parent, "ChildSm");
|
|
|
|
// Move child to "Running" state.
|
|
child.DoTransition(m_context, 100, 1000, default, []);
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(11u));
|
|
|
|
// Move parent off state 1 and back.
|
|
parent.DoTransition(m_context, 12, 0, default, []);
|
|
parent.DoTransition(m_context, 21, 0, default, []);
|
|
|
|
// Child should have reset to its initial state.
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(10u));
|
|
Assert.That(child.IsSuspended, Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void PreserveOnReentryRetainsChildState()
|
|
{
|
|
FluentFiniteStateMachineState parent = BuildParent()
|
|
.WithInitialState(1)
|
|
.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c
|
|
.AddState(10, "ChildIdle", isInitial: true)
|
|
.AddState(11, "ChildRunning")
|
|
.AddTransition(100, "IdleToRunning", from: 10, to: 11)
|
|
.OnCause(1000, from: 10, transition: 100),
|
|
preserveOnReentry: true)
|
|
.StateMachine;
|
|
|
|
var child = (FluentFiniteStateMachineState)
|
|
GetChild(parent, "ChildSm");
|
|
|
|
child.DoTransition(m_context, 100, 1000, default, []);
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(11u));
|
|
|
|
parent.DoTransition(m_context, 12, 0, default, []);
|
|
parent.DoTransition(m_context, 21, 0, default, []);
|
|
|
|
// Child retained its "Running" state across the
|
|
// parent-exit / re-entry cycle.
|
|
Assert.That(CurrentStateId(child), Is.EqualTo(11u));
|
|
Assert.That(child.IsSuspended, Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void WithSubStateMachineThrowsInLifecycleMode()
|
|
{
|
|
FluentFiniteStateMachineState sm = BuildParent().StateMachine;
|
|
var lifecycle =
|
|
StateMachineBuilder.For(sm, m_context);
|
|
|
|
Assert.That(() => lifecycle.WithSubStateMachine(
|
|
parentStateId: 1,
|
|
browseName: new QualifiedName("ChildSm", 1),
|
|
configure: c => c.AddState(10, "X", isInitial: true)),
|
|
Throws.InvalidOperationException);
|
|
}
|
|
|
|
private StateMachineBuilder<FluentFiniteStateMachineState> BuildParent()
|
|
{
|
|
return StateMachineTestFixtures.NewBuilder(m_context)
|
|
.AddState(1, "ParentA", isInitial: true)
|
|
.AddState(2, "ParentB")
|
|
.AddTransition(12, "AToB", from: 1, to: 2)
|
|
.AddTransition(21, "BToA", from: 2, to: 1);
|
|
}
|
|
|
|
private static BaseInstanceState GetChild(FluentFiniteStateMachineState parent, string browseName)
|
|
{
|
|
var children = new List<BaseInstanceState>();
|
|
parent.GetChildren(null!, children);
|
|
return children.Find(c => c.BrowseName.Name == browseName)!;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|