Skip to content

Commit

Permalink
Merge pull request #700 from bstasyszyn/699
Browse files Browse the repository at this point in the history
fix: Ensure "patches" slice is alway constructed in the same order
  • Loading branch information
bstasyszyn authored Jun 9, 2023
2 parents 3c7387f + 35b272e commit 793cbea
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
20 changes: 18 additions & 2 deletions pkg/patch/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"

"github.com/trustbloc/sidetree-core-go/pkg/document"
Expand Down Expand Up @@ -103,8 +104,8 @@ func PatchesFromDocument(doc string) ([]Patch, error) {
var docPatches []Patch
var jsonPatches []string

for key, value := range parsed {
jsonBytes, err := json.Marshal(value)
for _, key := range sortedKeys(parsed) {
jsonBytes, err := json.Marshal(parsed[key])
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -432,3 +433,18 @@ func getGenericArray(arr []string) []interface{} {

return values
}

func sortedKeys(m map[string]interface{}) []string {
keys := make([]string, len(m))

i := 0

for k := range m {
keys[i] = k
i++
}

sort.Strings(keys)

return keys
}
14 changes: 14 additions & 0 deletions pkg/patch/patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,20 @@ func TestPatchesFromDocument(t *testing.T) {
require.Nil(t, p)
require.Contains(t, err.Error(), "document must NOT have the id property")
})
t.Run("patches array is always in the same order", func(t *testing.T) {
var prev []Patch

for i := 1; i <= 100; i++ {
patches, err := PatchesFromDocument(testDoc)
require.NoError(t, err)

if prev != nil {
require.Equalf(t, prev, patches, "expecting the patches array to be in the same order")
}

prev = patches
}
})
}

func TestReplacePatch(t *testing.T) {
Expand Down

0 comments on commit 793cbea

Please sign in to comment.