Skip to content

Commit

Permalink
Correcting lint issues and adding unit tests
Browse files Browse the repository at this point in the history
Signed-off-by: Annaraya Narasagond <[email protected]>
Signed-off-by: Annaraya Narasagond <[email protected]> Annaraya Narasagond <[email protected]>
  • Loading branch information
asn1809 committed Nov 11, 2024
1 parent dc44123 commit 9e275d9
Show file tree
Hide file tree
Showing 3 changed files with 252 additions and 48 deletions.
73 changes: 40 additions & 33 deletions internal/controller/util/json_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func EvaluateCheckHook(client client.Client, hook *kubeobjects.HookSpec, log log
return false, err
}

return evaluateCheckHookExp(hook.Chk.Condition, resource)
return EvaluateCheckHookExp(hook.Chk.Condition, resource)
case "deployment":
// handle deployment type
resource := &appsv1.Deployment{}
Expand All @@ -49,7 +49,7 @@ func EvaluateCheckHook(client client.Client, hook *kubeobjects.HookSpec, log log
return false, err
}

return evaluateCheckHookExp(hook.Chk.Condition, resource)
return EvaluateCheckHookExp(hook.Chk.Condition, resource)
case "statefulset":
// handle statefulset type
resource := &appsv1.StatefulSet{}
Expand All @@ -59,7 +59,7 @@ func EvaluateCheckHook(client client.Client, hook *kubeobjects.HookSpec, log log
return false, err
}

return evaluateCheckHookExp(hook.Chk.Condition, resource)
return EvaluateCheckHookExp(hook.Chk.Condition, resource)
}

return false, nil
Expand Down Expand Up @@ -104,7 +104,7 @@ func getTimeoutValue(hook *kubeobjects.HookSpec) int {
return defaultTimeoutValue
}

func evaluateCheckHookExp(booleanExpression string, jsonData interface{}) (bool, error) {
func EvaluateCheckHookExp(booleanExpression string, jsonData interface{}) (bool, error) {
op, jsonPaths, err := parseBooleanExpression(booleanExpression)
if err != nil {
return false, fmt.Errorf("failed to parse boolean expression: %w", err)
Expand Down Expand Up @@ -197,6 +197,36 @@ func compareBool(a, b bool, operator string) (bool, error) {
}
}

func compareString(a, b, operator string) (bool, error) {
switch operator {
case "==":
return a == b, nil
case "!=":
return a != b, nil
default:
return false, fmt.Errorf("unknown operator: %s", operator)
}
}

func compareFloat(a, b float64, operator string) (bool, error) {
switch operator {
case "==":
return a == b, nil
case "!=":
return a != b, nil
case "<":
return a < b, nil
case ">":
return a > b, nil
case "<=":
return a <= b, nil
case ">=":
return a >= b, nil
default:
return false, fmt.Errorf("unknown operator: %s", operator)
}
}

func compareValues(val1, val2 interface{}, operator string) (bool, error) {
switch v1 := val1.(type) {
case float64:
Expand All @@ -205,44 +235,21 @@ func compareValues(val1, val2 interface{}, operator string) (bool, error) {
return false, fmt.Errorf("mismatched types")
}

switch operator {
case "==":
return v1 == v2, nil
case "!=":
return v1 != v2, nil
case "<":
return v1 < v2, nil
case ">":
return v1 > v2, nil
case "<=":
return v1 <= v2, nil
case ">=":
return v1 >= v2, nil
}
return compareFloat(v1, v2, operator)
case string:
v2, ok := val2.(string)
if !ok {
return false, fmt.Errorf("mismatched types")
}

switch operator {
case "==":
return v1 == v2, nil
case "!=":
return v1 != v2, nil
}
return compareString(v1, v2, operator)
case bool:
v2, ok := val2.(bool)
if !ok {
return false, fmt.Errorf("mismatched types")
}

switch operator {
case "==":
return v1 == v2, nil
case "!=":
return v1 != v2, nil
}
return compareBool(v1, v2, operator)
}

return false, fmt.Errorf("unsupported type or operator")
Expand Down Expand Up @@ -281,16 +288,16 @@ func parseBooleanExpression(booleanExpression string) (op string, jsonPaths []st
jsonPaths = trimLeadingTrailingWhiteSpace(exprs)

if len(exprs) == 2 &&
isValidJSONPathExpression(jsonPaths[0]) &&
isValidJSONPathExpression(jsonPaths[1]) {
IsValidJSONPathExpression(jsonPaths[0]) &&
IsValidJSONPathExpression(jsonPaths[1]) {
return op, jsonPaths, nil
}
}

return "", []string{}, fmt.Errorf("unable to parse boolean expression %v", booleanExpression)
}

func isValidJSONPathExpression(expr string) bool {
func IsValidJSONPathExpression(expr string) bool {
jp := jsonpath.New("validator").AllowMissingKeys(true)

err := jp.Parse(expr)
Expand Down
199 changes: 199 additions & 0 deletions internal/controller/util/json_util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
package util_test

import (
"encoding/json"
"strconv"
"testing"

"github.com/ramendr/ramen/internal/controller/util"
)

type testCases struct {
jsonPathExprs string
result bool
}

var jsonText1 = []byte(`{
"kind": "Deployment",
"spec": {
"progressDeadlineSeconds": 600,
"replicas": 1,
"revisionHistoryLimit": 10
},
"status": {
"replicas": 1,
"conditions": [
{
"status": "True",
"type": "Progressing"
},
{
"status": "True",
"type": "Available"
}
]
}
}`)

var testCasesData = []testCases{
{
jsonPathExprs: "{$.status.conditions[0].status} == True",
result: true,
},
{
jsonPathExprs: "{$.spec.replicas} == 1",
result: true,
},
{
jsonPathExprs: "{$.status.conditions[0].status} == {True}",
result: false,
},
}

func TestXYZ(t *testing.T) {
for i, tt := range testCasesData {
t.Run(strconv.Itoa(i), func(t *testing.T) {
var jsonData map[string]interface{}
err := json.Unmarshal(jsonText1, &jsonData)
if err != nil {
t.Error(err)
}
_, err = util.EvaluateCheckHookExp(tt.jsonPathExprs, jsonData)

Check failure on line 61 in internal/controller/util/json_util_test.go

View workflow job for this annotation

GitHub Actions / Golangci Lint (.)

Using the variable on range scope `tt` in function literal (scopelint)
if (err == nil) != tt.result {

Check failure on line 62 in internal/controller/util/json_util_test.go

View workflow job for this annotation

GitHub Actions / Golangci Lint (.)

Using the variable on range scope `tt` in function literal (scopelint)
t.Errorf("EvaluateCheckHook() = %v, want %v", err, tt.result)

Check failure on line 63 in internal/controller/util/json_util_test.go

View workflow job for this annotation

GitHub Actions / Golangci Lint (.)

Using the variable on range scope `tt` in function literal (scopelint)
}
})
}
}

func Test_isValidJsonPathExpression(t *testing.T) {
type args struct {
expr string
}
tests := []struct {

Check failure on line 73 in internal/controller/util/json_util_test.go

View workflow job for this annotation

GitHub Actions / Golangci Lint (.)

assignments should only be cuddled with other assignments (wsl)
name string
args args
want bool
}{
{
name: "Simple expression",
args: args{
expr: "$.spec.replicas",
},
want: true,
},
{
name: "no $ at the start",
args: args{
expr: "{.spec.replicas}",
},
want: true,
},
{
name: "element in array",
args: args{
expr: "{$.status.conditions[0].status}",
},
want: true,
},
{
name: "spec 1",
args: args{
expr: "{$.status.readyReplicas}",
},
want: true,
},
{
name: "spec 2",
args: args{
expr: "{$.status.containerStatuses[0].ready}",
},
want: true,
},
{
name: "spec 3a",
args: args{
expr: "{True}",
},
want: false,
},
{
name: "spec 3b",
args: args{
expr: "{False}",
},
want: false,
},
{
name: "spec 3c",
args: args{
expr: "{true}",
},
want: true,
},
{
name: "spec 3d",
args: args{
expr: "{false}",
},
want: true,
},
{
name: "Spec 4",
args: args{
expr: "{$.spec.replicas}",
},
want: true,
},
{
name: "expression with == operator",
args: args{
expr: "$.store.book[?(@.price > 10)].title==$.store.book[0].title",
},
want: true,
},
{
name: "expression with > operator",
args: args{
expr: "$.store.book[?(@.author CONTAINS 'Smith')].price>20",
},
want: true,
},
{
name: "expression with >= operator",
args: args{
expr: "$.user.age>=$.minimum.age",
},
want: true,
},
{
name: "expression with < operator",
args: args{
expr: "$.user.age<$.maximum.age",
},
want: true,
},
{
name: "expression with <= operator",
args: args{
expr: "$.user.age<=$.maximum.age",
},
want: true,
},
{
name: "expression with != operator",
args: args{
expr: "$.user.age!=$.maximum.age",
},
want: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := util.IsValidJSONPathExpression(tt.args.expr); got != tt.want {
t.Errorf("isValidJsonPathExpression() = %v, want %v", got, tt.want)
}
})
}
}
28 changes: 13 additions & 15 deletions internal/controller/vrg_kubeobjects.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,14 +259,12 @@ func (v *VRGInstance) kubeObjectsCaptureStartOrResume(
log1.Info("Check hook executed successfully", "check hook is ", hookName, " result is ", hookResult)
}

if !hookResult {
if shouldHookBeFailedOnError(&cg.Hook) {
// update error state
break
}
if !hookResult && shouldHookBeFailedOnError(&cg.Hook) {
// update error state
continue
break
}
// update error state
continue
}
} else {
requestsCompletedCount += v.kubeObjectsGroupCapture(
Expand Down Expand Up @@ -632,16 +630,16 @@ func (v *VRGInstance) kubeObjectsRecoveryStartOrResume(
log1 := log.WithValues("group", groupNumber, "name", rg.BackupName)

if rg.IsHook {

Check failure on line 632 in internal/controller/vrg_kubeobjects.go

View workflow job for this annotation

GitHub Actions / Golangci Lint (.)

`if rg.IsHook` has complex nested blocks (complexity: 15) (nestif)
hookResult, err := util.EvaluateCheckHook(v.reconciler.Client, &rg.Hook, log1)
if err != nil {
log.Error(err, "error occurred during check hook ")
} else {
hookName := rg.Hook.Name + "/" + rg.Hook.Chk.Name
log1.Info("Check hook executed successfully", "check hook is ", hookName, " result is ", hookResult)
}
if rg.Hook.Type == "check" {
hookResult, err := util.EvaluateCheckHook(v.reconciler.Client, &rg.Hook, log1)
if err != nil {
log.Error(err, "error occurred during check hook ")
} else {
hookName := rg.Hook.Name + "/" + rg.Hook.Chk.Name
log1.Info("Check hook executed successfully", "check hook is ", hookName, " result is ", hookResult)
}

if !hookResult {
if shouldHookBeFailedOnError(&rg.Hook) {
if !hookResult && shouldHookBeFailedOnError(&rg.Hook) {
// update error state
break
}
Expand Down

0 comments on commit 9e275d9

Please sign in to comment.