Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added tests for default environment under cel package #1119

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions pkg/utils/cel/default_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cel

import (
"reflect"
"testing"
"time"

"github.com/google/cel-go/common/types"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func TestFuncsToMethods(t *testing.T) {
funcs := map[string][]any{
nowName: {timeNow},
mathRandName: {mathRand},
sinceSecondName: {sinceSecond[*corev1.Node], sinceSecond[*corev1.Pod]},
unixSecondName: {unixSecond},
quantityName: {NewQuantityFromString},
}

methods := FuncsToMethods(funcs)

expectedMethods := map[string][]any{
sinceSecondName: {sinceSecond[*corev1.Node], sinceSecond[*corev1.Pod]},
}

for name, funcs := range expectedMethods {
if _, ok := methods[name]; !ok {
t.Errorf("Expected method %s not found in the result", name)
continue
}

for i, fun := range funcs {
if reflect.TypeOf(methods[name][i]) != reflect.TypeOf(fun) {
t.Errorf("Expected method %s of type %v, but got %v", name, reflect.TypeOf(fun), reflect.TypeOf(methods[name][i]))
}
}
}
}

func TestDefaultConversions(t *testing.T) {
timeValue := metav1.Time{Time: time.Now()}
durationValue := metav1.Duration{Duration: time.Second}
quantityValue := resource.MustParse("1Gi")

tests := []struct {
name string
fn any
arg any
want any
}{
{
name: "metav1.Time to types.Timestamp",
fn: DefaultConversions[0],
arg: timeValue,
want: types.Timestamp{Time: timeValue.Time},
},
{
name: "*metav1.Time to types.Timestamp",
fn: DefaultConversions[1],
arg: &timeValue,
want: types.Timestamp{Time: timeValue.Time},
},
{
name: "metav1.Duration to types.Duration",
fn: DefaultConversions[2],
arg: durationValue,
want: types.Duration{Duration: durationValue.Duration},
},
{
name: "*metav1.Duration to types.Duration",
fn: DefaultConversions[3],
arg: &durationValue,
want: types.Duration{Duration: durationValue.Duration},
},
{
name: "resource.Quantity to Quantity",
fn: DefaultConversions[4],
arg: quantityValue,
want: NewQuantity(&quantityValue),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fnValue := reflect.ValueOf(tt.fn)
argValue := reflect.ValueOf(tt.arg)
result := fnValue.Call([]reflect.Value{argValue})[0].Interface()
if !reflect.DeepEqual(result, tt.want) {
t.Errorf("Expected %v, but got %v", tt.want, result)
}
})
}
}
129 changes: 129 additions & 0 deletions pkg/utils/cel/environment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
Copyright 2024 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cel

import (
"testing"

"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
)

// TestNewEnvironment tests the NewEnvironment function.
func TestNewEnvironment(t *testing.T) {
// Mock configuration
conf := EnvironmentConfig{
Conversions: []interface{}{},
Types: []interface{}{},
Vars: map[string]interface{}{},
Funcs: map[string][]interface{}{},
Methods: map[string][]interface{}{},
}

// Create a new environment
env, err := NewEnvironment(conf)
if err != nil {
t.Fatalf("Error creating new environment: %v", err)
}

// Check if the environment is created successfully
if env == nil {
t.Fatal("Expected non-nil environment, got nil")
}
}

// TestCompile tests the Compile function.
func TestCompile(t *testing.T) {
// Mock configuration
conf := EnvironmentConfig{
Conversions: []interface{}{},
Types: []interface{}{},
Vars: map[string]interface{}{},
Funcs: map[string][]interface{}{},
Methods: map[string][]interface{}{},
}

// Create a new environment
env, err := NewEnvironment(conf)
if err != nil {
t.Fatalf("Error creating new environment: %v", err)
}

// Compile a simple expression
expression := "1 + 2"
program, err := env.Compile(expression)
if err != nil {
t.Fatalf("Error compiling expression '%s': %v", expression, err)
}

// Check if the program is compiled successfully
if program == nil {
t.Fatalf("Expected non-nil program, got nil")
}
}

// TestAsFloat64 tests the AsFloat64 function.
func TestAsFloat64(t *testing.T) {
// Test with supported types
testCases := []struct {
input ref.Val
expected float64
}{
{types.Double(3.14), 3.14},
{types.Int(10), 10},
{types.Uint(5), 5},
{types.Bool(true), 1},
}

for _, tc := range testCases {
result, err := AsFloat64(tc.input)
if err != nil {
t.Errorf("Error converting %T to float64: %v", tc.input, err)
}

if result != tc.expected {
t.Errorf("Expected %T to be converted to %f, got %f", tc.input, tc.expected, result)
}
}

// Test with unsupported type
_, err := AsFloat64(types.String("test"))
if err == nil {
t.Error("Expected an error for unsupported type conversion")
}
}

// TestAsString tests the AsString function.
func TestAsString(t *testing.T) {
// Test with supported type
input := types.String("test")
expected := "test"

result, err := AsString(input)
if err != nil {
t.Errorf("Error converting %T to string: %v", input, err)
}

if result != expected {
t.Errorf("Expected %T to be converted to '%s', got '%s'", input, expected, result)
}

// Test with unsupported type
_, err = AsString(types.Int(10))
if err == nil {
t.Error("Expected an error for unsupported type conversion")
}
}
Loading