From 947173bf7153d8512b0ad607206b6e5eaf74225f Mon Sep 17 00:00:00 2001 From: TwiN Date: Fri, 23 Dec 2022 09:55:17 -0500 Subject: [PATCH] fix: Prevent jsonpath from causing panic when body is expected to be array but isn't (#392) * fix: Prevent jsonpath from causing panic when body is expected to be array but isn't Fixes #391 --- core/condition_test.go | 7 +++++++ jsonpath/jsonpath.go | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/core/condition_test.go b/core/condition_test.go index 934c053d..005316b5 100644 --- a/core/condition_test.go +++ b/core/condition_test.go @@ -231,6 +231,13 @@ func TestCondition_evaluate(t *testing.T) { ExpectedSuccess: true, ExpectedOutput: "[BODY][0].id == 1", }, + { + Name: "body-jsonpath-when-body-is-array-but-actual-body-is-not", + Condition: Condition("[BODY][0].name == test"), + Result: &Result{body: []byte("{\"statusCode\": 500, \"message\": \"Internal Server Error\"}")}, + ExpectedSuccess: false, + ExpectedOutput: "[BODY][0].name (INVALID) == test", + }, { Name: "body-jsonpath-complex-int", Condition: Condition("[BODY].data.id == 1"), diff --git a/jsonpath/jsonpath.go b/jsonpath/jsonpath.go index 04052987..2c7c10dd 100644 --- a/jsonpath/jsonpath.go +++ b/jsonpath/jsonpath.go @@ -93,7 +93,7 @@ func extractValue(currentKey string, value interface{}) interface{} { currentKeyWithoutIndex := currentKey[:startOfBracket] // if currentKeyWithoutIndex contains only an index (i.e. [0] or 0) if len(currentKeyWithoutIndex) == 0 { - array := value.([]interface{}) + array, _ := value.([]interface{}) if len(array) > arrayIndex { if isNestedArray { return extractValue(currentKey[endOfBracket+1:], array[arrayIndex]) @@ -106,7 +106,7 @@ func extractValue(currentKey string, value interface{}) interface{} { return nil } // if currentKeyWithoutIndex contains both a key and an index (i.e. data[0]) - array := value.(map[string]interface{})[currentKeyWithoutIndex].([]interface{}) + array, _ := value.(map[string]interface{})[currentKeyWithoutIndex].([]interface{}) if len(array) > arrayIndex { if isNestedArray { return extractValue(currentKey[endOfBracket+1:], array[arrayIndex])