// Copyright 2017 Istio 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 config

import (
	"strconv"
	"strings"
	"testing"
)

func TestKinds(t *testing.T) {
	i := 0
	for k := range kindToString {
		str := k.String()
		kind, ok := ParseKind(str)

		if !ok {
			t.Error("Got !ok, expecting true")
		}

		if kind != k {
			t.Errorf("%d: Got %v, expected %v", i, kind, k)
		}
		i++
	}
}

func TestKindSetString(t *testing.T) {
	tests := []struct {
		ks KindSet
		// We can't expect an exact output string because KindSet.String() is generated by iterating over a map;
		// map iteration order is unspecified so the exact output string can vary over runs. Instead we make sure
		// it has the major elements we're looking for and has the correct length.
		expect []string
	}{
		{KindSet(0), []string{""}},
		{KindSet(0).Set(QuotasKind), []string{"quotas"}},
		{KindSet(0).Set(QuotasKind).Set(AttributesKind), []string{"quotas", "attributes"}},
	}

	for idx, tt := range tests {
		t.Run(strconv.Itoa(idx), func(t *testing.T) {
			out := tt.ks.String()
			expectedLength := 0
			for _, expected := range tt.expect {
				// 2 for the ', ' following each entry; we trim off two chars at the end to account for the braces,
				// so all the math works out.
				expectedLength += len(expected) + 2
				if !strings.Contains(out, expected) {
					t.Errorf("tt.ks.String() = %s, expected to contain %s", out, expected)
				}
			}

			if len(out) != expectedLength {
				t.Fatalf("tt.ks.String() has unexpected format: wanted a string %d chars long, got %d", expectedLength, len(out))
			}
		})
	}
}
