k8s.io/apiserver@v0.31.1/pkg/cel/mutation/typeprovider_test.go (about)

     1  /*
     2  Copyright 2024 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package mutation
    18  
    19  import (
    20  	"reflect"
    21  	"testing"
    22  )
    23  
    24  func TestTypeProvider(t *testing.T) {
    25  	for _, tc := range []struct {
    26  		name          string
    27  		expression    string
    28  		expectedValue any
    29  	}{
    30  		{
    31  			name:          "not an object",
    32  			expression:    `2 * 31 * 1847`,
    33  			expectedValue: int64(114514), // type resolver should not interfere.
    34  		},
    35  		{
    36  			name:          "empty",
    37  			expression:    "Object{}",
    38  			expectedValue: map[string]any{},
    39  		},
    40  		{
    41  			name:          "Object.spec",
    42  			expression:    "Object{spec: Object.spec{replicas: 3}}",
    43  			expectedValue: map[string]any{"spec": map[string]any{"replicas": int64(3)}},
    44  		},
    45  	} {
    46  		t.Run(tc.name, func(t *testing.T) {
    47  			_, option := NewTypeProviderAndEnvOption(&mockTypeResolver{})
    48  			env := mustCreateEnv(t, option)
    49  			ast, issues := env.Compile(tc.expression)
    50  			if issues != nil {
    51  				t.Fatalf("unexpected issues during compilation: %v", issues)
    52  			}
    53  			program, err := env.Program(ast)
    54  			if err != nil {
    55  				t.Fatalf("unexpected error while creating program: %v", err)
    56  			}
    57  			r, _, err := program.Eval(map[string]any{})
    58  			if err != nil {
    59  				t.Fatalf("unexpected error during evaluation: %v", err)
    60  			}
    61  			if v := r.Value(); !reflect.DeepEqual(tc.expectedValue, v) {
    62  				t.Errorf("expected %v but got %v", tc.expectedValue, v)
    63  			}
    64  		})
    65  	}
    66  }