machine/machine_test.go

70 lines
1.9 KiB
Go
Raw 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", "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())
}
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", "disconnected", "start_connection")
assert.Nil(t, s.AddSubscription("connect", x))
s.AddModel(setupModel("disconnected"))
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)
2024-04-04 17:33:22 +00:00
}