// Copyright Project Contour 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 k8s

import (
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/restmapper"

	"github.com/stretchr/testify/assert"
)

func TestResourceKindExists(t *testing.T) {
	// The following resources were generated by dumping the result
	// of restmapper.GetAPIGroupResources().
	r := &restmapper.APIGroupResources{
		Group: metav1.APIGroup{
			Name: "networking.k8s.io",
			Versions: []metav1.GroupVersionForDiscovery{
				{
					GroupVersion: "networking.k8s.io/v1",
					Version:      "v1",
				},
			},
		},
		VersionedResources: map[string][]metav1.APIResource{
			"v1": {
				{
					Name:               "ingressclasses",
					Namespaced:         false,
					Kind:               "IngressClass",
					Verbs:              metav1.Verbs{"create", "delete", "deletecollection", "get", "list", "patch", "update", "watch"},
					StorageVersionHash: "6upRfBq0FOI=",
				},
				{
					Name:               "ingresses",
					Namespaced:         true,
					Kind:               "Ingress",
					Verbs:              metav1.Verbs{"create", "delete", "deletecollection", "get", "list", "patch", "update", "watch"},
					ShortNames:         []string{"ing"},
					StorageVersionHash: "ZOAfGflaKd0=",
				},
				{
					Name:       "ingresses/status",
					Namespaced: true,
					Kind:       "Ingress",
					Verbs:      metav1.Verbs{"get", "patch", "update"},
				},
			},
		},
	}

	mapper := restmapper.NewDiscoveryRESTMapper([]*restmapper.APIGroupResources{r})

	clients := &Clients{
		RESTMapper: mapper,
	}

	valid := schema.GroupVersionResource{
		Group:    "networking.k8s.io",
		Version:  "v1",
		Resource: "ingress",
	}

	invalid := schema.GroupVersionResource{
		Group:    "networking.k8s.io",
		Version:  "v1",
		Resource: "phony",
	}

	assert.True(t, clients.ResourcesExist(valid), "v1 ingress exists")
	assert.False(t, clients.ResourcesExist(invalid), "v1 phony exists")
	assert.False(t, clients.ResourcesExist(valid, valid, invalid), "v1 phony exists")
}
