machine/machine_test.go
Matthew Rich e533a67303
Some checks failed
Machine Tests / test (push) Waiting to run
Lint / golangci-lint (push) Has been cancelled
add support for multiple source states in transitions
2024-05-20 12:24:24 -07:00

70 lines
2.0 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package machine
import (
"github.com/stretchr/testify/assert"
"log"
"testing"
)
func setupStater(initial State) Stater {
s := New(initial)
if s == nil {
log.Fatal("Failed creating new Stater")
}
return s
}
func TestMachineStater(t *testing.T) {
s := setupStater("disconnected")
s.AddStates("disconnected", "start_connection", "connected")
r := s.GetState("connected")
if r != "connected" {
t.Errorf("Failed checking state: %s", r)
}
}
func TestMachineCurrentState(t *testing.T) {
s := setupStater("disconnected")
s.AddStates("disconnected", "start_connection", "connected")
r := s.CurrentState()
if r != "disconnected" {
t.Errorf("Failed checking state: %s", r)
}
}
func TestMachineAddTransition(t *testing.T) {
s := setupStater("disconnected")
s.AddStates("disconnected", "start_connection", "connected")
s.AddTransition("connect", States("disconnected"), "start_connection")
s.AddModel(setupModel("disconnected"))
// worker gets a trigger message
assert.Nil(t, s.Trigger("connect"))
// machine generates transition event mesages
if s.CurrentState() != "start_connection" {
t.Errorf("State transition failed for: connect - %s", s.CurrentState())
}
}
func TestMachineAddSubscription(t *testing.T) {
x := setupSubscriber()
s := setupStater("disconnected")
s.AddStates("disconnected", "start_connection", "connected")
s.AddTransition("connect", States("disconnected"), "start_connection")
assert.Nil(t, s.AddSubscription("connect", x))
s.AddModel(setupModel("disconnected"))
assert.Nil(t, s.Trigger("connect"))
exitMessage := <-*x.(*EventChannel)
enterMessage := <-*x.(*EventChannel)
if exitMessage.On == EXITSTATEEVENT && exitMessage.Source == "disconnected" {
if enterMessage.On == ENTERSTATEEVENT && enterMessage.Dest == "start_connection" {
return
}
}
t.Errorf("Unexpected event message in state transition notification: exit: %s, enter: %s", exitMessage, enterMessage)
}