schema/notify: add tests for Message parsing

This commit is contained in:
Paul Stemmet 2022-12-10 17:01:44 +00:00
parent c277b1e813
commit 83cca8cc6f
Signed by: Paul Stemmet
GPG Key ID: EDEA539F594E7E75
1 changed files with 127 additions and 0 deletions

View File

@ -0,0 +1,127 @@
package notify_test
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
n "git.st8l.com/luxolus/kdnotify/schema/notify"
"git.st8l.com/luxolus/kdnotify/schema/notify/prio"
"git.st8l.com/luxolus/kdnotify/schema/notify/state"
"git.st8l.com/luxolus/kdnotify/schema/notify/ty"
)
func Test_ParseMessage(t *testing.T) {
t.Parallel()
cases := []struct {
Name string
Message string
Expected *n.Message
ShouldError bool
HandlerFunc func(t *testing.T, expected, actual *n.Message) bool
}{
{
Name: "Empty",
Message: "",
ShouldError: true,
},
{
Name: "Simple",
Message: `INSTANCE foo_instance MASTER`,
Expected: &n.Message{
Type: ty.INSTANCE,
State: state.MASTER,
Instance: "foo_instance",
},
},
{
Name: "WithPriority",
Message: `INSTANCE foo_instance BACKUP 100`,
Expected: &n.Message{
Type: ty.INSTANCE,
State: state.BACKUP,
Instance: "foo_instance",
Priority: prio.Priority(100),
},
},
{
Name: "Trailing",
Message: `INSTANCE foo_instance MASTER 255 othe!r ran@##@dom ^garbage%`,
Expected: &n.Message{
Type: ty.INSTANCE,
State: state.MASTER,
Instance: "foo_instance",
Priority: prio.MASTER,
},
},
{
Name: "DirtyInstance",
Message: `INSTANCE "'"foo_instance"'" MASTER`,
Expected: &n.Message{
Type: ty.INSTANCE,
State: state.MASTER,
Instance: "foo_instance",
},
},
{
Name: "Group",
Message: `GROUP "''baz_group''" STOP`,
Expected: &n.Message{
Type: ty.GROUP,
State: state.STOP,
Instance: "baz_group",
},
},
}
for i, test := range cases {
test := test // Avoid closure capture by ref
tname := fmt.Sprintf("%s@%d:%d", test.Name, i+1, len(cases))
t.Run(tname, func(t *testing.T) {
t.Parallel()
if test.HandlerFunc == nil {
test.HandlerFunc = Noop[string]
if test.Expected != nil {
test.HandlerFunc = ExpectMessage
if test.ShouldError {
test.HandlerFunc = ExpectNotEqual[*n.Message]
}
}
}
actual, err := n.ParseMessage(test.Message)
if test.ShouldError && err != nil {
return
} else if assert.NoError(t, err) {
test.HandlerFunc(t, test.Expected, &actual)
}
})
}
}
func ExpectMessage(t *testing.T, expected, actual *n.Message) bool {
return assert.Equal(t, expected, actual)
}
func ExpectVrrp(t *testing.T, expected, actual *n.Message) bool {
e, err := n.NewVrrp(*expected)
require.NoError(t, err)
a, err := n.NewVrrp(*actual)
assert.NoError(t, err)
return assert.Equal(t, e, a)
}
func ExpectNotEqual[T any](t *testing.T, expected, actual T) bool {
return assert.NotEqual(t, expected, actual)
}
func Noop[T any](_ *testing.T, _, _ *n.Message) bool {
return true
}