...

Source file src/gomodules.xyz/jsonpatch/v2/fuzz_test.go

Documentation: gomodules.xyz/jsonpatch/v2

     1  package jsonpatch_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"testing"
     6  
     7  	jp "github.com/evanphx/json-patch"
     8  	"github.com/stretchr/testify/assert"
     9  	"gomodules.xyz/jsonpatch/v2"
    10  )
    11  
    12  func FuzzCreatePatch(f *testing.F) {
    13  	add := func(a, b string) {
    14  		f.Add([]byte(a), []byte(b))
    15  	}
    16  	add(simpleA, simpleB)
    17  	add(superComplexBase, superComplexA)
    18  	add(hyperComplexBase, hyperComplexA)
    19  	add(arraySrc, arrayDst)
    20  	add(empty, simpleA)
    21  	add(point, lineString)
    22  	f.Fuzz(func(t *testing.T, a, b []byte) {
    23  		checkFuzz(t, a, b)
    24  	})
    25  }
    26  
    27  func checkFuzz(t *testing.T, src, dst []byte) {
    28  	t.Logf("Test: %v -> %v", string(src), string(dst))
    29  	patch, err := jsonpatch.CreatePatch(src, dst)
    30  	if err != nil {
    31  		// Ok to error, src or dst may be invalid
    32  		t.Skip()
    33  	}
    34  
    35  	// Applying library only works with arrays and structs, no primitives
    36  	// We still do CreatePatch to make sure it doesn't panic
    37  	if isPrimitive(src) || isPrimitive(dst) {
    38  		return
    39  	}
    40  
    41  	for _, p := range patch {
    42  		if p.Path == "" {
    43  			// json-patch doesn't handle this properly, but it is valid
    44  			return
    45  		}
    46  	}
    47  
    48  	data, err := json.Marshal(patch)
    49  	assert.Nil(t, err)
    50  
    51  	t.Logf("Applying patch %v", string(data))
    52  	p2, err := jp.DecodePatch(data)
    53  	assert.Nil(t, err)
    54  
    55  	d2, err := p2.Apply(src)
    56  	assert.Nil(t, err)
    57  
    58  	assert.JSONEq(t, string(dst), string(d2))
    59  }
    60  
    61  func isPrimitive(data []byte) bool {
    62  	return data[0] != '{' && data[0] != '['
    63  }
    64  

View as plain text