k8s.io/kubernetes@v1.29.3/test/integration/apiserver/openapi/openapi_enum_test.go (about)

     1  /*
     2  Copyright 2021 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 openapi
    18  
    19  import (
    20  	"context"
    21  	"encoding/json"
    22  	"net/http"
    23  	"testing"
    24  
    25  	"k8s.io/apiserver/pkg/features"
    26  	utilfeature "k8s.io/apiserver/pkg/util/feature"
    27  	"k8s.io/apiserver/pkg/util/openapi"
    28  	restclient "k8s.io/client-go/rest"
    29  	featuregatetesting "k8s.io/component-base/featuregate/testing"
    30  	"k8s.io/kube-openapi/pkg/common"
    31  	"k8s.io/kube-openapi/pkg/validation/spec"
    32  	"k8s.io/kubernetes/pkg/controlplane"
    33  	generated "k8s.io/kubernetes/pkg/generated/openapi"
    34  	"k8s.io/kubernetes/test/integration/framework"
    35  	"k8s.io/kubernetes/test/utils/ktesting"
    36  )
    37  
    38  func TestEnablingOpenAPIEnumTypes(t *testing.T) {
    39  	const typeToAddEnum = "k8s.io/api/core/v1.ContainerPort"
    40  	const typeToCheckEnum = "io.k8s.api.core.v1.ContainerPort"
    41  
    42  	for _, tc := range []struct {
    43  		name            string
    44  		featureEnabled  bool
    45  		enumShouldExist bool
    46  	}{
    47  		{
    48  			name:            "disabled",
    49  			featureEnabled:  false,
    50  			enumShouldExist: false,
    51  		},
    52  		{
    53  			name:            "enabled",
    54  			featureEnabled:  true,
    55  			enumShouldExist: true,
    56  		},
    57  	} {
    58  		t.Run(tc.name, func(t *testing.T) {
    59  			_, ctx := ktesting.NewTestContext(t)
    60  			ctx, cancel := context.WithCancel(ctx)
    61  			defer cancel()
    62  
    63  			defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.OpenAPIEnums, tc.featureEnabled)()
    64  
    65  			getDefinitionsFn := openapi.GetOpenAPIDefinitionsWithoutDisabledFeatures(func(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {
    66  				defs := generated.GetOpenAPIDefinitions(ref)
    67  				def := defs[typeToAddEnum]
    68  				// replace protocol to add the would-be enum field.
    69  				def.Schema.Properties["protocol"] = spec.Schema{
    70  					SchemaProps: spec.SchemaProps{
    71  						Description: "Protocol for port. Must be UDP, TCP, or SCTP. Defaults to \\\"TCP\\\".\\n\\nPossible enum values:\\n - `SCTP`: is the SCTP protocol.\\n - `TCP`: is the TCP protocol.\\n - `UDP`: is the UDP protocol.",
    72  						Default:     "TCP",
    73  						Type:        []string{"string"},
    74  						Format:      "",
    75  						Enum:        []interface{}{"SCTP", "TCP", "UDP"},
    76  					},
    77  				}
    78  				defs[typeToAddEnum] = def
    79  				return defs
    80  			})
    81  
    82  			_, kubeConfig, tearDownFn := framework.StartTestServer(ctx, t, framework.TestServerSetup{
    83  				ModifyServerConfig: func(config *controlplane.Config) {
    84  					config.GenericConfig.OpenAPIConfig = framework.DefaultOpenAPIConfig()
    85  					config.GenericConfig.OpenAPIConfig.GetDefinitions = getDefinitionsFn
    86  				},
    87  			})
    88  			defer tearDownFn()
    89  
    90  			rt, err := restclient.TransportFor(kubeConfig)
    91  			if err != nil {
    92  				t.Fatal(err)
    93  			}
    94  
    95  			req, err := http.NewRequest("GET", kubeConfig.Host+"/openapi/v2", nil)
    96  			if err != nil {
    97  				t.Fatal(err)
    98  			}
    99  			resp, err := rt.RoundTrip(req)
   100  			if err != nil {
   101  				t.Fatal(err)
   102  			}
   103  			var body struct {
   104  				Definitions map[string]struct {
   105  					Properties map[string]struct {
   106  						Description string   `json:"description"`
   107  						Type        string   `json:"type"`
   108  						Enum        []string `json:"enum"`
   109  					} `json:"properties"`
   110  				} `json:"definitions"`
   111  			}
   112  			err = json.NewDecoder(resp.Body).Decode(&body)
   113  			if err != nil {
   114  				t.Fatal(err)
   115  			}
   116  			protocol, ok := body.Definitions[typeToCheckEnum].Properties["protocol"]
   117  			if !ok {
   118  				t.Fatalf("protocol not found in properties in %v", body)
   119  			}
   120  			if enumExists := len(protocol.Enum) > 0; enumExists != tc.enumShouldExist {
   121  				t.Errorf("expect enum exists: %v, but got %v", tc.enumShouldExist, enumExists)
   122  			}
   123  		})
   124  	}
   125  }