Skip to content

Commit

Permalink
chore: add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mabdh committed Apr 20, 2024
1 parent fcdfe38 commit 06d5781
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 2 deletions.
63 changes: 63 additions & 0 deletions pkg/body_extractor/json_payload_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package body_extractor

import (
"bytes"
"encoding/json"
"io"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
)

func TestJSONPayloadHandler_Extract(t *testing.T) {
defaultTestMessage := map[string]any{
"k1": "v1",
"nested_k1": map[string]any{
"k1_1": "v1",
"k2_2": 1,
},
}

tests := []struct {
name string
key string
testMessage any
want any
wantErrString string
}{
{
name: "should return error if field not exist",
key: "x",
testMessage: defaultTestMessage,
wantErrString: "failed to find field: x",
},
{
name: "should return value if field found",
key: "nested_k1.k2_2",
testMessage: defaultTestMessage,
want: float64(1),
},
}
for _, tt := range tests {
h := JSONPayloadHandler{}
t.Run(tt.name, func(t *testing.T) {
tt := tt
t.Parallel()

msg, err := json.Marshal(tt.testMessage)
assert.NoError(t, err)

testReader := io.NopCloser(bytes.NewBuffer(msg))
extractedData, err := h.Extract(&testReader, tt.key)

if tt.wantErrString != "" {
assert.Equal(t, tt.wantErrString, err.Error())
} else {
if diff := cmp.Diff(tt.want, extractedData); diff != "" {
t.Fatal(diff)
}
}
})
}
}
3 changes: 1 addition & 2 deletions pkg/expression/expression.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package expression

import (
"errors"
"fmt"
"reflect"
)
Expand All @@ -21,7 +20,7 @@ func (e Expression) Evaluate() (bool, error) {
output = reflect.DeepEqual(e.Attribute, e.Value)
err = nil
default:
err = errors.New(fmt.Sprintf("unsupported operator %s", e.Operator))
err = fmt.Errorf("unsupported operator %s", e.Operator)
}

return output, err
Expand Down
10 changes: 10 additions & 0 deletions pkg/expression/expression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ func TestExpression_Evaluate(t *testing.T) {
wantNilErr: true,
wantOutput: false,
},
{
name: "unknown expression return error",
expression: Expression{
Attribute: "A",
Operator: "';l",
Value: "B",
},
wantNilErr: false,
wantOutput: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 06d5781

Please sign in to comment.