From f98944590058f936c7adb76ea2c974899a460fe2 Mon Sep 17 00:00:00 2001 From: Jordan Liggitt Date: Tue, 14 Feb 2023 22:14:37 -0500 Subject: [PATCH] Revert "Refactor fake versions of openapi client into testing subdir" This reverts commit 869da89eab37ce670759cea2c86325f36625e7fc. --- .../client-go/openapi/openapitest/fake.go | 131 -------------- .../openapi/openapitest/fake_test.go | 168 ----------------- .../kubectl/pkg/explain/v2/explain_test.go | 170 ++++++++++-------- .../kubectl/pkg/explain/v2/generator_test.go | 42 +---- 4 files changed, 105 insertions(+), 406 deletions(-) delete mode 100644 staging/src/k8s.io/client-go/openapi/openapitest/fake.go delete mode 100644 staging/src/k8s.io/client-go/openapi/openapitest/fake_test.go diff --git a/staging/src/k8s.io/client-go/openapi/openapitest/fake.go b/staging/src/k8s.io/client-go/openapi/openapitest/fake.go deleted file mode 100644 index 30d11727021..00000000000 --- a/staging/src/k8s.io/client-go/openapi/openapitest/fake.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright 2023 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 openapitest - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "k8s.io/client-go/openapi" -) - -// NewFileClient returns a pointer to a testing -// FileOpenAPIClient, which parses the OpenAPI GroupVersion -// files in the passed directory path. Example GroupVersion -// OpenAPI filename for apps/v1 would look like: -// -// apis__apps__v1_openapi.json -// -// The current directory housing these hard-coded GroupVersion -// OpenAPI V3 specification files is: -// -// /api/openapi-spec/v3 -// -// An example to invoke this function for the test files: -// -// NewFileClient("../../../api/openapi-spec/v3") -// -// This function will search passed directory for files -// with the suffix "_openapi.json". IMPORTANT: If any file in -// the directory does NOT parse correctly, this function will -// panic. -func NewFileClient(fullDirPath string) openapi.Client { - _, err := os.Stat(fullDirPath) - if err != nil { - panic(fmt.Sprintf("Unable to find test file directory: %s\n", fullDirPath)) - } - files, err := ioutil.ReadDir(fullDirPath) - if err != nil { - panic(fmt.Sprintf("Error reading test file directory: %s (%s)\n", err, fullDirPath)) - } - values := map[string]openapi.GroupVersion{} - for _, fileInfo := range files { - filename := fileInfo.Name() - apiFilename, err := apiFilepath(filename) - if err != nil { - panic(fmt.Sprintf("Error translating file to apipath: %s (%s)\n", err, filename)) - } - fullFilename := filepath.Join(fullDirPath, filename) - gvFile := fileOpenAPIGroupVersion{filepath: fullFilename} - values[apiFilename] = gvFile - } - return &fileOpenAPIClient{values: values} -} - -// fileOpenAPIClient is a testing version implementing the -// openapi.Client interface. This struct stores the hard-coded -// values returned by this file client. -type fileOpenAPIClient struct { - values map[string]openapi.GroupVersion -} - -// fileOpenAPIClient implements the openapi.Client interface. -var _ openapi.Client = &fileOpenAPIClient{} - -// Paths returns the hard-coded map of the api server relative URL -// path string to the GroupVersion swagger bytes. An example Path -// string for apps/v1 GroupVersion is: -// -// apis/apps/v1 -func (f fileOpenAPIClient) Paths() (map[string]openapi.GroupVersion, error) { - return f.values, nil -} - -// fileOpenAPIGroupVersion is a testing version implementing the -// openapi.GroupVersion interface. This struct stores the full -// filepath to the file storing the hard-coded GroupVersion bytes. -type fileOpenAPIGroupVersion struct { - filepath string -} - -// FileOpenAPIGroupVersion implements the openapi.GroupVersion interface. -var _ openapi.GroupVersion = &fileOpenAPIGroupVersion{} - -// Schemas returns the GroupVersion bytes at the stored filepath, or -// an error if one is returned from reading the file. Panics if the -// passed contentType string is not "application/json". -func (f fileOpenAPIGroupVersion) Schema(contentType string) ([]byte, error) { - if contentType != "application/json" { - panic("FileOpenAPI only supports 'application/json' contentType") - } - return ioutil.ReadFile(f.filepath) -} - -// apiFilepath is a helper function to parse a openapi filename -// and transform it to the corresponding api relative url. This function -// is the inverse of the filenaming for OpenAPI V3 specs in the -// hack/update-openapi-spec.sh -// -// Examples: -// -// apis__apps__v1_openapi.json -> apis/apps/v1 -// apis__networking.k8s.io__v1alpha1_openapi.json -> apis/networking.k8s.io/v1alpha1 -// api__v1_openapi.json -> api/v1 -// logs_openapi.json -> logs -func apiFilepath(filename string) (string, error) { - if !strings.HasSuffix(filename, "_openapi.json") { - errStr := fmt.Sprintf("Unable to parse openapi v3 spec filename: %s", filename) - return "", errors.New(errStr) - } - filename = strings.TrimSuffix(filename, "_openapi.json") - filepath := strings.ReplaceAll(filename, "__", "/") - return filepath, nil -} diff --git a/staging/src/k8s.io/client-go/openapi/openapitest/fake_test.go b/staging/src/k8s.io/client-go/openapi/openapitest/fake_test.go deleted file mode 100644 index bda6fdd10bf..00000000000 --- a/staging/src/k8s.io/client-go/openapi/openapitest/fake_test.go +++ /dev/null @@ -1,168 +0,0 @@ -/* -Copyright 2023 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 openapitest - -import ( - "io/ioutil" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var openAPIV3SpecDir = "../../../../../../api/openapi-spec/v3" - -func TestFileOpenAPIClient_Paths(t *testing.T) { - // Directory with OpenAPI V3 spec files - tests := map[string]struct { - path string - found bool - }{ - "apps/v1 path exists": { - path: "apis/apps/v1", - found: true, - }, - "core/v1 path exists": { - path: "api/v1", - found: true, - }, - "batch/v1 path exists": { - path: "apis/batch/v1", - found: true, - }, - "networking/v1alpha1 path exists": { - path: "apis/networking.k8s.io/v1alpha1", - found: true, - }, - "discovery/v1 path exists": { - path: "apis/discovery.k8s.io/v1", - found: true, - }, - "fake path does not exists": { - path: "does/not/exist", - found: false, - }, - } - - fileClient := NewFileClient(openAPIV3SpecDir) - paths, err := fileClient.Paths() - require.NoError(t, err) - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - _, found := paths[tc.path] - if tc.found { - require.True(t, found) - } else { - require.False(t, found) - } - }) - } -} - -func TestFileOpenAPIClient_GroupVersions(t *testing.T) { - tests := map[string]struct { - path string - filename string - }{ - "apps/v1 groupversion spec validation": { - path: "apis/apps/v1", - filename: "apis__apps__v1_openapi.json", - }, - "core/v1 groupversion spec validation": { - path: "api/v1", - filename: "api__v1_openapi.json", - }, - "networking/v1alpha1 groupversion spec validation": { - path: "apis/networking.k8s.io/v1alpha1", - filename: "apis__networking.k8s.io__v1alpha1_openapi.json", - }, - } - - fileClient := NewFileClient(openAPIV3SpecDir) - paths, err := fileClient.Paths() - require.NoError(t, err) - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - gv, found := paths[tc.path] - require.True(t, found) - actualBytes, err := gv.Schema("application/json") - require.NoError(t, err) - expectedBytes, err := ioutil.ReadFile( - filepath.Join(openAPIV3SpecDir, tc.filename)) - require.NoError(t, err) - assert.Equal(t, expectedBytes, actualBytes) - }) - } -} - -func TestFileOpenAPIClient_apiFilePath(t *testing.T) { - tests := map[string]struct { - filename string - expected string - isError bool - }{ - "apps/v1 filename": { - filename: "apis__apps__v1_openapi.json", - expected: "apis/apps/v1", - }, - "core/v1 filename": { - filename: "api__v1_openapi.json", - expected: "api/v1", - }, - "logs filename": { - filename: "logs_openapi.json", - expected: "logs", - }, - "api filename": { - filename: "api_openapi.json", - expected: "api", - }, - "unversioned autoscaling filename": { - filename: "apis__autoscaling_openapi.json", - expected: "apis/autoscaling", - }, - "networking/v1alpha1 filename": { - filename: "apis__networking.k8s.io__v1alpha1_openapi.json", - expected: "apis/networking.k8s.io/v1alpha1", - }, - "batch/v1beta1 filename": { - filename: "apis__batch__v1beta1_openapi.json", - expected: "apis/batch/v1beta1", - }, - "non-JSON suffix is invalid": { - filename: "apis__networking.k8s.io__v1alpha1_openapi.yaml", - isError: true, - }, - "missing final openapi before suffix is invalid": { - filename: "apis__apps__v1_something.json", - isError: true, - }, - } - - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - actual, err := apiFilepath(tc.filename) - if !tc.isError { - require.NoError(t, err) - assert.Equal(t, tc.expected, actual) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/staging/src/k8s.io/kubectl/pkg/explain/v2/explain_test.go b/staging/src/k8s.io/kubectl/pkg/explain/v2/explain_test.go index da7bf38fce2..c69f3356b29 100644 --- a/staging/src/k8s.io/kubectl/pkg/explain/v2/explain_test.go +++ b/staging/src/k8s.io/kubectl/pkg/explain/v2/explain_test.go @@ -19,44 +19,118 @@ package v2 import ( "bytes" "encoding/json" - "fmt" + "errors" + "sync" "testing" "github.com/stretchr/testify/require" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/openapi" - "k8s.io/client-go/openapi/openapitest" ) -var apiGroupsPath = "apis/discovery.k8s.io/v1" - -var apiGroupsGVR = schema.GroupVersionResource{ +var apiDiscoveryJSON string = `{"openapi":"3.0.0","info":{"title":"Kubernetes","version":"v1.26.0"},"paths":{"/apis/discovery.k8s.io/":{"get":{"tags":["discovery"],"description":"get information of a group","operationId":"getDiscoveryAPIGroup","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.APIGroup"}},"application/vnd.kubernetes.protobuf":{"schema":{"$ref":"#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.APIGroup"}},"application/yaml":{"schema":{"$ref":"#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.APIGroup"}}}},"401":{"description":"Unauthorized"}}}}},"components":{"schemas":{"io.k8s.apimachinery.pkg.apis.meta.v1.APIGroup":{"description":"APIGroup contains the name, the supported versions, and the preferred version of a group.","type":"object","required":["name","versions"],"properties":{"apiVersion":{"description":"APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources","type":"string"},"kind":{"description":"Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds","type":"string"},"name":{"description":"name is the name of the group.","type":"string","default":""},"preferredVersion":{"description":"preferredVersion is the version preferred by the API server, which probably is the storage version.","default":{},"allOf":[{"$ref":"#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.GroupVersionForDiscovery"}]},"serverAddressByClientCIDRs":{"description":"a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.","type":"array","items":{"default":{},"allOf":[{"$ref":"#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ServerAddressByClientCIDR"}]}},"versions":{"description":"versions are the versions supported in this group.","type":"array","items":{"default":{},"allOf":[{"$ref":"#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.GroupVersionForDiscovery"}]}}},"x-kubernetes-group-version-kind":[{"group":"","kind":"APIGroup","version":"v1"}]},"io.k8s.apimachinery.pkg.apis.meta.v1.GroupVersionForDiscovery":{"description":"GroupVersion contains the \"group/version\" and \"version\" string of a version. It is made a struct to keep extensibility.","type":"object","required":["groupVersion","version"],"properties":{"groupVersion":{"description":"groupVersion specifies the API group and version in the form \"group/version\"","type":"string","default":""},"version":{"description":"version specifies the version in the form of \"version\". This is to save the clients the trouble of splitting the GroupVersion.","type":"string","default":""}}},"io.k8s.apimachinery.pkg.apis.meta.v1.ServerAddressByClientCIDR":{"description":"ServerAddressByClientCIDR helps the client to determine the server address that they should use, depending on the clientCIDR that they match.","type":"object","required":["clientCIDR","serverAddress"],"properties":{"clientCIDR":{"description":"The CIDR with which clients can match their IP to figure out the server address that they should use.","type":"string","default":""},"serverAddress":{"description":"Address of this server, suitable for a client that matches the above CIDR. This can be a hostname, hostname:port, IP or IP:port.","type":"string","default":""}}}},"securitySchemes":{"BearerToken":{"type":"apiKey","description":"Bearer Token authentication","name":"authorization","in":"header"}}}}` +var apiGroupsGVR schema.GroupVersionResource = schema.GroupVersionResource{ Group: "discovery.k8s.io", Version: "v1", Resource: "apigroups", } +var apiGroupsDocument map[string]interface{} = func() map[string]interface{} { + var doc map[string]interface{} -var openAPIV3SpecDir = "../../../../../../../api/openapi-spec/v3" + err := json.Unmarshal([]byte(apiDiscoveryJSON), &doc) + if err != nil { + panic(err) + } + + return doc +}() + +type FakeOpenAPIV3Client struct { + // Path: + // ContentType: + // OpenAPIV3 Schema bytes + Values map[string]map[string][]byte + FetchCounts map[string]map[string]int + lock sync.Mutex +} + +type FakeGroupVersion struct { + Data map[string][]byte + FetchCounts map[string]int + Lock *sync.Mutex +} + +func (f *FakeGroupVersion) Schema(contentType string) ([]byte, error) { + f.Lock.Lock() + defer f.Lock.Unlock() + + if count, ok := f.FetchCounts[contentType]; ok { + f.FetchCounts[contentType] = count + 1 + } else { + f.FetchCounts[contentType] = 1 + } + + data, ok := f.Data[contentType] + if !ok { + return nil, errors.New("not found") + } + return data, nil +} + +func (f *FakeOpenAPIV3Client) Paths() (map[string]openapi.GroupVersion, error) { + if f.Values == nil { + return nil, errors.New("values is nil") + } + + res := map[string]openapi.GroupVersion{} + if f.FetchCounts == nil { + f.FetchCounts = map[string]map[string]int{} + } + + for k, v := range f.Values { + counts, ok := f.FetchCounts[k] + if !ok { + counts = map[string]int{} + f.FetchCounts[k] = counts + } + res[k] = &FakeGroupVersion{Data: v, FetchCounts: counts, Lock: &f.lock} + } + return res, nil +} func TestExplainErrors(t *testing.T) { var buf bytes.Buffer - // Validate error when "Paths()" returns error. - err := PrintModelDescription(nil, &buf, &forceErrorClient{}, apiGroupsGVR, false, "unknown-format") + // A client with nil `Values` will return error on returning paths + failFetchPaths := &FakeOpenAPIV3Client{} + + err := PrintModelDescription(nil, &buf, failFetchPaths, apiGroupsGVR, false, "unknown-format") require.ErrorContains(t, err, "failed to fetch list of groupVersions") - // Validate error when GVR is not found in returned paths map. - emptyClient := &emptyPathsClient{} - err = PrintModelDescription(nil, &buf, emptyClient, schema.GroupVersionResource{ + // Missing Schema + fakeClient := &FakeOpenAPIV3Client{ + Values: map[string]map[string][]byte{ + "apis/test1.example.com/v1": { + "unknown/content-type": []byte(apiDiscoveryJSON), + }, + "apis/test2.example.com/v1": { + runtime.ContentTypeJSON: []byte(``), + }, + "apis/discovery.k8s.io/v1": { + runtime.ContentTypeJSON: []byte(apiDiscoveryJSON), + }, + }, + } + + err = PrintModelDescription(nil, &buf, fakeClient, schema.GroupVersionResource{ Group: "test0.example.com", Version: "v1", Resource: "doesntmatter", }, false, "unknown-format") require.ErrorContains(t, err, "could not locate schema") - // Validate error when GroupVersion "Schema()" call returns error. - fakeClient := &fakeOpenAPIClient{values: make(map[string]openapi.GroupVersion)} - fakeClient.values["apis/test1.example.com/v1"] = &forceErrorGV{} + // Missing JSON err = PrintModelDescription(nil, &buf, fakeClient, schema.GroupVersionResource{ Group: "test1.example.com", Version: "v1", @@ -64,8 +138,6 @@ func TestExplainErrors(t *testing.T) { }, false, "unknown-format") require.ErrorContains(t, err, "failed to fetch openapi schema ") - // Validate error when returned bytes from GroupVersion "Schema" are invalid. - fakeClient.values["apis/test2.example.com/v1"] = &parseErrorGV{} err = PrintModelDescription(nil, &buf, fakeClient, schema.GroupVersionResource{ Group: "test2.example.com", Version: "v1", @@ -73,9 +145,7 @@ func TestExplainErrors(t *testing.T) { }, false, "unknown-format") require.ErrorContains(t, err, "failed to parse openapi schema") - // Validate error when render template is not recognized. - client := openapitest.NewFileClient(openAPIV3SpecDir) - err = PrintModelDescription(nil, &buf, client, apiGroupsGVR, false, "unknown-format") + err = PrintModelDescription(nil, &buf, fakeClient, apiGroupsGVR, false, "unknown-format") require.ErrorContains(t, err, "unrecognized format: unknown-format") } @@ -84,71 +154,31 @@ func TestExplainErrors(t *testing.T) { func TestExplainOpenAPIClient(t *testing.T) { var buf bytes.Buffer - fileClient := openapitest.NewFileClient(openAPIV3SpecDir) - paths, err := fileClient.Paths() - require.NoError(t, err) - gv, found := paths[apiGroupsPath] - require.True(t, found) - discoveryBytes, err := gv.Schema("application/json") - require.NoError(t, err) - - var doc map[string]interface{} - err = json.Unmarshal(discoveryBytes, &doc) - require.NoError(t, err) + fakeClient := &FakeOpenAPIV3Client{ + Values: map[string]map[string][]byte{ + "apis/discovery.k8s.io/v1": { + runtime.ContentTypeJSON: []byte(apiDiscoveryJSON), + }, + }, + } gen := NewGenerator() - err = gen.AddTemplate("Context", "{{ toJson . }}") + err := gen.AddTemplate("Context", "{{ toJson . }}") require.NoError(t, err) expectedContext := TemplateContext{ - Document: doc, + Document: apiGroupsDocument, GVR: apiGroupsGVR, Recursive: false, FieldPath: nil, } - err = printModelDescriptionWithGenerator(gen, nil, &buf, fileClient, apiGroupsGVR, false, "Context") + err = printModelDescriptionWithGenerator(gen, nil, &buf, fakeClient, apiGroupsGVR, false, "Context") require.NoError(t, err) var actualContext TemplateContext err = json.Unmarshal(buf.Bytes(), &actualContext) require.NoError(t, err) require.Equal(t, expectedContext, actualContext) -} - -// forceErrorClient always returns an error for "Paths()". -type forceErrorClient struct{} - -func (f *forceErrorClient) Paths() (map[string]openapi.GroupVersion, error) { - return nil, fmt.Errorf("Always fails") -} - -// emptyPathsClient returns an empty map for "Paths()". -type emptyPathsClient struct{} - -func (f *emptyPathsClient) Paths() (map[string]openapi.GroupVersion, error) { - return map[string]openapi.GroupVersion{}, nil -} - -// fakeOpenAPIClient returns hard-coded map for "Paths()". -type fakeOpenAPIClient struct { - values map[string]openapi.GroupVersion -} - -func (f *fakeOpenAPIClient) Paths() (map[string]openapi.GroupVersion, error) { - return f.values, nil -} - -// forceErrorGV always returns an error for "Schema()". -type forceErrorGV struct{} - -func (f *forceErrorGV) Schema(contentType string) ([]byte, error) { - return nil, fmt.Errorf("Always fails") -} - -// parseErrorGV always returns invalid JSON for "Schema()". -type parseErrorGV struct{} - -func (f *parseErrorGV) Schema(contentType string) ([]byte, error) { - return []byte(``), nil + require.Equal(t, fakeClient.FetchCounts["apis/discovery.k8s.io/v1"][runtime.ContentTypeJSON], 1) } diff --git a/staging/src/k8s.io/kubectl/pkg/explain/v2/generator_test.go b/staging/src/k8s.io/kubectl/pkg/explain/v2/generator_test.go index c31f928b1e4..ab0e892ecc1 100644 --- a/staging/src/k8s.io/kubectl/pkg/explain/v2/generator_test.go +++ b/staging/src/k8s.io/kubectl/pkg/explain/v2/generator_test.go @@ -22,31 +22,20 @@ import ( "testing" "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/client-go/openapi/openapitest" ) -var appsv1Path = "apis/apps/v1" - -var appsDeploymentGVR = schema.GroupVersionResource{ - Group: "apps", - Version: "v1", - Resource: "deployments", -} - // Shows generic throws error when attempting to `Render“ an invalid output name // And if it is then added as a template, no error is thrown upon `Render` func TestGeneratorMissingOutput(t *testing.T) { var buf bytes.Buffer var doc map[string]interface{} - appsv1Bytes := bytesForGV(t, appsv1Path) - err := json.Unmarshal(appsv1Bytes, &doc) + err := json.Unmarshal([]byte(apiDiscoveryJSON), &doc) require.NoError(t, err) gen := NewGenerator() badTemplateName := "bad-template" - err = gen.Render(badTemplateName, doc, appsDeploymentGVR, nil, false, &buf) + err = gen.Render(badTemplateName, doc, apiGroupsGVR, nil, false, &buf) require.ErrorContains(t, err, "unrecognized format: "+badTemplateName) require.Zero(t, buf.Len()) @@ -54,7 +43,7 @@ func TestGeneratorMissingOutput(t *testing.T) { err = gen.AddTemplate(badTemplateName, "ok") require.NoError(t, err) - err = gen.Render(badTemplateName, doc, appsDeploymentGVR, nil, false, &buf) + err = gen.Render(badTemplateName, doc, apiGroupsGVR, nil, false, &buf) require.NoError(t, err) require.Equal(t, "ok", buf.String()) } @@ -64,8 +53,7 @@ func TestGeneratorContext(t *testing.T) { var buf bytes.Buffer var doc map[string]interface{} - appsv1Bytes := bytesForGV(t, appsv1Path) - err := json.Unmarshal(appsv1Bytes, &doc) + err := json.Unmarshal([]byte(apiDiscoveryJSON), &doc) require.NoError(t, err) gen := NewGenerator() @@ -74,7 +62,7 @@ func TestGeneratorContext(t *testing.T) { expectedContext := TemplateContext{ Document: doc, - GVR: appsDeploymentGVR, + GVR: apiGroupsGVR, Recursive: false, FieldPath: nil, } @@ -92,23 +80,3 @@ func TestGeneratorContext(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedContext, actualContext) } - -// bytesForGV returns the OpenAPI V3 spec for the passed -// group/version as a byte slice. Assumes bytes are in json -// format. The passed path string looks like: -// -// apis/apps/v1 -// -// Obtains bytes from OpenAPI V3 files at: -// -// /api/openapi-spec/v3 -func bytesForGV(t *testing.T, gvPath string) []byte { - fakeClient := openapitest.NewFileClient(openAPIV3SpecDir) - paths, err := fakeClient.Paths() - require.NoError(t, err) - gv, found := paths[gvPath] - require.True(t, found) - gvBytes, err := gv.Schema("application/json") - require.NoError(t, err) - return gvBytes -}