1
0
mirror of https://github.com/json-iterator/go.git synced 2025-04-20 11:28:49 +02:00

consolidate more tests

This commit is contained in:
Tao Wen 2018-02-14 08:28:17 +08:00
parent 8fa357ab7b
commit e3bc511e5a
9 changed files with 99 additions and 258 deletions

View File

@ -13,3 +13,16 @@ func Test_wrap_map(t *testing.T) {
any = jsoniter.Wrap(map[string]string{"Field1": "hello"}) any = jsoniter.Wrap(map[string]string{"Field1": "hello"})
should.Equal(1, any.Size()) should.Equal(1, any.Size())
} }
func Test_map_wrapper_any_get_all(t *testing.T) {
should := require.New(t)
any := jsoniter.Wrap(map[string][]int{"Field1": {1, 2}})
should.Equal(`{"Field1":1}`, any.Get('*', 0).ToString())
should.Contains(any.Keys(), "Field1")
// map write to
stream := jsoniter.NewStream(jsoniter.ConfigDefault, nil, 0)
any.WriteTo(stream)
// TODO cannot pass
//should.Equal(string(stream.buf), "")
}

View File

@ -1,10 +1,11 @@
package jsoniter package test
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io/ioutil"
"os" "os"
"testing" "testing"
"github.com/json-iterator/go"
) )
//func Test_large_file(t *testing.T) { //func Test_large_file(t *testing.T) {
@ -127,9 +128,9 @@ func Benchmark_jsoniter_large_file(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
file, _ := os.Open("/tmp/large-file.json") file, _ := os.Open("/tmp/large-file.json")
iter := Parse(ConfigDefault, file, 4096) iter := jsoniter.Parse(jsoniter.ConfigDefault, file, 4096)
count := 0 count := 0
iter.ReadArrayCB(func(iter *Iterator) bool { iter.ReadArrayCB(func(iter *jsoniter.Iterator) bool {
// Skip() is strict by default, use --tags jsoniter-sloppy to skip without validation // Skip() is strict by default, use --tags jsoniter-sloppy to skip without validation
iter.Skip() iter.Skip()
count++ count++

View File

@ -1,65 +0,0 @@
package jsoniter
import (
"bytes"
"github.com/stretchr/testify/require"
"io"
"testing"
)
func Test_read_by_one(t *testing.T) {
iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 1)
b := iter.readByte()
if iter.Error != nil {
t.Fatal(iter.Error)
}
if b != 'a' {
t.Fatal(b)
}
iter.unreadByte()
if iter.Error != nil {
t.Fatal(iter.Error)
}
b = iter.readByte()
if iter.Error != nil {
t.Fatal(iter.Error)
}
if b != 'a' {
t.Fatal(b)
}
}
func Test_read_by_two(t *testing.T) {
should := require.New(t)
iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 2)
b := iter.readByte()
should.Nil(iter.Error)
should.Equal(byte('a'), b)
b = iter.readByte()
should.Nil(iter.Error)
should.Equal(byte('b'), b)
iter.unreadByte()
should.Nil(iter.Error)
iter.unreadByte()
should.Nil(iter.Error)
b = iter.readByte()
should.Nil(iter.Error)
should.Equal(byte('a'), b)
}
func Test_read_until_eof(t *testing.T) {
iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 2)
iter.readByte()
iter.readByte()
b := iter.readByte()
if iter.Error != nil {
t.Fatal(iter.Error)
}
if b != 'c' {
t.Fatal(b)
}
iter.readByte()
if iter.Error != io.EOF {
t.Fatal(iter.Error)
}
}

View File

@ -1,160 +0,0 @@
package jsoniter
import (
"encoding/json"
"math/big"
"testing"
"github.com/stretchr/testify/require"
"strings"
)
func Test_read_map(t *testing.T) {
should := require.New(t)
iter := ParseString(ConfigDefault, `{"hello": "world"}`)
m := map[string]string{"1": "2"}
iter.ReadVal(&m)
copy(iter.buf, []byte{0, 0, 0, 0, 0, 0})
should.Equal(map[string]string{"1": "2", "hello": "world"}, m)
}
func Test_read_map_of_interface(t *testing.T) {
should := require.New(t)
iter := ParseString(ConfigDefault, `{"hello": "world"}`)
m := map[string]interface{}{"1": "2"}
iter.ReadVal(&m)
should.Equal(map[string]interface{}{"1": "2", "hello": "world"}, m)
iter = ParseString(ConfigDefault, `{"hello": "world"}`)
should.Equal(map[string]interface{}{"hello": "world"}, iter.Read())
}
func Test_map_wrapper_any_get_all(t *testing.T) {
should := require.New(t)
any := Wrap(map[string][]int{"Field1": {1, 2}})
should.Equal(`{"Field1":1}`, any.Get('*', 0).ToString())
should.Contains(any.Keys(), "Field1")
// map write to
stream := NewStream(ConfigDefault, nil, 0)
any.WriteTo(stream)
// TODO cannot pass
//should.Equal(string(stream.buf), "")
}
func Test_write_val_map(t *testing.T) {
should := require.New(t)
val := map[string]string{"1": "2"}
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"1":"2"}`, str)
}
func Test_slice_of_map(t *testing.T) {
should := require.New(t)
val := []map[string]string{{"1": "2"}}
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`[{"1":"2"}]`, str)
val = []map[string]string{}
should.Nil(UnmarshalFromString(str, &val))
should.Equal("2", val[0]["1"])
}
func Test_encode_int_key_map(t *testing.T) {
should := require.New(t)
val := map[int]string{1: "2"}
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"1":"2"}`, str)
}
func Test_decode_int_key_map(t *testing.T) {
should := require.New(t)
var val map[int]string
should.Nil(UnmarshalFromString(`{"1":"2"}`, &val))
should.Equal(map[int]string{1: "2"}, val)
}
func Test_encode_TextMarshaler_key_map(t *testing.T) {
should := require.New(t)
f, _, _ := big.ParseFloat("1", 10, 64, big.ToZero)
val := map[*big.Float]string{f: "2"}
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"1":"2"}`, str)
}
func Test_decode_TextMarshaler_key_map(t *testing.T) {
should := require.New(t)
var val map[*big.Float]string
should.Nil(UnmarshalFromString(`{"1":"2"}`, &val))
str, err := MarshalToString(val)
should.Nil(err)
should.Equal(`{"1":"2"}`, str)
}
func Test_map_key_with_escaped_char(t *testing.T) {
type Ttest struct {
Map map[string]string
}
var jsonBytes = []byte(`
{
"Map":{
"k\"ey": "val"
}
}`)
should := require.New(t)
{
var obj Ttest
should.Nil(json.Unmarshal(jsonBytes, &obj))
should.Equal(map[string]string{"k\"ey": "val"}, obj.Map)
}
{
var obj Ttest
should.Nil(Unmarshal(jsonBytes, &obj))
should.Equal(map[string]string{"k\"ey": "val"}, obj.Map)
}
}
func Test_encode_map_with_sorted_keys(t *testing.T) {
should := require.New(t)
m := map[string]interface{}{
"3": 3,
"1": 1,
"2": 2,
}
bytes, err := json.Marshal(m)
should.Nil(err)
output, err := ConfigCompatibleWithStandardLibrary.MarshalToString(m)
should.Nil(err)
should.Equal(string(bytes), output)
}
func Test_encode_map_uint_keys(t *testing.T) {
should := require.New(t)
m := map[uint64]interface{}{
uint64(1): "a",
uint64(2): "a",
uint64(4): "a",
}
bytes, err := json.Marshal(m)
should.Nil(err)
output, err := ConfigCompatibleWithStandardLibrary.MarshalToString(m)
should.Nil(err)
should.Equal(string(bytes), output)
}
func Test_read_map_with_reader(t *testing.T) {
should := require.New(t)
input := `{"branch":"beta","change_log":"add the rows{10}","channel":"fros","create_time":"2017-06-13 16:39:08","firmware_list":"","md5":"80dee2bf7305bcf179582088e29fd7b9","note":{"CoreServices":{"md5":"d26975c0a8c7369f70ed699f2855cc2e","package_name":"CoreServices","version_code":"76","version_name":"1.0.76"},"FrDaemon":{"md5":"6b1f0626673200bc2157422cd2103f5d","package_name":"FrDaemon","version_code":"390","version_name":"1.0.390"},"FrGallery":{"md5":"90d767f0f31bcd3c1d27281ec979ba65","package_name":"FrGallery","version_code":"349","version_name":"1.0.349"},"FrLocal":{"md5":"f15a215b2c070a80a01f07bde4f219eb","package_name":"FrLocal","version_code":"791","version_name":"1.0.791"}},"pack_region_urls":{"CN":"https://s3.cn-north-1.amazonaws.com.cn/xxx-os/ttt_xxx_android_1.5.3.344.393.zip","default":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip","local":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip"},"pack_version":"1.5.3.344.393","pack_version_code":393,"region":"all","release_flag":0,"revision":62,"size":38966875,"status":3}`
reader := strings.NewReader(input)
decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(reader)
m1 := map[string]interface{}{}
should.Nil(decoder.Decode(&m1))
m2 := map[string]interface{}{}
should.Nil(json.Unmarshal([]byte(input), &m2))
should.Equal(m2, m1)
should.Equal("1.0.76", m1["note"].(map[string]interface{})["CoreServices"].(map[string]interface{})["version_name"])
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,33 @@
package misc_tests
import (
"encoding/json"
"math/big"
"testing"
"github.com/stretchr/testify/require"
"strings"
"github.com/json-iterator/go"
)
func Test_decode_TextMarshaler_key_map(t *testing.T) {
should := require.New(t)
var val map[*big.Float]string
should.Nil(jsoniter.UnmarshalFromString(`{"1":"2"}`, &val))
str, err := jsoniter.MarshalToString(val)
should.Nil(err)
should.Equal(`{"1":"2"}`, str)
}
func Test_read_map_with_reader(t *testing.T) {
should := require.New(t)
input := `{"branch":"beta","change_log":"add the rows{10}","channel":"fros","create_time":"2017-06-13 16:39:08","firmware_list":"","md5":"80dee2bf7305bcf179582088e29fd7b9","note":{"CoreServices":{"md5":"d26975c0a8c7369f70ed699f2855cc2e","package_name":"CoreServices","version_code":"76","version_name":"1.0.76"},"FrDaemon":{"md5":"6b1f0626673200bc2157422cd2103f5d","package_name":"FrDaemon","version_code":"390","version_name":"1.0.390"},"FrGallery":{"md5":"90d767f0f31bcd3c1d27281ec979ba65","package_name":"FrGallery","version_code":"349","version_name":"1.0.349"},"FrLocal":{"md5":"f15a215b2c070a80a01f07bde4f219eb","package_name":"FrLocal","version_code":"791","version_name":"1.0.791"}},"pack_region_urls":{"CN":"https://s3.cn-north-1.amazonaws.com.cn/xxx-os/ttt_xxx_android_1.5.3.344.393.zip","default":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip","local":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip"},"pack_version":"1.5.3.344.393","pack_version_code":393,"region":"all","release_flag":0,"revision":62,"size":38966875,"status":3}`
reader := strings.NewReader(input)
decoder := jsoniter.ConfigCompatibleWithStandardLibrary.NewDecoder(reader)
m1 := map[string]interface{}{}
should.Nil(decoder.Decode(&m1))
m2 := map[string]interface{}{}
should.Nil(json.Unmarshal([]byte(input), &m2))
should.Equal(m2, m1)
should.Equal("1.0.76", m1["note"].(map[string]interface{})["CoreServices"].(map[string]interface{})["version_name"])
}

View File

@ -1,4 +1,4 @@
package jsoniter package test
import ( import (
"bytes" "bytes"
@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"io" "io"
"testing" "testing"
"github.com/json-iterator/go"
) )
func Test_missing_object_end(t *testing.T) { func Test_missing_object_end(t *testing.T) {
@ -16,18 +17,18 @@ func Test_missing_object_end(t *testing.T) {
Tags map[string]interface{} `json:"tags"` Tags map[string]interface{} `json:"tags"`
} }
obj := TestObject{} obj := TestObject{}
should.NotNil(UnmarshalFromString(`{"metric": "sys.777","tags": {"a":"123"}`, &obj)) should.NotNil(jsoniter.UnmarshalFromString(`{"metric": "sys.777","tags": {"a":"123"}`, &obj))
} }
func Test_missing_array_end(t *testing.T) { func Test_missing_array_end(t *testing.T) {
should := require.New(t) should := require.New(t)
should.NotNil(UnmarshalFromString(`[1,2,3`, &[]int{})) should.NotNil(jsoniter.UnmarshalFromString(`[1,2,3`, &[]int{}))
} }
func Test_invalid_any(t *testing.T) { func Test_invalid_any(t *testing.T) {
should := require.New(t) should := require.New(t)
any := Get([]byte("[]")) any := jsoniter.Get([]byte("[]"))
should.Equal(InvalidValue, any.Get(0.3).ValueType()) should.Equal(jsoniter.InvalidValue, any.Get(0.3).ValueType())
// is nil correct ? // is nil correct ?
should.Equal(nil, any.Get(0.3).GetInterface()) should.Equal(nil, any.Get(0.3).GetInterface())
@ -43,7 +44,7 @@ func Test_invalid_any(t *testing.T) {
should.Equal(float64(0), any.ToFloat64()) should.Equal(float64(0), any.ToFloat64())
should.Equal("", any.ToString()) should.Equal("", any.ToString())
should.Equal(InvalidValue, any.Get(0.1).Get(1).ValueType()) should.Equal(jsoniter.InvalidValue, any.Get(0.1).Get(1).ValueType())
} }
func Test_invalid_struct_input(t *testing.T) { func Test_invalid_struct_input(t *testing.T) {
@ -51,7 +52,7 @@ func Test_invalid_struct_input(t *testing.T) {
type TestObject struct{} type TestObject struct{}
input := []byte{54, 141, 30} input := []byte{54, 141, 30}
obj := TestObject{} obj := TestObject{}
should.NotNil(Unmarshal(input, &obj)) should.NotNil(jsoniter.Unmarshal(input, &obj))
} }
func Test_invalid_slice_input(t *testing.T) { func Test_invalid_slice_input(t *testing.T) {
@ -59,7 +60,7 @@ func Test_invalid_slice_input(t *testing.T) {
type TestObject struct{} type TestObject struct{}
input := []byte{93} input := []byte{93}
obj := []string{} obj := []string{}
should.NotNil(Unmarshal(input, &obj)) should.NotNil(jsoniter.Unmarshal(input, &obj))
} }
func Test_invalid_array_input(t *testing.T) { func Test_invalid_array_input(t *testing.T) {
@ -67,7 +68,7 @@ func Test_invalid_array_input(t *testing.T) {
type TestObject struct{} type TestObject struct{}
input := []byte{93} input := []byte{93}
obj := [0]string{} obj := [0]string{}
should.NotNil(Unmarshal(input, &obj)) should.NotNil(jsoniter.Unmarshal(input, &obj))
} }
func Test_invalid_float(t *testing.T) { func Test_invalid_float(t *testing.T) {
@ -83,17 +84,17 @@ func Test_invalid_float(t *testing.T) {
for _, input := range inputs { for _, input := range inputs {
t.Run(input, func(t *testing.T) { t.Run(input, func(t *testing.T) {
should := require.New(t) should := require.New(t)
iter := ParseString(ConfigDefault, input+",") iter := jsoniter.ParseString(jsoniter.ConfigDefault, input+",")
iter.Skip() iter.Skip()
should.NotEqual(io.EOF, iter.Error) should.NotEqual(io.EOF, iter.Error)
should.NotNil(iter.Error) should.NotNil(iter.Error)
v := float64(0) v := float64(0)
should.NotNil(json.Unmarshal([]byte(input), &v)) should.NotNil(json.Unmarshal([]byte(input), &v))
iter = ParseString(ConfigDefault, input+",") iter = jsoniter.ParseString(jsoniter.ConfigDefault, input+",")
iter.ReadFloat64() iter.ReadFloat64()
should.NotEqual(io.EOF, iter.Error) should.NotEqual(io.EOF, iter.Error)
should.NotNil(iter.Error) should.NotNil(iter.Error)
iter = ParseString(ConfigDefault, input+",") iter = jsoniter.ParseString(jsoniter.ConfigDefault, input+",")
iter.ReadFloat32() iter.ReadFloat32()
should.NotEqual(io.EOF, iter.Error) should.NotEqual(io.EOF, iter.Error)
should.NotNil(iter.Error) should.NotNil(iter.Error)
@ -121,10 +122,10 @@ func Test_invalid_number(t *testing.T) {
Number int `json:"number"` Number int `json:"number"`
} }
obj := Message{} obj := Message{}
decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(bytes.NewBufferString(`{"number":"5"}`)) decoder := jsoniter.ConfigCompatibleWithStandardLibrary.NewDecoder(bytes.NewBufferString(`{"number":"5"}`))
err := decoder.Decode(&obj) err := decoder.Decode(&obj)
invalidStr := err.Error() invalidStr := err.Error()
result, err := ConfigCompatibleWithStandardLibrary.Marshal(invalidStr) result, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(invalidStr)
should := require.New(t) should := require.New(t)
should.Nil(err) should.Nil(err)
result2, err := json.Marshal(invalidStr) result2, err := json.Marshal(invalidStr)
@ -134,8 +135,8 @@ func Test_invalid_number(t *testing.T) {
func Test_valid(t *testing.T) { func Test_valid(t *testing.T) {
should := require.New(t) should := require.New(t)
should.True(Valid([]byte(`{}`))) should.True(jsoniter.Valid([]byte(`{}`)))
should.False(Valid([]byte(`{`))) should.False(jsoniter.Valid([]byte(`{`)))
} }
func Test_nil_pointer(t *testing.T) { func Test_nil_pointer(t *testing.T) {
@ -145,7 +146,7 @@ func Test_nil_pointer(t *testing.T) {
X int X int
} }
var obj *T var obj *T
err := Unmarshal(data, obj) err := jsoniter.Unmarshal(data, obj)
should.NotNil(err) should.NotNil(err)
} }
@ -161,7 +162,7 @@ func Test_func_pointer_type(t *testing.T) {
output, err := json.Marshal(TestObject1{}) output, err := json.Marshal(TestObject1{})
should.Nil(err) should.Nil(err)
should.Equal(`{"Obj":null}`, string(output)) should.Equal(`{"Obj":null}`, string(output))
output, err = Marshal(TestObject1{}) output, err = jsoniter.Marshal(TestObject1{})
should.Nil(err) should.Nil(err)
should.Equal(`{"Obj":null}`, string(output)) should.Equal(`{"Obj":null}`, string(output))
}) })
@ -169,32 +170,32 @@ func Test_func_pointer_type(t *testing.T) {
should := require.New(t) should := require.New(t)
_, err := json.Marshal(TestObject1{Obj: &TestObject2{}}) _, err := json.Marshal(TestObject1{Obj: &TestObject2{}})
should.NotNil(err) should.NotNil(err)
_, err = Marshal(TestObject1{Obj: &TestObject2{}}) _, err = jsoniter.Marshal(TestObject1{Obj: &TestObject2{}})
should.NotNil(err) should.NotNil(err)
}) })
t.Run("decode null is valid", func(t *testing.T) { t.Run("decode null is valid", func(t *testing.T) {
should := require.New(t) should := require.New(t)
var obj TestObject1 var obj TestObject1
should.Nil(json.Unmarshal([]byte(`{"Obj":{"F": null}}`), &obj)) should.Nil(json.Unmarshal([]byte(`{"Obj":{"F": null}}`), &obj))
should.Nil(Unmarshal([]byte(`{"Obj":{"F": null}}`), &obj)) should.Nil(jsoniter.Unmarshal([]byte(`{"Obj":{"F": null}}`), &obj))
}) })
t.Run("decode not null is invalid", func(t *testing.T) { t.Run("decode not null is invalid", func(t *testing.T) {
should := require.New(t) should := require.New(t)
var obj TestObject1 var obj TestObject1
should.NotNil(json.Unmarshal([]byte(`{"Obj":{"F": "hello"}}`), &obj)) should.NotNil(json.Unmarshal([]byte(`{"Obj":{"F": "hello"}}`), &obj))
should.NotNil(Unmarshal([]byte(`{"Obj":{"F": "hello"}}`), &obj)) should.NotNil(jsoniter.Unmarshal([]byte(`{"Obj":{"F": "hello"}}`), &obj))
}) })
} }
func TestEOF(t *testing.T) { func TestEOF(t *testing.T) {
var s string var s string
err := ConfigCompatibleWithStandardLibrary.NewDecoder(&bytes.Buffer{}).Decode(&s) err := jsoniter.ConfigCompatibleWithStandardLibrary.NewDecoder(&bytes.Buffer{}).Decode(&s)
assert.Equal(t, io.EOF, err) assert.Equal(t, io.EOF, err)
} }
func TestDecodeErrorType(t *testing.T) { func TestDecodeErrorType(t *testing.T) {
should := require.New(t) should := require.New(t)
var err error var err error
should.Nil(Unmarshal([]byte("null"), &err)) should.Nil(jsoniter.Unmarshal([]byte("null"), &err))
should.NotNil(Unmarshal([]byte("123"), &err)) should.NotNil(jsoniter.Unmarshal([]byte("123"), &err))
} }

View File

@ -1,10 +1,27 @@
package test package test
import "math/big"
func init() { func init() {
marshalCases = append(marshalCases, marshalCases = append(marshalCases,
map[string]interface{}{"abc": 1}, map[string]interface{}{"abc": 1},
map[string]MyInterface{"hello": MyString("world")}, map[string]MyInterface{"hello": MyString("world")},
map[*big.Float]string{big.NewFloat(1.2): "2"},
map[string]interface{}{
"3": 3,
"1": 1,
"2": 2,
},
map[uint64]interface{}{
uint64(1): "a",
uint64(2): "a",
uint64(4): "a",
},
) )
unmarshalCases = append(unmarshalCases, unmarshalCase{
ptr: (*map[string]string)(nil),
input: `{"k\"ey": "val"}`,
})
} }
type MyInterface interface { type MyInterface interface {

View File

@ -25,7 +25,7 @@ func Test_unmarshal(t *testing.T) {
err1 := json.Unmarshal([]byte(testCase.input), ptr1Val.Interface()) err1 := json.Unmarshal([]byte(testCase.input), ptr1Val.Interface())
should.NoError(err1) should.NoError(err1)
ptr2Val := reflect.New(valType) ptr2Val := reflect.New(valType)
err2 := jsoniter.Unmarshal([]byte(testCase.input), ptr2Val.Interface()) err2 := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(testCase.input), ptr2Val.Interface())
should.NoError(err2) should.NoError(err2)
should.Equal(ptr1Val.Interface(), ptr2Val.Interface()) should.Equal(ptr1Val.Interface(), ptr2Val.Interface())
} }
@ -36,7 +36,7 @@ func Test_marshal(t *testing.T) {
for _, testCase := range marshalCases { for _, testCase := range marshalCases {
output1, err1 := json.Marshal(testCase) output1, err1 := json.Marshal(testCase)
should.NoError(err1) should.NoError(err1)
output2, err2 := jsoniter.Marshal(testCase) output2, err2 := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(testCase)
should.NoError(err2) should.NoError(err2)
should.Equal(string(output1), string(output2)) should.Equal(string(output1), string(output2))
} }