Improve encoding tests
This commit is contained in:
parent
4642a135db
commit
db98a34e23
2 changed files with 16 additions and 16 deletions
|
|
@ -95,11 +95,11 @@ func encode(v interface{}) (string, error) {
|
|||
var s string
|
||||
switch val := v.(type) {
|
||||
case time.Time:
|
||||
var b []byte
|
||||
if !val.IsZero() {
|
||||
b, _ = val.Round(time.Second).Local().MarshalText()
|
||||
if val.IsZero() {
|
||||
s = "null"
|
||||
} else {
|
||||
s = fmt.Sprintf(`"%s"`, val.Format(time.RFC3339))
|
||||
}
|
||||
s = fmt.Sprintf(`"%s"`, string(b))
|
||||
case time.Duration:
|
||||
// must be before stringer to convert to seconds instead of string
|
||||
s = fmt.Sprintf("%d", int64(val.Seconds()))
|
||||
|
|
@ -112,6 +112,8 @@ func encode(v interface{}) (string, error) {
|
|||
default:
|
||||
if b, err := json.Marshal(v); err == nil {
|
||||
s = string(b)
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
|
|
|
|||
|
|
@ -2,14 +2,18 @@ package server
|
|||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestEncode(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
tc := []struct {
|
||||
in, out interface{}
|
||||
in interface{}
|
||||
out string
|
||||
}{
|
||||
{int64(1), "1"},
|
||||
{math.NaN(), "null"},
|
||||
|
|
@ -17,19 +21,13 @@ func TestEncode(t *testing.T) {
|
|||
{"1.2345", "\"1.2345\""},
|
||||
{time.Hour, "3600"},
|
||||
{"minpv", "\"minpv\""},
|
||||
{time.Time{}, "null"},
|
||||
{now, "\"" + now.Format(time.RFC3339) + "\""},
|
||||
}
|
||||
|
||||
for _, tc := range tc {
|
||||
t.Logf("%+v", tc)
|
||||
out, err := encode(tc.in)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if out != tc.out {
|
||||
t.Errorf("expected %v (string), got %v (%s)",
|
||||
tc.out, out, reflect.TypeOf(out).Kind(),
|
||||
)
|
||||
}
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.out, out)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue