| 1 |
// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package benchmarks |
| 5 |
|
| 6 |
import ( |
| 7 |
stdjson "encoding/json" |
| 8 |
"fmt" |
| 9 |
"testing" |
| 10 |
|
| 11 |
fixtures "github.com/go-openapi/swag/jsonutils/fixtures_test" |
| 12 |
"github.com/go-openapi/testify/v2/require" |
| 13 |
"github.com/mailru/easyjson" |
| 14 |
jlexer "github.com/mailru/easyjson/jlexer" |
| 15 |
jwriter "github.com/mailru/easyjson/jwriter" |
| 16 |
) |
| 17 |
|
| 18 |
func TestPayloads(t *testing.T) { |
| 19 |
t.Run("SmallPayload should ReadJSON and WriteJSON", verifyPayload(NewSmallPayload)) |
| 20 |
t.Run("MediumPayload should ReadJSON and WriteJSON", verifyPayload(NewMediumPayload)) |
| 21 |
t.Run("LargePayload should ReadJSON and WriteJSON", verifyPayload(NewLargePayload)) |
| 22 |
} |
| 23 |
|
| 24 |
func TestFixtures(t *testing.T) { |
| 25 |
for i, jazon := range [][]byte{ |
| 26 |
fixtures.ShouldLoadFixture(t, EmbeddedFixtures, "fixtures/small_sample.json"), |
| 27 |
fixtures.ShouldLoadFixture(t, EmbeddedFixtures, "fixtures/medium_sample.json"), |
| 28 |
fixtures.ShouldLoadFixture(t, EmbeddedFixtures, "fixtures/large_sample.json"), |
| 29 |
} { |
| 30 |
t.Run(fmt.Sprintf("[%d] json should be valid", i), func(t *testing.T) { |
| 31 |
var value any |
| 32 |
require.NoError(t, stdjson.Unmarshal(jazon, &value)) |
| 33 |
}) |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
func verifyPayload[T any](constructor func() *T) func(*testing.T) { |
| 38 |
return func(t *testing.T) { |
| 39 |
value := constructor() |
| 40 |
|
| 41 |
t.Run(fmt.Sprintf("value of type %T should MarshalJSON", value), func(t *testing.T) { |
| 42 |
jazon, err := stdjson.Marshal(value) |
| 43 |
require.NoError(t, err) |
| 44 |
require.NotEmpty(t, jazon) |
| 45 |
|
| 46 |
t.Run(fmt.Sprintf("value of type %T should MarshalEasyJSON", value), func(t *testing.T) { |
| 47 |
var val any = value |
| 48 |
easyMarshaler, ok := val.(easyjson.Marshaler) |
| 49 |
require.TrueT(t, ok) |
| 50 |
jw := jwriter.Writer{} |
| 51 |
easyMarshaler.MarshalEasyJSON(&jw) |
| 52 |
data, err := jw.BuildBytes() |
| 53 |
require.NoError(t, err) |
| 54 |
require.NotEmpty(t, data) |
| 55 |
require.JSONEqBytes(t, jazon, data) |
| 56 |
|
| 57 |
t.Run(fmt.Sprintf("value of type %T should UnmarshalEasyJSON", value), func(t *testing.T) { |
| 58 |
target := new(T) |
| 59 |
var tgt any = target |
| 60 |
easyUnmarshaler, ok := tgt.(easyjson.Unmarshaler) |
| 61 |
require.TrueT(t, ok) |
| 62 |
jl := jlexer.Lexer{Data: data} |
| 63 |
easyUnmarshaler.UnmarshalEasyJSON(&jl) |
| 64 |
require.NoError(t, jl.Error()) |
| 65 |
|
| 66 |
require.Equal(t, *value, *target) |
| 67 |
}) |
| 68 |
}) |
| 69 |
}) |
| 70 |
} |
| 71 |
} |