Skip to content

Commit

Permalink
Improve fuzz tests
Browse files Browse the repository at this point in the history
Signed-off-by: John Howard <[email protected]>
  • Loading branch information
howardjohn committed May 16, 2023
1 parent 471fa30 commit 1f7eb13
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion v2/fuzz_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package jsonpatch_test

import (
"encoding/json"
"testing"

jp "github.com/evanphx/json-patch"
"github.com/stretchr/testify/assert"
"gomodules.xyz/jsonpatch/v2"
)

Expand All @@ -17,6 +20,35 @@ func FuzzCreatePatch(f *testing.F) {
add(empty, simpleA)
add(point, lineString)
f.Fuzz(func(t *testing.T, a, b []byte) {
_, _ = jsonpatch.CreatePatch(a, b)
checkFuzz(t, a, b)
})
}

func checkFuzz(t *testing.T, src, dst []byte) {
patch, err := jsonpatch.CreatePatch(src, dst)
if err != nil {
// Ok to error, src or dst may be invalid
t.Skip()
}

// Applying library only works with arrays and structs, no primitives
// We still do CreatePatch to make sure it doesn't panic
if isPrimitive(src) || isPrimitive(dst) {
return
}

data, err := json.Marshal(patch)
assert.Nil(t, err)

p2, err := jp.DecodePatch(data)
assert.Nil(t, err)

d2, err := p2.Apply(src)
assert.Nil(t, err)

assert.JSONEq(t, string(dst), string(d2))
}

func isPrimitive(data []byte) bool {
return data[0] != '{' && data[0] != '['
}

0 comments on commit 1f7eb13

Please sign in to comment.