machine/transition_test.go
Matthew Rich 1835255b6d
Some checks failed
Lint / golangci-lint (push) Has been cancelled
Machine Tests / test (push) Has been cancelled
add support for multiple source states in transitions
2024-05-20 12:31:17 -07:00

75 lines
1.8 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package machine
import (
"github.com/stretchr/testify/assert"
"log"
"testing"
)
func setupTransition() Transitioner {
t := NewTransition("open", States("closed"), "open")
if t == nil {
log.Fatal("Failed creating new transition")
}
return t
}
func setupSubscriber() Subscriber {
c := make(EventChannel, 2)
return &c
}
func TestNewTransition(t *testing.T) {
s := NewTransition("connect", States("disconnected"), "connected")
if s == nil {
t.Errorf("Failed creating new transition")
}
}
func TestTransitionExecution(t *testing.T) {
s := setupTransition()
m := setupModel("closed")
assert.Nil(t, s.Run(m))
state := m.InspectState()
if state != "open" {
t.Errorf("Failed to transition state: %s", state)
}
}
func TestTransitionWildcard(t *testing.T) {
tr := NewTransition("open", States("*"), "opened")
assert.NotNil(t, tr)
m := setupModel("closed")
assert.Nil(t, tr.Run(m))
assert.Equal(t, "opened", string(m.InspectState()))
}
func TestTransitionSubscribe(t *testing.T) {
c := setupSubscriber()
s := setupTransition()
s.Subscribe(c)
m := setupModel("closed")
assert.Nil(t, s.Run(m))
exitEvent := <-*c.(*EventChannel)
enterEvent := <-*c.(*EventChannel)
if exitEvent.On != EXITSTATEEVENT {
t.Errorf("Invalid exit event")
}
if enterEvent.On != ENTERSTATEEVENT {
t.Errorf("Invalid enter event")
}
}
func TestTransitionMultipleSourceStates(t *testing.T) {
tr := NewTransition("open", States("closed", "disconnected"), "opened")
assert.NotNil(t, tr)
mc := setupModel("closed")
assert.Nil(t, tr.Run(mc))
assert.Equal(t, "opened", string(mc.InspectState()))
md := setupModel("disconnected")
assert.Nil(t, tr.Run(md))
assert.Equal(t, "opened", string(md.InspectState()))
}