journal/attr_key_test.go

86 lines
2.2 KiB
Go
Raw Normal View History

2024-02-18 10:31:14 +00:00
package journal
import (
"errors"
"strings"
"testing"
)
func TestAttrKeyValid(t *testing.T) {
for _, testcase := range []struct {
name, key string
valid bool
reason InvalidAttrKeyReason
}{
{"short", "MESSAGE", true, -1},
{"underscore", "MESSAGE_", true, -1},
{"numeric", "12345", true, -1},
{"long", strings.Repeat("Z", 255), true, -1},
{"too_long", strings.Repeat("Z", 256), false, AttrKeyLength},
{"empty", "", false, AttrKeyEmpty},
{"trusted", "_MESSAGE", false, AttrKeyTrusted},
{"punctuation", "MESSAGE-2", false, AttrKeyInvalidChars},
{"lowercase", "message", false, AttrKeyInvalidChars},
{"space", "MESS AGE", false, AttrKeyInvalidChars},
{"newline", "MESS\nAGE", false, AttrKeyInvalidChars},
{"NUL", "\x00", false, AttrKeyInvalidChars},
} {
if testcase.valid {
t.Run("valid/"+testcase.name, func(t *testing.T) {
if err := AttrKeyValid(testcase.key); err != nil {
t.Errorf("unexpected error: %v", err)
}
})
} else {
t.Run("invalid/"+testcase.name, func(t *testing.T) {
err := AttrKeyValid(testcase.key)
var iak *InvalidAttrKey
switch {
case err == nil:
t.Error("unexpectedly succeeded")
case errors.As(err, &iak):
if iak.Key != testcase.key {
t.Errorf("InvalidAttrKey error has wrong key %q", iak.Key)
}
if iak.Reason != testcase.reason {
t.Errorf("InvalidAttrKey error has wrong reason %v", iak.Reason)
}
default:
t.Errorf("unexpected error type %T: %v", err, err)
}
})
}
}
}
func TestNewAttrKeyValid(t *testing.T) {
k, err := NewAttrKey("MESSAGE")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if k.key != "MESSAGE" {
t.Errorf(".key does not match expected: %q", k.key)
}
}
func TestNewAttrKeyInvalid(t *testing.T) {
k, err := NewAttrKey("_MESSAGE")
var iak *InvalidAttrKey
switch {
case err == nil:
t.Error("unexpectedly succeeded")
case errors.As(err, &iak):
if iak.Key != "_MESSAGE" {
t.Errorf("InvalidAttrKey error has wrong key %q", iak.Key)
}
if iak.Reason != AttrKeyTrusted {
t.Errorf("InvalidAttrKey error has wrong reason %v", iak.Reason)
}
default:
t.Errorf("unexpected error type %T: %v", err, err)
}
if k.key != "" {
t.Errorf(".key not empty: %q", k.key)
}
}