You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.9 KiB
61 lines
1.9 KiB
package cbortest
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/hex"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestMarshal(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
v any
|
|
want string
|
|
}{
|
|
{uint64(0), "00"}, {uint(24), "1818"}, {256, "190100"}, {int64(-1), "20"}, {-500, "3901f3"},
|
|
{uint64(1) << 32, "1b0000000100000000"}, {"a", "6161"}, {[]byte{1}, "4101"},
|
|
{true, "f5"}, {false, "f4"}, {nil, "f6"}, {Raw{0xf9, 0x7e, 0x00}, "f97e00"},
|
|
{[]any{uint64(1), "x"}, "82016178"}, {map[uint64]any{10: uint64(1), 2: uint64(0)}, "a202000a01"},
|
|
{Pairs{uint64(1), uint64(0), "k", nil}, "a2010061" + "6bf6"},
|
|
{uint64(65536), "1a00010000"},
|
|
} {
|
|
b, err := Marshal(tc.v)
|
|
if err != nil || hex.EncodeToString(b) != tc.want {
|
|
t.Errorf("%#v: %x %v, want %s", tc.v, b, err, tc.want)
|
|
}
|
|
}
|
|
for _, v := range []any{Pairs{uint64(1)}, 1.5, []any{struct{}{}}, map[uint64]any{0: 1.5}, Pairs{uint64(0), 1.5}} {
|
|
if _, err := Marshal(v); err == nil {
|
|
t.Errorf("%#v encoded", v)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestUnmarshal(t *testing.T) {
|
|
v, err := Unmarshal([]byte{0xa2, 0x00, 0x82, 0x40, 0x60, 0x0a, 0x1b, 0, 0, 0, 1, 0, 0, 0, 0})
|
|
want := map[uint64]any{0: []any{[]byte{}, ""}, 10: uint64(1) << 32}
|
|
if err != nil || !reflect.DeepEqual(v, want) {
|
|
t.Fatalf("%#v %v", v, err)
|
|
}
|
|
for _, h := range []string{
|
|
"", "20", "c101", "f5", "f6", "1c", "9f00ff", "1817", "190017", "1a0000ffff", "1b00000000ffffffff",
|
|
"a1616100", "a201000001", "a200000001", "61ff", "0100", "1901", "4201", "8201", "a100",
|
|
strings.Repeat("81", MaxDepth+1) + "00",
|
|
} {
|
|
b, _ := hex.DecodeString(h)
|
|
if _, err := Unmarshal(b); err == nil {
|
|
t.Errorf("%s accepted", h)
|
|
}
|
|
}
|
|
if _, err := UnmarshalMap([]byte{0x80}); err == nil {
|
|
t.Error("an array read as a map")
|
|
}
|
|
if _, err := UnmarshalMap([]byte{0xff}); err == nil {
|
|
t.Error("garbage read as a map")
|
|
}
|
|
if m, err := UnmarshalMap([]byte{0xa1, 0x00, 0x41, 0x07}); err != nil || !bytes.Equal(m[0].([]byte), []byte{7}) {
|
|
t.Errorf("%v %v", m, err)
|
|
}
|
|
}
|