my-log/models/log_test.go

111 lines
2.4 KiB
Go
Raw Permalink Normal View History

2024-02-03 18:52:12 -06:00
package models
import (
"encoding"
"testing"
"github.com/nalgeon/be"
2024-02-03 18:52:12 -06:00
)
var _ encoding.TextUnmarshaler = new(Log)
const first = "@begin January 01, 2020 at 01:02:03AM -0000 - This is simple @end\n"
const second = `@begin January 01, 2020 at 01:02:05AM -0000 - We have one thing here
@foo bar @end
`
const third = `@begin January 01, 2020 at 01:02:07AM -0000 - We have two things here
@num 42
@newline true
@end
`
const fourth = `@begin 2020-01-01T01:02:09Z - ISO-8601 date
@end
`
const skip = "@ignoreme true\n"
const fifth = `@begin 2020-01-01T01:02:11+00:00 - ISO-8601 other date
@with-timezone yes @end
`
const badEntry = "@begin bad date no title @end\n"
const all = first + second + third + fourth + skip + fifth
func TestLogUnmarshalBig(t *testing.T) {
l := &Log{Name: "test-log"}
err := l.UnmarshalText([]byte(all))
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 5)
2024-02-03 18:52:12 -06:00
var e Entry
var f bool
if e, f = findEntry(t, l, "This is simple", true); !f {
return
}
be.Equal(t, len(e.Fields), 0)
2024-02-03 18:52:12 -06:00
for _, e := range l.Entries {
findMeta(t, e, "ignoreme", true, false)
}
}
func TestLogUnmarshalIgnoreGarbage(t *testing.T) {
l := &Log{Name: "test-log"}
in := "ignore this\n" + second + "some crap also skip -> " + third + skip
err := l.UnmarshalText([]byte(in))
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 1)
2024-02-03 18:52:12 -06:00
en := l.Entries[0]
be.Equal(t, en.Title, "We have one thing here")
be.Equal(t, len(en.Fields), 1)
be.Equal(t, en.Fields[0].Key, "foo")
be.Equal(t, en.Fields[0].Value, "bar")
2024-02-03 18:52:12 -06:00
}
func TestLogUnmarshalEmpty(t *testing.T) {
l := &Log{Name: "test-log"}
err := l.UnmarshalText([]byte{})
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 0)
2024-02-03 18:52:12 -06:00
}
func TestLogUnmarshalBad(t *testing.T) {
l := &Log{Name: "test-log"}
err := l.UnmarshalText([]byte(badEntry))
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 0)
2024-02-03 18:52:12 -06:00
}
func findEntry(t *testing.T, log *Log, title string, shouldFind bool) (Entry, bool) {
var ret Entry
found := false
for _, e := range log.Entries {
if e.Title == title {
ret = e
found = true
}
}
if shouldFind {
be.True(t, found)
2024-02-03 18:52:12 -06:00
} else {
be.True(t, !found)
2024-02-03 18:52:12 -06:00
}
return ret, found
}
func findMeta(t *testing.T, entry Entry, key string, value any, shouldFind bool) (Meta, bool) {
var ret Meta
found := false
for _, m := range entry.Fields {
if m.Key == key && m.Value == value {
ret = m
found = true
}
}
if shouldFind {
be.True(t, found)
2024-02-03 18:52:12 -06:00
} else {
be.True(t, !found)
2024-02-03 18:52:12 -06:00
}
return ret, found
}