machine/machine_test.go

70 lines
2.0 KiB
Go
Raw Permalink Normal View History

2024-04-04 17:33:22 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
2024-04-04 20:08:50 +00:00
2024-04-04 17:33:22 +00:00
package machine
2024-04-04 20:08:50 +00:00
import (
2024-04-04 20:06:45 +00:00
"github.com/stretchr/testify/assert"
2024-04-04 20:08:50 +00:00
"log"
"testing"
2024-04-04 17:33:22 +00:00
)
func setupStater(initial State) Stater {
2024-04-04 20:08:50 +00:00
s := New(initial)
if s == nil {
log.Fatal("Failed creating new Stater")
}
return s
2024-04-04 17:33:22 +00:00
}
func TestMachineStater(t *testing.T) {
2024-04-04 20:08:50 +00:00
s := setupStater("disconnected")
2024-04-04 17:33:22 +00:00
2024-04-04 20:08:50 +00:00
s.AddStates("disconnected", "start_connection", "connected")
r := s.GetState("connected")
if r != "connected" {
t.Errorf("Failed checking state: %s", r)
}
2024-04-04 17:33:22 +00:00
}
func TestMachineCurrentState(t *testing.T) {
2024-04-04 20:08:50 +00:00
s := setupStater("disconnected")
2024-04-04 17:33:22 +00:00
2024-04-04 20:08:50 +00:00
s.AddStates("disconnected", "start_connection", "connected")
r := s.CurrentState()
if r != "disconnected" {
t.Errorf("Failed checking state: %s", r)
}
2024-04-04 17:33:22 +00:00
}
func TestMachineAddTransition(t *testing.T) {
2024-04-04 20:08:50 +00:00
s := setupStater("disconnected")
s.AddStates("disconnected", "start_connection", "connected")
s.AddTransition("connect", States("disconnected"), "start_connection")
2024-04-04 20:08:50 +00:00
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())
}
2024-04-04 17:33:22 +00:00
}
func TestMachineAddSubscription(t *testing.T) {
2024-04-04 20:08:50 +00:00
x := setupSubscriber()
s := setupStater("disconnected")
s.AddStates("disconnected", "start_connection", "connected")
s.AddTransition("connect", States("disconnected"), "start_connection")
2024-04-04 20:08:50 +00:00
assert.Nil(t, s.AddSubscription("connect", x))
s.AddModel(setupModel("disconnected"))
2024-04-04 20:43:46 +00:00
assert.Nil(t, s.Trigger("connect"))
2024-04-04 20:08:50 +00:00
exitMessage := <-*x.(*EventChannel)
enterMessage := <-*x.(*EventChannel)
2024-05-07 05:59:18 +00:00
if exitMessage.On == EXITSTATEEVENT && exitMessage.Source == "disconnected" {
if enterMessage.On == ENTERSTATEEVENT && enterMessage.Dest == "start_connection" {
2024-04-04 20:08:50 +00:00
return
}
}
t.Errorf("Unexpected event message in state transition notification: exit: %s, enter: %s", exitMessage, enterMessage)
2024-04-04 17:33:22 +00:00
}