k8s.io/kube-openapi@v0.0.0-20240228011516-70dd3763d340/pkg/openapiconv/convert_test.go (about)

     1  /*
     2  Copyright 2022 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 openapiconv
    18  
    19  import (
    20  	"encoding/json"
    21  	"os"
    22  	"path/filepath"
    23  	"reflect"
    24  	"testing"
    25  
    26  	"k8s.io/kube-openapi/pkg/spec3"
    27  	"k8s.io/kube-openapi/pkg/util/jsontesting"
    28  	"k8s.io/kube-openapi/pkg/validation/spec"
    29  )
    30  
    31  func TestConvert(t *testing.T) {
    32  
    33  	tcs := []struct {
    34  		groupVersion string
    35  	}{{
    36  		"batch.v1",
    37  	}, {
    38  		"api.v1",
    39  	}, {
    40  		"apiextensions.k8s.io.v1",
    41  	}}
    42  
    43  	for _, tc := range tcs {
    44  
    45  		spec2JSON, err := os.ReadFile(filepath.Join("testdata_generated_from_k8s/v2_" + tc.groupVersion + ".json"))
    46  		if err != nil {
    47  			t.Fatal(err)
    48  		}
    49  		var swaggerSpec spec.Swagger
    50  		err = json.Unmarshal(spec2JSON, &swaggerSpec)
    51  		if err != nil {
    52  			t.Fatal(err)
    53  		}
    54  
    55  		openAPIV2JSONBeforeConversion, err := swaggerSpec.MarshalJSON()
    56  		if err != nil {
    57  			t.Fatal(err)
    58  		}
    59  
    60  		convertedV3Spec := ConvertV2ToV3(&swaggerSpec)
    61  
    62  		openAPIV2JSONAfterConversion, err := swaggerSpec.MarshalJSON()
    63  		if err != nil {
    64  			t.Fatal(err)
    65  		}
    66  		if err := jsontesting.JsonCompare(openAPIV2JSONBeforeConversion, openAPIV2JSONAfterConversion); err != nil {
    67  			t.Errorf("Expected OpenAPI V2 to be untouched before and after conversion: %v", err)
    68  		}
    69  
    70  		spec3JSON, err := os.ReadFile(filepath.Join("testdata_generated_from_k8s/v3_" + tc.groupVersion + ".json"))
    71  		if err != nil {
    72  			t.Fatal(err)
    73  		}
    74  
    75  		var V3Spec spec3.OpenAPI
    76  		json.Unmarshal(spec3JSON, &V3Spec)
    77  		if !reflect.DeepEqual(V3Spec, *convertedV3Spec) {
    78  			t.Error("Expected specs to be equal")
    79  		}
    80  	}
    81  }