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 }