machine/machine_test.go
Matthew Rich d126067c56
All checks were successful
Lint / golangci-lint (push) Successful in 9m40s
Machine Tests / test (push) Successful in 41s
fix message fields
2024-05-06 22:59:18 -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", "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", "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)
}