Skip to content

Commit 2510644

Browse files
committed
refact(test): refactored tests to avoid conversions when asserting JSON
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
1 parent dcfd48d commit 2510644

File tree

17 files changed

+84
-99
lines changed

17 files changed

+84
-99
lines changed

README.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ You may also use it standalone for your projects.
1818
* [Contents](#contents)
1919
* [Dependencies](#dependencies)
2020
* [Release Notes](#release-notes)
21+
* [Licensing](#licensing)
2122
* [Note to contributors](#note-to-contributors)
2223
* [TODOs, suggestions and plans](#todos-suggestions-and-plans)
2324

@@ -64,17 +65,17 @@ dependencies outside of the standard library.
6465

6566
### v0.25.2 (draft, unpublished)
6667

67-
Minor changes due to internal maintainance that don't affect the behavior of the library.
68+
Minor changes due to internal maintenance that don't affect the behavior of the library.
6869

69-
* removed indirect test dependencies by switching all tests to `go-openapi/testify`,
70+
* [x] removed indirect test dependencies by switching all tests to `go-openapi/testify`,
7071
a fork of `stretch/testify` with zero-dependencies.
71-
* improvements to CI to catch test reports.
72-
* modernized licensing annotations in source code, using the more compact SPDX annotations
72+
* [x] improvements to CI to catch test reports.
73+
* [x] modernized licensing annotations in source code, using the more compact SPDX annotations
7374
rather than the full license terms.
74-
* simplified a bit JSON & YAML testing by using newly available assertions
75+
* [x] simplified a bit JSON & YAML testing by using newly available assertions
7576
* started the journey to an OpenSSF score card badge:
76-
* explicited permissions in CI workflows
77-
* published security policy
77+
* [x] explicited permissions in CI workflows
78+
* [x] published security policy
7879
* pinned dependencies to github actions
7980
* introduced fuzzing in tests
8081

jsonutils/adapters/easyjson/json/adapter_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func TestAdapter(t *testing.T) {
4141
jazon, err := a.Marshal(value)
4242
require.NoError(t, err)
4343

44-
require.JSONEq(t, test.JSONPayload, string(jazon))
44+
require.JSONEqBytes(t, test.JSONBytes(), jazon)
4545
})
4646
})
4747

@@ -60,7 +60,7 @@ func TestAdapter(t *testing.T) {
6060
jazon, err := a.OrderedMarshal(value)
6161
require.NoError(t, err)
6262

63-
fixtures.JSONEqualOrdered(t, test.JSONPayload, string(jazon))
63+
fixtures.JSONEqualOrderedBytes(t, test.JSONBytes(), jazon)
6464
})
6565
})
6666
})

jsonutils/adapters/easyjson/json/ordered_map_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func TestSetOrdered(t *testing.T) {
3434
jazon, err := m.MarshalJSON()
3535
require.NoError(t, err)
3636

37-
fixtures.JSONEqualOrdered(t, `{"a":1,"c":"y","b":2}`, string(jazon))
37+
fixtures.JSONEqualOrderedBytes(t, []byte(`{"a":1,"c":"y","b":2}`), jazon)
3838
})
3939

4040
t.Run("should reset keys", func(t *testing.T) {

jsonutils/adapters/stdlib/json/adapter_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func TestAdapter(t *testing.T) {
4343
jazon, err := a.Marshal(value)
4444
require.NoError(t, err)
4545

46-
require.JSONEq(t, test.JSONPayload, string(jazon))
46+
require.JSONEqBytes(t, test.JSONBytes(), jazon)
4747
})
4848
})
4949

@@ -62,7 +62,7 @@ func TestAdapter(t *testing.T) {
6262
jazon, err := a.OrderedMarshal(value)
6363
require.NoError(t, err)
6464

65-
fixtures.JSONEqualOrdered(t, test.JSONPayload, string(jazon))
65+
fixtures.JSONEqualOrderedBytes(t, test.JSONBytes(), jazon)
6666
})
6767
})
6868
})

jsonutils/adapters/stdlib/json/ordered_map_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func TestSetOrdered(t *testing.T) {
4242
jazon, err := m.MarshalJSON()
4343
require.NoError(t, err)
4444

45-
fixtures.JSONEqualOrdered(t, `{"a":1,"c":"y","b":2}`, string(jazon))
45+
fixtures.JSONEqualOrderedBytes(t, []byte(`{"a":1,"c":"y","b":2}`), jazon)
4646
})
4747

4848
t.Run("should reset keys", func(t *testing.T) {
@@ -79,21 +79,21 @@ func TestMapSlice(t *testing.T) {
7979
jazon, err := stdjson.Marshal(data)
8080
require.NoError(t, err)
8181

82-
fixtures.JSONEqualOrdered(t, test.JSONPayload, string(jazon))
82+
fixtures.JSONEqualOrderedBytes(t, test.JSONBytes(), jazon)
8383
})
8484

8585
t.Run("should keep the order of keys", func(t *testing.T) {
8686
fixture := harness.ShouldGet("with numbers")
87-
input := fixture.JSONPayload
87+
input := fixture.JSONBytes()
8888

8989
const iterations = 10
9090
for range iterations {
9191
var data MapSlice
92-
require.NoError(t, stdjson.Unmarshal([]byte(input), &data))
92+
require.NoError(t, stdjson.Unmarshal(input, &data))
9393
jazon, err := stdjson.Marshal(data)
9494
require.NoError(t, err)
9595

96-
fixtures.JSONEqualOrdered(t, input, string(jazon)) // specifically check the same order, not require.JSONEq()
96+
fixtures.JSONEqualOrderedBytes(t, input, jazon) // specifically check the same order, not require.JSONEq()
9797
}
9898
})
9999
})

jsonutils/adapters/testintegration/benchmarks/payloads_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func verifyPayload[T any](constructor func() *T) func(*testing.T) {
5252
data, err := jw.BuildBytes()
5353
require.NoError(t, err)
5454
require.NotEmpty(t, data)
55-
require.JSONEq(t, string(jazon), string(data))
55+
require.JSONEqBytes(t, jazon, data)
5656

5757
t.Run(fmt.Sprintf("value of type %T should UnmarshalEasyJSON", value), func(t *testing.T) {
5858
target := new(T)

jsonutils/adapters/testintegration/integration_suite_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -230,9 +230,9 @@ func testJSONTransforms[V any, T any](test fixtures.Fixture, valueConstructor fu
230230

231231
switch assertAs {
232232
case assertionTypeOrdered:
233-
fixtures.JSONEqualOrdered(t, test.JSONPayload, string(jazon))
233+
fixtures.JSONEqualOrderedBytes(t, test.JSONBytes(), jazon)
234234
case assertionTypeUnordered:
235-
require.JSONEq(t, test.JSONPayload, string(jazon))
235+
require.JSONEqBytes(t, test.JSONBytes(), jazon)
236236
}
237237

238238
t.Run(fmt.Sprintf("FromDynamicJSON then WriteJSON should produce %s JSON", expectation), func(t *testing.T) {
@@ -253,9 +253,9 @@ func testJSONTransforms[V any, T any](test fixtures.Fixture, valueConstructor fu
253253

254254
switch assertAs {
255255
case assertionTypeOrdered:
256-
fixtures.JSONEqualOrdered(t, test.JSONPayload, string(jazon))
256+
fixtures.JSONEqualOrderedBytes(t, test.JSONBytes(), jazon)
257257
case assertionTypeUnordered:
258-
require.JSONEq(t, test.JSONPayload, string(jazon))
258+
require.JSONEqBytes(t, test.JSONBytes(), jazon)
259259
}
260260
})
261261
})

jsonutils/fixtures_test/go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
module github.com/go-openapi/swag/jsonutils/fixtures_test
22

33
require (
4+
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2
45
github.com/go-openapi/testify/v2 v2.0.2
56
go.yaml.in/yaml/v3 v3.0.4
67
)

jsonutils/fixtures_test/go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
2+
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4=
3+
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg=
24
github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls=
35
github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
46
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=

jsonutils/fixtures_test/harness.go

Lines changed: 25 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,14 @@ import (
88
"embed"
99
"encoding/json"
1010
"errors"
11-
"fmt"
1211
"io"
1312
"io/fs"
1413
"iter"
1514
"path/filepath"
1615
"regexp"
1716
"testing"
1817

19-
"github.com/go-openapi/testify/v2/assert"
18+
_ "github.com/go-openapi/testify/enable/yaml/v2" // enable yaml in testify
2019
"github.com/go-openapi/testify/v2/require"
2120
yaml "go.yaml.in/yaml/v3"
2221
)
@@ -199,11 +198,19 @@ func loadFixture(fsys fs.FS, pth string) ([]byte, error) {
199198
func JSONEqualOrdered(t testing.TB, expected, actual string) {
200199
t.Helper()
201200

202-
bufExpected := bytes.NewBufferString(expected)
201+
JSONEqualOrderedBytes(t, []byte(expected), []byte(actual))
202+
}
203+
204+
// JSONEqualOrderedBytes is a replacement for [require.JSONEqBytes] that checks further that
205+
// two JSONs are exactly equal. See [JSONEqualOrdered].
206+
func JSONEqualOrderedBytes(t testing.TB, expected, actual []byte) {
207+
t.Helper()
208+
209+
bufExpected := bytes.NewBuffer(expected)
203210
decExpected := json.NewDecoder(bufExpected)
204211
expectedTokens := make([]json.Token, 0)
205212

206-
bufActual := bytes.NewBufferString(actual)
213+
bufActual := bytes.NewBuffer(actual)
207214
decActual := json.NewDecoder(bufActual)
208215

209216
for {
@@ -266,53 +273,25 @@ var (
266273
func YAMLEqualOrdered(t testing.TB, expected, actual string) {
267274
t.Helper()
268275

269-
RequireYAMLEq(t, expected, actual) // necessary but not sufficient condition
270-
271-
// strip all indentation and comments (anchors not supported)
272-
strippedExpected := rexStripIndent.ReplaceAllString(expected, "")
273-
strippedExpected = rexStripComment.ReplaceAllString(strippedExpected, "")
274-
strippedExpected = rexStripInlineComment.ReplaceAllString(strippedExpected, "$1")
275-
strippedExpected = rexStripEmpty.ReplaceAllString(strippedExpected, "")
276-
277-
strippedActual := rexStripIndent.ReplaceAllString(expected, "")
278-
strippedActual = rexStripComment.ReplaceAllString(strippedActual, "")
279-
strippedActual = rexStripInlineComment.ReplaceAllString(strippedActual, "$1")
280-
strippedActual = rexStripEmpty.ReplaceAllString(strippedActual, "")
281-
282-
require.Equal(t, strippedExpected, strippedActual)
276+
YAMLEqualOrderedBytes(t, []byte(expected), []byte(actual))
283277
}
284278

285-
// RequireYAMLEq is the same as [require.YAMLEq] but without the dependency to go.pkg.in/yaml.v3.
286-
//
287-
// NOTE: this could be reverted once https://github.com/stretchr/testify/pull/1772 is merged.
288-
func RequireYAMLEq(t testing.TB, expected string, actual string, msgAndArgs ...any) {
279+
func YAMLEqualOrderedBytes(t testing.TB, expected, actual []byte) {
289280
t.Helper()
290281

291-
if AssertYAMLEq(t, expected, actual, msgAndArgs...) {
292-
return
293-
}
294-
t.FailNow()
295-
}
296-
297-
// AssertYAMLEq is the same as [assert.YAMLEq] but without the dependency to go.pkg.in/yaml.v3.
298-
//
299-
// NOTE: this could be reverted once https://github.com/stretchr/testify/pull/1772 is merged.
300-
func AssertYAMLEq(t testing.TB, expected string, actual string, msgAndArgs ...any) bool {
301-
t.Helper()
302-
var expectedYAMLAsInterface, actualYAMLAsInterface any
303-
304-
if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
305-
return assert.Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
306-
}
282+
// TODO: add YAMLEqBytes to testify
283+
require.YAMLEq(t, string(expected), string(actual)) // necessary but not sufficient condition
307284

308-
// Shortcut if same bytes
309-
if actual == expected {
310-
return true
311-
}
285+
// strip all indentation and comments (anchors not supported)
286+
strippedExpected := rexStripIndent.ReplaceAll(expected, []byte(""))
287+
strippedExpected = rexStripComment.ReplaceAll(strippedExpected, []byte(""))
288+
strippedExpected = rexStripInlineComment.ReplaceAll(strippedExpected, []byte("$1"))
289+
strippedExpected = rexStripEmpty.ReplaceAll(strippedExpected, []byte(""))
312290

313-
if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
314-
return assert.Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
315-
}
291+
strippedActual := rexStripIndent.ReplaceAll(expected, []byte(""))
292+
strippedActual = rexStripComment.ReplaceAll(strippedActual, []byte(""))
293+
strippedActual = rexStripInlineComment.ReplaceAll(strippedActual, []byte("$1"))
294+
strippedActual = rexStripEmpty.ReplaceAll(strippedActual, []byte(""))
316295

317-
return assert.Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
296+
require.Equal(t, strippedExpected, strippedActual)
318297
}

0 commit comments

Comments
 (0)