Add support for getting the length of the string or the slice of a json path

This commit is contained in:
TwinProduction
2020-08-12 21:42:13 -04:00
parent 937b136e60
commit da92907873
7 changed files with 68 additions and 35 deletions

View File

@ -41,10 +41,10 @@ func (c *Condition) evaluate(result *Result) bool {
return false
}
conditionToDisplay := condition
// If the condition isn't a success, return the resolved condition
// If the condition isn't a success, return what the resolved condition was too
if !success {
log.Printf("[Condition][evaluate] Condition '%s' did not succeed because '%s' is false", condition, resolvedCondition)
conditionToDisplay = resolvedCondition
conditionToDisplay = fmt.Sprintf("%s (%s)", condition, resolvedCondition)
}
result.ConditionResults = append(result.ConditionResults, &ConditionResult{Condition: conditionToDisplay, Success: success})
return success

View File

@ -166,3 +166,21 @@ func TestCondition_evaluateWithBodyJsonPathComplexIntFailureUsingLessThan(t *tes
t.Errorf("Condition '%s' should have been a failure", condition)
}
}
func TestCondition_evaluateWithBodySliceLength(t *testing.T) {
condition := Condition("len([BODY].data) == 3")
result := &Result{Body: []byte("{\"data\": [{\"id\": 1}, {\"id\": 2}, {\"id\": 3}]}")}
condition.evaluate(result)
if !result.ConditionResults[0].Success {
t.Errorf("Condition '%s' should have been a success", condition)
}
}
func TestCondition_evaluateWithBodyStringLength(t *testing.T) {
condition := Condition("len([BODY].name) == 8")
result := &Result{Body: []byte("{\"name\": \"john.doe\"}")}
condition.evaluate(result)
if !result.ConditionResults[0].Success {
t.Errorf("Condition '%s' should have been a success", condition)
}
}

View File

@ -32,13 +32,22 @@ func sanitizeAndResolve(list []string, result *Result) []string {
element = body
default:
// if starts with BodyPlaceHolder, then evaluate json path
if strings.HasPrefix(element, BodyPlaceHolder) {
resolvedElement, err := jsonpath.Eval(strings.Replace(element, fmt.Sprintf("%s.", BodyPlaceHolder), "", 1), result.Body)
if strings.Contains(element, BodyPlaceHolder) {
wantLength := false
if strings.HasPrefix(element, "len(") && strings.HasSuffix(element, ")") {
wantLength = true
element = strings.TrimSuffix(strings.TrimPrefix(element, "len("), ")")
}
resolvedElement, resolvedElementLength, err := jsonpath.Eval(strings.Replace(element, fmt.Sprintf("%s.", BodyPlaceHolder), "", 1), result.Body)
if err != nil {
result.Errors = append(result.Errors, err.Error())
element = fmt.Sprintf("%s %s", element, InvalidConditionElementSuffix)
} else {
element = resolvedElement
if wantLength {
element = fmt.Sprintf("%d", resolvedElementLength)
} else {
element = resolvedElement
}
}
}
}