Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions internal/canonicaljson/canonicaljson_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package canonicaljson

import (
"encoding/json"
"testing"
)

Expand Down Expand Up @@ -100,3 +101,47 @@ func TestEquivalentNestedMapsWithDifferentInputOrderProduceSameCanonicalJSON(t *
t.Fatalf("equivalent nested maps must produce identical canonical JSON:\n A: %s\n B: %s", canonA, canonB)
}
}

func TestCanonicalJSONIgnoresInputWhitespace(t *testing.T) {
compactJSON := []byte(`{"a":1,"b":{"x":2,"y":[3,4]}}`)

formattedJSON := []byte(`{
"b": {
"y": [
3,
4
],
"x": 2
},
"a": 1
}`)

var compact any
if err := json.Unmarshal(compactJSON, &compact); err != nil {
t.Fatalf("unmarshal compact JSON: %v", err)
}

var formatted any
if err := json.Unmarshal(formattedJSON, &formatted); err != nil {
t.Fatalf("unmarshal formatted JSON: %v", err)
}

canonCompact, err := Marshal(compact)
if err != nil {
t.Fatalf("Marshal compact JSON: %v", err)
}

canonFormatted, err := Marshal(formatted)
if err != nil {
t.Fatalf("Marshal formatted JSON: %v", err)
}

if string(canonCompact) != string(canonFormatted) {
t.Fatalf("canonical JSON must ignore input whitespace:\n compact: %s\n formatted: %s", canonCompact, canonFormatted)
}

want := `{"a":1,"b":{"x":2,"y":[3,4]}}`
if string(canonCompact) != want {
t.Fatalf("unexpected canonical output:\n got: %s\nwant: %s", canonCompact, want)
}
}
Loading