package tools import ( "encoding/json" "testing" "time" "github.com/stretchr/testify/assert" ) func TestParse(t *testing.T) { when := time.Now() now := when.Local().Truncate(time.Second) tests := []struct { name string in string out any }{ {"int", "42", 42}, {"float", "42.13", 42.13}, {"string", "hello", "hello"}, {"true", "true", true}, {"false", "false", false}, {"nil", "nil", nil}, {"time", when.Format(time.RFC3339), when}, {"now", "now", now}, {"DateFormat", now.Format(DateFormat), now}, {"json-obj", `{"foo":"bar","baz":"quux"}`, json.RawMessage(`{"foo":"bar","baz":"quux"}`)}, {"json-arr", `["foo",42,"bar", null,"quux", true]`, json.RawMessage(`["foo",42,"bar", null,"quux", true]`)}, {"empty", "", ""}, {"space-value", " ", ""}, {"space-nl-value", " \n ", ""}, {"null-value", "null", nil}, {"tilda-value", "~", nil}, {"none-value", "none", nil}, {"nil-value", "nil", nil}, {"yes-value", "yes", true}, {"on-value", "on", true}, {"no-value", "no", false}, {"off-value", "off", false}, } for _, tt := range tests { t.Run(tt.name, getParseTestRunner(tt.in, tt.out)) } } func getParseTestRunner(in string, exp any) func(*testing.T) { return func(t *testing.T) { out := ParseString(in) if expT, ok := exp.(time.Time); ok { ti, gotTime := out.(time.Time) if assert.True(t, gotTime, "Should have gotten a time.Time, but didn't") { assert.WithinRange(t, expT, ti.Add(-2*time.Second), ti.Add(2*time.Second)) } } else { assert.Equal(t, exp, out) } out = ParseBytes([]byte(in)) if expT, ok := exp.(time.Time); ok { ti, gotTime := out.(time.Time) if assert.True(t, gotTime, "Should have gotten a time.Time, but didn't") { assert.WithinRange(t, expT, ti.Add(-2*time.Second), ti.Add(2*time.Second)) } } else { assert.Equal(t, exp, out) } } }