2017-08-06 11:15:07 +02:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
2017-08-06 15:32:10 +02:00
|
|
|
stdlibJson "encoding/json"
|
2017-08-06 11:15:07 +02:00
|
|
|
"testing"
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
parsecJson "github.com/prataprc/goparsec/json"
|
2017-08-06 11:15:07 +02:00
|
|
|
"github.com/stretchr/testify/require"
|
2017-08-07 12:07:29 +02:00
|
|
|
"github.com/vektah/goparsify"
|
2017-08-06 11:15:07 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestUnmarshal(t *testing.T) {
|
|
|
|
t.Run("basic types", func(t *testing.T) {
|
|
|
|
result, err := Unmarshal(`true`)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, true, result)
|
|
|
|
|
|
|
|
result, err = Unmarshal(`false`)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, false, result)
|
|
|
|
|
|
|
|
result, err = Unmarshal(`null`)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, nil, result)
|
|
|
|
|
|
|
|
result, err = Unmarshal(`"true"`)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, "true", result)
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("array", func(t *testing.T) {
|
|
|
|
result, err := Unmarshal(`[true, null, false]`)
|
|
|
|
require.NoError(t, err)
|
2017-08-06 15:32:10 +02:00
|
|
|
require.Equal(t, []interface{}{true, nil, false}, result)
|
2017-08-06 11:15:07 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("object", func(t *testing.T) {
|
|
|
|
result, err := Unmarshal(`{"true":true, "false":false, "null": null} `)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, map[string]interface{}{"true": true, "false": false, "null": nil}, result)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const benchmarkString = `{"true":true, "false":false, "null": null}`
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
func BenchmarkUnmarshalParsec(b *testing.B) {
|
|
|
|
bytes := []byte(benchmarkString)
|
|
|
|
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
scanner := parsecJson.NewJSONScanner(bytes)
|
|
|
|
_, remaining := parsecJson.Y(scanner)
|
|
|
|
|
|
|
|
require.True(b, remaining.Endof())
|
|
|
|
}
|
|
|
|
}
|
2017-08-06 11:15:07 +02:00
|
|
|
|
|
|
|
func BenchmarkUnmarshalParsify(b *testing.B) {
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
_, err := Unmarshal(benchmarkString)
|
|
|
|
require.NoError(b, err)
|
|
|
|
}
|
2017-08-07 12:07:29 +02:00
|
|
|
goparsify.DumpDebugStats()
|
2017-08-06 11:15:07 +02:00
|
|
|
}
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
func BenchmarkUnmarshalStdlib(b *testing.B) {
|
|
|
|
bytes := []byte(benchmarkString)
|
|
|
|
var result interface{}
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
err := stdlibJson.Unmarshal(bytes, &result)
|
|
|
|
require.NoError(b, err)
|
|
|
|
}
|
|
|
|
}
|