41 lines
897 B
Go
41 lines
897 B
Go
|
|
package canonical
|
||
|
|
|
||
|
|
import "testing"
|
||
|
|
|
||
|
|
func TestMarshalSortsKeys(t *testing.T) {
|
||
|
|
got, err := Marshal(map[string]any{"b": 1, "a": 2})
|
||
|
|
if err != nil {
|
||
|
|
t.Fatal(err)
|
||
|
|
}
|
||
|
|
// Both keys must be present and sorted by name
|
||
|
|
want := `{"a":2,"b":1}`
|
||
|
|
if string(got) != want {
|
||
|
|
t.Errorf("got %q want %q", string(got), want)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestMarshalStableAcrossRuns(t *testing.T) {
|
||
|
|
input := map[string]any{
|
||
|
|
"outer": map[string]any{"z": 1, "a": 2, "m": 3},
|
||
|
|
"arr": []any{"3", "1", "2"},
|
||
|
|
}
|
||
|
|
a, _ := Marshal(input)
|
||
|
|
b, _ := Marshal(input)
|
||
|
|
if string(a) != string(b) {
|
||
|
|
t.Errorf("not stable:\n%s\nvs\n%s", a, b)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestHashReturnsPrefix(t *testing.T) {
|
||
|
|
hash, raw, err := Hash(map[string]any{"k": "v"})
|
||
|
|
if err != nil {
|
||
|
|
t.Fatal(err)
|
||
|
|
}
|
||
|
|
if hash[:7] != "sha256:" {
|
||
|
|
t.Errorf("hash missing sha256: prefix: %q", hash)
|
||
|
|
}
|
||
|
|
if string(raw) != `{"k":"v"}` {
|
||
|
|
t.Errorf("canonical form: %q", raw)
|
||
|
|
}
|
||
|
|
}
|