k8s.io/apiserver@v0.31.1/pkg/cel/mutation/common/val_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 common
    18  
    19  import (
    20  	"reflect"
    21  	"testing"
    22  
    23  	"github.com/google/cel-go/common/types"
    24  	"github.com/google/cel-go/common/types/ref"
    25  )
    26  
    27  func TestOptional(t *testing.T) {
    28  	for _, tc := range []struct {
    29  		name     string
    30  		fields   map[string]ref.Val
    31  		expected map[string]any
    32  	}{
    33  		{
    34  			name: "present",
    35  			fields: map[string]ref.Val{
    36  				"zero": types.OptionalOf(types.IntZero),
    37  			},
    38  			expected: map[string]any{
    39  				"zero": int64(0),
    40  			},
    41  		},
    42  		{
    43  			name: "none",
    44  			fields: map[string]ref.Val{
    45  				"absent": types.OptionalNone,
    46  			},
    47  			expected: map[string]any{
    48  				// right now no way to differ from a plain null.
    49  				// we will need to filter out optional.none() before this conversion.
    50  				"absent": nil,
    51  			},
    52  		},
    53  	} {
    54  		t.Run(tc.name, func(t *testing.T) {
    55  			v := &ObjectVal{
    56  				typeRef: nil, // safe in this test, otherwise put a mock
    57  				fields:  tc.fields,
    58  			}
    59  			converted := v.Value()
    60  			if !reflect.DeepEqual(tc.expected, converted) {
    61  				t.Errorf("wrong result, expected %v but got %v", tc.expected, converted)
    62  			}
    63  		})
    64  	}
    65  }