my-log/models/meta_test.go

55 lines
1.6 KiB
Go
Raw Normal View History

2024-01-26 20:00:03 -06:00
package models
import (
"encoding"
"encoding/json"
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// Type assertions
var _ encoding.TextMarshaler = Meta{}
func TestMeta(t *testing.T) {
when := time.Now()
tests := []struct {
name string
key string
value any
out string
err error
}{
{"int", "num", 42, "@num 42", nil},
{"float", "num", 42.13, "@num 42.13", nil},
{"string", "word", "hello", "@word hello", nil},
{"json number", "num", json.Number("42.13"), "@num 42.13", nil},
{"true", "b", true, "@b true", nil},
{"false", "b", false, "@b false", nil},
{"nil", "n", nil, "", nil},
{"time", "when", when, "@when " + when.Format(time.RFC3339), nil},
{"rune", "char", '@', "@char @", nil},
{"bytes", "byteme", []byte("yo"), "@byteme yo", nil},
{"byte", "byteme", byte(67), "@byteme C", nil},
{"json-obj", "obj", json.RawMessage(`{"foo":"bar","baz":"quux"}`), `@obj {"foo":"bar","baz":"quux"}`, nil},
{"json-arr", "arr", json.RawMessage(`["foo",42,"bar", null,"quux", true]`), `@arr ["foo",42,"bar", null,"quux", true]`, nil},
{"chan", "nope", make(chan bool), "", errors.New("Unknown type chan bool")},
{"whitespace", "no space", "hi", "", errors.New("whitespace is now allowed in key: no space")},
}
for _, tt := range tests {
t.Run(tt.name, getMetaTestRunner(tt.key, tt.value, tt.out, tt.err))
}
}
func getMetaTestRunner(key string, value any, out string, err error) func(*testing.T) {
return func(t *testing.T) {
st := Meta{key, value}
o, e := st.MarshalText()
assert.Equal(t, out, string(o))
assert.Equal(t, err, e)
}
}