Skip to content

Commit

Permalink
Throw InvalidOperationException when firing async action synchronously.
Browse files Browse the repository at this point in the history
  • Loading branch information
mclift committed Jun 2, 2023
1 parent 2ab545b commit 5bcedd6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/Stateless/EntryActionBehaviour.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ public AsyncFrom(TTriggerType trigger, Func<Transition, object[], Task> action,

public override void Execute(Transition transition, object[] args)
{
ExecuteAsync(transition, args);
if (transition.Trigger.Equals(Trigger))
{
base.Execute(transition, args);
}
}

public override Task ExecuteAsync(Transition transition, object[] args)
Expand Down
34 changes: 33 additions & 1 deletion test/Stateless.Tests/AsyncActionsFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,19 @@ public void VerifyNotEnterSuperstateWhenDoingInitialTransition()
Assert.Equal(State.D, sm.State);
}

[Fact]
public void OnEntryFromAsync_WhenTriggeredSynchronously_Throws()
{
var sm = new StateMachine<State, Trigger>(State.A);

sm.Configure(State.A).Permit(Trigger.X, State.B);

sm.Configure(State.B)
.OnEntryFromAsync(Trigger.X, async () => await Task.Run(() => { }));

Assert.Throws<InvalidOperationException>(() => sm.Fire(Trigger.X));
}

[Fact]
public async Task OnEntryFromAsync_WhenTriggered_InvokesAction()
{
Expand All @@ -490,6 +503,25 @@ public async Task OnEntryFromAsync_WhenTriggered_InvokesAction()
Assert.True(wasInvoked);
}

[Fact]
public void OnEntryFromAsync_WhenEnteringByAnotherTriggerSynchronously_DoesNotThrow()
{
bool wasInvoked = false;

var sm = new StateMachine<State, Trigger>(State.A);

sm.Configure(State.A)
.Permit(Trigger.X, State.B)
.Permit(Trigger.Y, State.B);

sm.Configure(State.B)
.OnEntryFromAsync(Trigger.X, async () => await Task.Run(() => { wasInvoked = true; }));

sm.Fire(Trigger.Y);

Assert.False(wasInvoked);
}

[Fact]
public async Task OnEntryFromAsync_WhenEnteringByAnotherTrigger_InvokesAction()
{
Expand All @@ -499,7 +531,7 @@ public async Task OnEntryFromAsync_WhenEnteringByAnotherTrigger_InvokesAction()

sm.Configure(State.A)
.Permit(Trigger.X, State.B)
.Permit(Trigger.Y, State.B); ;
.Permit(Trigger.Y, State.B);

sm.Configure(State.B)
.OnEntryFromAsync(Trigger.X, async () => await Task.Run(() => { wasInvoked = true; }));
Expand Down

0 comments on commit 5bcedd6

Please sign in to comment.