Skip to content

Commit

Permalink
add tests for delete operation, make it more forgiving in case user w…
Browse files Browse the repository at this point in the history
…ants to delete a non-existing field
  • Loading branch information
can3p committed Apr 14, 2024
1 parent 63cc295 commit 12ded8c
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pkg/operations/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ func Delete(root types.Node, path []string, args ...any) error {

node, err := root.Visit(path[0])

if err != nil {
if err == types.ErrFieldMissing {
return nil
} else if err != nil {
return err
}

Expand Down
46 changes: 46 additions & 0 deletions pkg/operations/delete_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package operations

import (
"testing"

"github.com/alecthomas/assert/v2"
"github.com/can3p/sackmesser/pkg/traverse/simplejson"
)

func TestDeleteOperation(t *testing.T) {
jstr := `{ "abc": { "def": [ 1, 2, 3 ] } }`

examples := []struct {
description string
path []string
expected string
isErr bool
}{
{
description: "delete existing field",
path: []string{"abc"},
expected: `{}`,
},
{
description: "delete missing field is fine, it was deleted already",
path: []string{"nonexistant"},
expected: jstr,
},
}

for idx, ex := range examples {
node := simplejson.MustParse([]byte(jstr))

err := Delete(node, ex.path)

if ex.isErr {
assert.Error(t, err, "[Ex %d - %s]", idx+1, ex.description)
continue
}

expected := simplejson.MustParse([]byte(ex.expected))

assert.Equal(t, expected.Value(), node.Value(), "[Ex %d - %s]", idx+1, ex.description)
}

}
10 changes: 10 additions & 0 deletions pkg/traverse/simplejson/simplejson.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,16 @@ func Parse(b []byte) (types.Node, error) {
}, nil
}

func MustParse(b []byte) types.Node {
n, err := Parse(b)

if err != nil {
panic(err)
}

return n
}

func FromNode(n types.Node) types.Node {
j := n.Value()

Expand Down

0 comments on commit 12ded8c

Please sign in to comment.