-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathassert.go
More file actions
52 lines (40 loc) · 1.3 KB
/
assert.go
File metadata and controls
52 lines (40 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package httpassert
import (
"bytes"
"encoding/json"
"testing"
"github.com/pmezard/go-difflib/difflib"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// NormalizeJSON parses JSON and re-marshals it with stable key ordering and indentation.
// - Uses Decoder.UseNumber() to preserve numeric fidelity (avoid float64 surprises).
func NormalizeJSON(t *testing.T, s string) string {
t.Helper()
dec := json.NewDecoder(bytes.NewReader([]byte(s)))
dec.UseNumber()
var v any
require.NoError(t, dec.Decode(&v), "invalid JSON")
b, err := json.MarshalIndent(v, "", " ")
require.NoError(t, err, "failed to marshal normalized JSON")
return string(b)
}
// AssertJSONCanonicalEq compares two JSON strings by normalizing both first.
// On mismatch, it prints a readable diff of the normalized forms.
func AssertJSONCanonicalEq(t *testing.T, expected, actual string) bool {
t.Helper()
expNorm := NormalizeJSON(t, expected)
actNorm := NormalizeJSON(t, actual)
if expNorm != actNorm {
diff := difflib.UnifiedDiff{
A: difflib.SplitLines(expNorm),
B: difflib.SplitLines(actNorm),
FromFile: "Expected",
ToFile: "Actual",
Context: 3,
}
text, _ := difflib.GetUnifiedDiffString(diff)
return assert.Fail(t, "JSON mismatch:\nDiff:\n"+text)
}
return true
}