machine/transition_test.go

75 lines
1.8 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
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 setupTransition() Transitioner {
t := NewTransition("open", States("closed"), "open")
2024-04-04 20:08:50 +00:00
if t == nil {
log.Fatal("Failed creating new transition")
}
return t
2024-04-04 17:33:22 +00:00
}
func setupSubscriber() Subscriber {
2024-04-04 20:08:50 +00:00
c := make(EventChannel, 2)
return &c
2024-04-04 17:33:22 +00:00
}
func TestNewTransition(t *testing.T) {
s := NewTransition("connect", States("disconnected"), "connected")
2024-04-04 20:08:50 +00:00
if s == nil {
t.Errorf("Failed creating new transition")
}
2024-04-04 17:33:22 +00:00
}
func TestTransitionExecution(t *testing.T) {
2024-04-04 20:08:50 +00:00
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)
}
2024-04-04 17:33:22 +00:00
}
2024-05-17 00:28:49 +00:00
func TestTransitionWildcard(t *testing.T) {
tr := NewTransition("open", States("*"), "opened")
2024-05-17 00:28:49 +00:00
assert.NotNil(t, tr)
m := setupModel("closed")
assert.Nil(t, tr.Run(m))
assert.Equal(t, "opened", string(m.InspectState()))
}
2024-04-04 17:33:22 +00:00
func TestTransitionSubscribe(t *testing.T) {
2024-04-04 20:08:50 +00:00
c := setupSubscriber()
s := setupTransition()
s.Subscribe(c)
m := setupModel("closed")
assert.Nil(t, s.Run(m))
exitEvent := <-*c.(*EventChannel)
enterEvent := <-*c.(*EventChannel)
2024-05-07 05:59:18 +00:00
if exitEvent.On != EXITSTATEEVENT {
2024-04-04 20:08:50 +00:00
t.Errorf("Invalid exit event")
}
2024-05-07 05:59:18 +00:00
if enterEvent.On != ENTERSTATEEVENT {
2024-04-04 20:08:50 +00:00
t.Errorf("Invalid enter event")
}
2024-04-04 17:33:22 +00:00
}
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()))
}