machine/machine_test.go
Matthew Rich 85e39191b8
Some checks failed
Lint / golangci-lint (push) Failing after 9m53s
Machine Tests / test (push) Successful in 40s
fix lint errors
2024-04-04 13:08:50 -07:00

70 lines
1.9 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"))
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)
}