Update go dependencies

This commit is contained in:
Manuel de Brito Fontes 2018-05-26 11:27:53 -04:00 committed by Manuel Alejandro de Brito Fontes
parent 15ffb51394
commit bb4d483837
No known key found for this signature in database
GPG key ID: 786136016A8BA02A
1621 changed files with 86368 additions and 284392 deletions

View file

@ -1,26 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["interfaces.go"],
importpath = "k8s.io/apiserver/pkg/authentication/authenticator",
deps = ["//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -1,33 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["util_test.go"],
embed = [":go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["util.go"],
importpath = "k8s.io/apiserver/pkg/authentication/serviceaccount",
deps = ["//vendor/k8s.io/apimachinery/pkg/api/validation:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -1,82 +0,0 @@
/*
Copyright 2014 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 serviceaccount
import "testing"
func TestMakeUsername(t *testing.T) {
testCases := map[string]struct {
Namespace string
Name string
ExpectedErr bool
}{
"valid": {
Namespace: "foo",
Name: "bar",
ExpectedErr: false,
},
"empty": {
ExpectedErr: true,
},
"empty namespace": {
Namespace: "",
Name: "foo",
ExpectedErr: true,
},
"empty name": {
Namespace: "foo",
Name: "",
ExpectedErr: true,
},
"extra segments": {
Namespace: "foo",
Name: "bar:baz",
ExpectedErr: true,
},
"invalid chars in namespace": {
Namespace: "foo ",
Name: "bar",
ExpectedErr: true,
},
"invalid chars in name": {
Namespace: "foo",
Name: "bar ",
ExpectedErr: true,
},
}
for k, tc := range testCases {
username := MakeUsername(tc.Namespace, tc.Name)
namespace, name, err := SplitUsername(username)
if (err != nil) != tc.ExpectedErr {
t.Errorf("%s: Expected error=%v, got %v", k, tc.ExpectedErr, err)
continue
}
if err != nil {
continue
}
if namespace != tc.Namespace {
t.Errorf("%s: Expected namespace %q, got %q", k, tc.Namespace, namespace)
}
if name != tc.Name {
t.Errorf("%s: Expected name %q, got %q", k, tc.Name, name)
}
}
}

View file

@ -1,28 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"user.go",
],
importpath = "k8s.io/apiserver/pkg/authentication/user",
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -1,26 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["kube_features.go"],
importpath = "k8s.io/apiserver/pkg/features",
deps = ["//vendor/k8s.io/apiserver/pkg/util/feature:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -1,172 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = [
"config_selfclient_test.go",
"config_test.go",
"genericapiserver_test.go",
],
embed = [":go_default_library"],
deps = [
"//vendor/github.com/stretchr/testify/assert:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apimachinery:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/version:go_default_library",
"//vendor/k8s.io/apiserver/pkg/apis/example:go_default_library",
"//vendor/k8s.io/apiserver/pkg/apis/example/v1:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authorization/authorizer:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/discovery:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/filters:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/filters:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/healthz:go_default_library",
"//vendor/k8s.io/client-go/informers:go_default_library",
"//vendor/k8s.io/client-go/kubernetes/fake:go_default_library",
"//vendor/k8s.io/client-go/rest:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"config.go",
"config_selfclient.go",
"doc.go",
"genericapiserver.go",
"handler.go",
"healthz.go",
"hooks.go",
"plugins.go",
"serve.go",
"signal.go",
] + select({
"@io_bazel_rules_go//go/platform:android": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:darwin": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:dragonfly": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:freebsd": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:linux": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:nacl": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:netbsd": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:openbsd": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:plan9": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:solaris": [
"signal_posix.go",
],
"@io_bazel_rules_go//go/platform:windows": [
"signal_windows.go",
],
"//conditions:default": [],
}),
importpath = "k8s.io/apiserver/pkg/server",
deps = [
"//vendor/github.com/coreos/go-systemd/daemon:go_default_library",
"//vendor/github.com/emicklei/go-restful:go_default_library",
"//vendor/github.com/emicklei/go-restful-swagger12:go_default_library",
"//vendor/github.com/go-openapi/spec:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/github.com/pborman/uuid:go_default_library",
"//vendor/golang.org/x/net/http2:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apimachinery:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apimachinery/registered:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/validation:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/waitgroup:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/version:go_default_library",
"//vendor/k8s.io/apiserver/pkg/admission:go_default_library",
"//vendor/k8s.io/apiserver/pkg/admission/plugin/initialization:go_default_library",
"//vendor/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle:go_default_library",
"//vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating:go_default_library",
"//vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/validating:go_default_library",
"//vendor/k8s.io/apiserver/pkg/apis/apiserver/install:go_default_library",
"//vendor/k8s.io/apiserver/pkg/audit:go_default_library",
"//vendor/k8s.io/apiserver/pkg/audit/policy:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/authenticator:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/authenticatorfactory:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/request/union:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authorization/authorizer:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authorization/authorizerfactory:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authorization/union:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/discovery:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/filters:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/openapi:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library",
"//vendor/k8s.io/apiserver/pkg/features:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/filters:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/healthz:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/mux:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/routes:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/storage:go_default_library",
"//vendor/k8s.io/apiserver/pkg/util/feature:go_default_library",
"//vendor/k8s.io/client-go/informers:go_default_library",
"//vendor/k8s.io/client-go/rest:go_default_library",
"//vendor/k8s.io/client-go/util/cert:go_default_library",
"//vendor/k8s.io/kube-openapi/pkg/common:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/filters:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/healthz:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/httplog:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/mux:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/options:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/resourceconfig:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/routes:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/server/storage:all-srcs",
],
tags = ["automanaged"],
)

View file

@ -1,68 +0,0 @@
/*
Copyright 2016 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 server
import (
"net"
"testing"
)
func TestLoopbackHostPort(t *testing.T) {
host, port, err := LoopbackHostPort("1.2.3.4:443")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if host != "1.2.3.4" {
t.Fatalf("expected 1.2.3.4 as host, got %q", host)
}
if port != "443" {
t.Fatalf("expected 443 as port, got %q", port)
}
host, port, err = LoopbackHostPort("0.0.0.0:443")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
t.Fatalf("expected host to be loopback, got %q", host)
}
if port != "443" {
t.Fatalf("expected 443 as port, got %q", port)
}
host, port, err = LoopbackHostPort("[ff06:0:0:0:0:0:0:c3]:443")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if host != "ff06:0:0:0:0:0:0:c3" {
t.Fatalf("expected ff06:0:0:0:0:0:0:c3 as host, got %q", host)
}
if port != "443" {
t.Fatalf("expected 443 as port, got %q", port)
}
host, port, err = LoopbackHostPort("[::]:443")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
t.Fatalf("expected host to be loopback, got %q", host)
}
if port != "443" {
t.Fatalf("expected 443 as port, got %q", port)
}
}

View file

@ -1,153 +0,0 @@
/*
Copyright 2017 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 server
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"testing"
"k8s.io/apimachinery/pkg/util/sets"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/rest"
)
func TestNewWithDelegate(t *testing.T) {
delegateConfig := NewConfig(codecs)
delegateConfig.PublicAddress = net.ParseIP("192.168.10.4")
delegateConfig.RequestContextMapper = genericapirequest.NewRequestContextMapper()
delegateConfig.LegacyAPIGroupPrefixes = sets.NewString("/api")
delegateConfig.LoopbackClientConfig = &rest.Config{}
delegateConfig.SwaggerConfig = DefaultSwaggerConfig()
clientset := fake.NewSimpleClientset()
if clientset == nil {
t.Fatal("unable to create fake client set")
}
delegateConfig.HealthzChecks = append(delegateConfig.HealthzChecks, healthz.NamedCheck("delegate-health", func(r *http.Request) error {
return fmt.Errorf("delegate failed healthcheck")
}))
sharedInformers := informers.NewSharedInformerFactory(clientset, delegateConfig.LoopbackClientConfig.Timeout)
delegateServer, err := delegateConfig.Complete(sharedInformers).New("test", EmptyDelegate)
if err != nil {
t.Fatal(err)
}
delegateServer.Handler.NonGoRestfulMux.HandleFunc("/foo", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
})
delegateServer.AddPostStartHook("delegate-post-start-hook", func(context PostStartHookContext) error {
return nil
})
// this wires up swagger
delegateServer.PrepareRun()
wrappingConfig := NewConfig(codecs)
wrappingConfig.PublicAddress = net.ParseIP("192.168.10.4")
wrappingConfig.RequestContextMapper = genericapirequest.NewRequestContextMapper()
wrappingConfig.LegacyAPIGroupPrefixes = sets.NewString("/api")
wrappingConfig.LoopbackClientConfig = &rest.Config{}
wrappingConfig.SwaggerConfig = DefaultSwaggerConfig()
wrappingConfig.HealthzChecks = append(wrappingConfig.HealthzChecks, healthz.NamedCheck("wrapping-health", func(r *http.Request) error {
return fmt.Errorf("wrapping failed healthcheck")
}))
sharedInformers = informers.NewSharedInformerFactory(clientset, wrappingConfig.LoopbackClientConfig.Timeout)
wrappingServer, err := wrappingConfig.Complete(sharedInformers).New("test", delegateServer)
if err != nil {
t.Fatal(err)
}
wrappingServer.Handler.NonGoRestfulMux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
})
wrappingServer.AddPostStartHook("wrapping-post-start-hook", func(context PostStartHookContext) error {
return nil
})
stopCh := make(chan struct{})
defer close(stopCh)
wrappingServer.PrepareRun()
wrappingServer.RunPostStartHooks(stopCh)
server := httptest.NewServer(wrappingServer.Handler)
defer server.Close()
checkPath(server.URL, http.StatusOK, `{
"paths": [
"/apis",
"/bar",
"/foo",
"/healthz",
"/healthz/delegate-health",
"/healthz/ping",
"/healthz/poststarthook/delegate-post-start-hook",
"/healthz/poststarthook/generic-apiserver-start-informers",
"/healthz/poststarthook/wrapping-post-start-hook",
"/healthz/wrapping-health",
"/swaggerapi"
]
}`, t)
checkPath(server.URL+"/healthz", http.StatusInternalServerError, `[+]ping ok
[-]wrapping-health failed: reason withheld
[-]delegate-health failed: reason withheld
[+]poststarthook/generic-apiserver-start-informers ok
[+]poststarthook/delegate-post-start-hook ok
[+]poststarthook/wrapping-post-start-hook ok
healthz check failed
`, t)
checkPath(server.URL+"/healthz/delegate-health", http.StatusInternalServerError, `internal server error: delegate failed healthcheck
`, t)
checkPath(server.URL+"/healthz/wrapping-health", http.StatusInternalServerError, `internal server error: wrapping failed healthcheck
`, t)
checkPath(server.URL+"/healthz/poststarthook/delegate-post-start-hook", http.StatusOK, `ok`, t)
checkPath(server.URL+"/healthz/poststarthook/wrapping-post-start-hook", http.StatusOK, `ok`, t)
checkPath(server.URL+"/foo", http.StatusForbidden, ``, t)
checkPath(server.URL+"/bar", http.StatusUnauthorized, ``, t)
}
func checkPath(url string, expectedStatusCode int, expectedBody string, t *testing.T) {
resp, err := http.Get(url)
if err != nil {
t.Fatal(err)
}
dump, _ := httputil.DumpResponse(resp, true)
t.Log(string(dump))
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if e, a := expectedBody, string(body); e != a {
t.Errorf("%q expected %v, got %v", url, e, a)
}
if e, a := expectedStatusCode, resp.StatusCode; e != a {
t.Errorf("%q expected %v, got %v", url, e, a)
}
}

View file

@ -1,581 +0,0 @@
/*
Copyright 2015 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 server
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
goruntime "runtime"
"strconv"
"sync"
"testing"
"time"
// "github.com/go-openapi/spec"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apimachinery"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/version"
"k8s.io/apiserver/pkg/apis/example"
examplev1 "k8s.io/apiserver/pkg/apis/example/v1"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/apiserver/pkg/endpoints/discovery"
genericapifilters "k8s.io/apiserver/pkg/endpoints/filters"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
genericfilters "k8s.io/apiserver/pkg/server/filters"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes/fake"
restclient "k8s.io/client-go/rest"
)
const (
extensionsGroupName = "extensions"
)
var (
v1GroupVersion = schema.GroupVersion{Group: "", Version: "v1"}
scheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(scheme)
parameterCodec = runtime.NewParameterCodec(scheme)
)
func init() {
metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion)
scheme.AddUnversionedTypes(v1GroupVersion,
&metav1.Status{},
&metav1.APIVersions{},
&metav1.APIGroupList{},
&metav1.APIGroup{},
&metav1.APIResourceList{},
)
example.AddToScheme(scheme)
examplev1.AddToScheme(scheme)
}
// setUp is a convience function for setting up for (most) tests.
func setUp(t *testing.T) (Config, *assert.Assertions) {
config := NewConfig(codecs)
config.PublicAddress = net.ParseIP("192.168.10.4")
config.RequestContextMapper = apirequest.NewRequestContextMapper()
config.LegacyAPIGroupPrefixes = sets.NewString("/api")
config.LoopbackClientConfig = &restclient.Config{}
clientset := fake.NewSimpleClientset()
if clientset == nil {
t.Fatal("unable to create fake client set")
}
// TODO restore this test, but right now, eliminate our cycle
// config.OpenAPIConfig = DefaultOpenAPIConfig(testGetOpenAPIDefinitions, runtime.NewScheme())
// config.OpenAPIConfig.Info = &spec.Info{
// InfoProps: spec.InfoProps{
// Title: "Kubernetes",
// Version: "unversioned",
// },
// }
config.SwaggerConfig = DefaultSwaggerConfig()
sharedInformers := informers.NewSharedInformerFactory(clientset, config.LoopbackClientConfig.Timeout)
config.Complete(sharedInformers)
return *config, assert.New(t)
}
func newMaster(t *testing.T) (*GenericAPIServer, Config, *assert.Assertions) {
config, assert := setUp(t)
s, err := config.Complete(nil).New("test", EmptyDelegate)
if err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}
return s, config, assert
}
// TestNew verifies that the New function returns a GenericAPIServer
// using the configuration properly.
func TestNew(t *testing.T) {
s, config, assert := newMaster(t)
// Verify many of the variables match their config counterparts
assert.Equal(s.legacyAPIGroupPrefixes, config.LegacyAPIGroupPrefixes)
assert.Equal(s.admissionControl, config.AdmissionControl)
assert.Equal(s.RequestContextMapper(), config.RequestContextMapper)
// these values get defaulted
assert.Equal(net.JoinHostPort(config.PublicAddress.String(), "443"), s.ExternalAddress)
assert.NotNil(s.swaggerConfig)
assert.Equal("http://"+s.ExternalAddress, s.swaggerConfig.WebServicesUrl)
}
// Verifies that AddGroupVersions works as expected.
func TestInstallAPIGroups(t *testing.T) {
config, assert := setUp(t)
config.LegacyAPIGroupPrefixes = sets.NewString("/apiPrefix")
config.DiscoveryAddresses = discovery.DefaultAddresses{DefaultAddress: "ExternalAddress"}
s, err := config.Complete(nil).New("test", EmptyDelegate)
if err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}
testAPI := func(gv schema.GroupVersion) APIGroupInfo {
getter, noVerbs := testGetterStorage{}, testNoVerbsStorage{}
scheme := runtime.NewScheme()
scheme.AddKnownTypeWithName(gv.WithKind("Getter"), getter.New())
scheme.AddKnownTypeWithName(gv.WithKind("NoVerb"), noVerbs.New())
scheme.AddKnownTypes(v1GroupVersion, &metav1.Status{})
metav1.AddToGroupVersion(scheme, v1GroupVersion)
interfacesFor := func(version schema.GroupVersion) (*meta.VersionInterfaces, error) {
return &meta.VersionInterfaces{
ObjectConvertor: scheme,
MetadataAccessor: meta.NewAccessor(),
}, nil
}
mapper := meta.NewDefaultRESTMapper([]schema.GroupVersion{gv}, interfacesFor)
for kind := range scheme.KnownTypes(gv) {
mapper.Add(gv.WithKind(kind), meta.RESTScopeNamespace)
}
groupMeta := apimachinery.GroupMeta{
GroupVersion: gv,
GroupVersions: []schema.GroupVersion{gv},
RESTMapper: mapper,
InterfacesFor: interfacesFor,
}
return APIGroupInfo{
GroupMeta: groupMeta,
VersionedResourcesStorageMap: map[string]map[string]rest.Storage{
gv.Version: {
"getter": &testGetterStorage{Version: gv.Version},
"noverbs": &testNoVerbsStorage{Version: gv.Version},
},
},
OptionsExternalVersion: &schema.GroupVersion{Version: "v1"},
ParameterCodec: parameterCodec,
NegotiatedSerializer: codecs,
Scheme: scheme,
}
}
apis := []APIGroupInfo{
testAPI(schema.GroupVersion{Group: "", Version: "v1"}),
testAPI(schema.GroupVersion{Group: extensionsGroupName, Version: "v1"}),
testAPI(schema.GroupVersion{Group: "batch", Version: "v1"}),
}
err = s.InstallLegacyAPIGroup("/apiPrefix", &apis[0])
assert.NoError(err)
groupPaths := []string{
config.LegacyAPIGroupPrefixes.List()[0], // /apiPrefix
}
for _, api := range apis[1:] {
err = s.InstallAPIGroup(&api)
assert.NoError(err)
groupPaths = append(groupPaths, APIGroupPrefix+"/"+api.GroupMeta.GroupVersion.Group) // /apis/<group>
}
server := httptest.NewServer(s.Handler)
defer server.Close()
for i := range apis {
// should serve APIGroup at group path
info := &apis[i]
path := groupPaths[i]
resp, err := http.Get(server.URL + path)
if err != nil {
t.Errorf("[%d] unexpected error getting path %q path: %v", i, path, err)
continue
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("[%d] unexpected error reading body at path %q: %v", i, path, err)
continue
}
t.Logf("[%d] json at %s: %s", i, path, string(body))
if i == 0 {
// legacy API returns APIVersions
group := metav1.APIVersions{}
err = json.Unmarshal(body, &group)
if err != nil {
t.Errorf("[%d] unexpected error parsing json body at path %q: %v", i, path, err)
continue
}
} else {
// API groups return APIGroup
group := metav1.APIGroup{}
err = json.Unmarshal(body, &group)
if err != nil {
t.Errorf("[%d] unexpected error parsing json body at path %q: %v", i, path, err)
continue
}
if got, expected := group.Name, info.GroupMeta.GroupVersion.Group; got != expected {
t.Errorf("[%d] unexpected group name at path %q: got=%q expected=%q", i, path, got, expected)
continue
}
if got, expected := group.PreferredVersion.Version, info.GroupMeta.GroupVersion.Version; got != expected {
t.Errorf("[%d] unexpected group version at path %q: got=%q expected=%q", i, path, got, expected)
continue
}
}
// should serve APIResourceList at group path + /<group-version>
path = path + "/" + info.GroupMeta.GroupVersion.Version
resp, err = http.Get(server.URL + path)
if err != nil {
t.Errorf("[%d] unexpected error getting path %q path: %v", i, path, err)
continue
}
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("[%d] unexpected error reading body at path %q: %v", i, path, err)
continue
}
t.Logf("[%d] json at %s: %s", i, path, string(body))
resources := metav1.APIResourceList{}
err = json.Unmarshal(body, &resources)
if err != nil {
t.Errorf("[%d] unexpected error parsing json body at path %q: %v", i, path, err)
continue
}
if got, expected := resources.GroupVersion, info.GroupMeta.GroupVersion.String(); got != expected {
t.Errorf("[%d] unexpected groupVersion at path %q: got=%q expected=%q", i, path, got, expected)
continue
}
// the verbs should match the features of resources
for _, r := range resources.APIResources {
switch r.Name {
case "getter":
if got, expected := sets.NewString([]string(r.Verbs)...), sets.NewString("get"); !got.Equal(expected) {
t.Errorf("[%d] unexpected verbs for resource %s/%s: got=%v expected=%v", i, resources.GroupVersion, r.Name, got, expected)
}
case "noverbs":
if r.Verbs == nil {
t.Errorf("[%d] unexpected nil verbs slice. Expected: []string{}", i)
}
if got, expected := sets.NewString([]string(r.Verbs)...), sets.NewString(); !got.Equal(expected) {
t.Errorf("[%d] unexpected verbs for resource %s/%s: got=%v expected=%v", i, resources.GroupVersion, r.Name, got, expected)
}
}
}
}
}
func TestPrepareRun(t *testing.T) {
s, config, assert := newMaster(t)
assert.NotNil(config.SwaggerConfig)
server := httptest.NewServer(s.Handler.Director)
defer server.Close()
done := make(chan struct{})
s.PrepareRun()
s.RunPostStartHooks(done)
// swagger is installed in PrepareRun
resp, err := http.Get(server.URL + "/swaggerapi/")
assert.NoError(err)
assert.Equal(http.StatusOK, resp.StatusCode)
// healthz checks are installed in PrepareRun
resp, err = http.Get(server.URL + "/healthz")
assert.NoError(err)
assert.Equal(http.StatusOK, resp.StatusCode)
resp, err = http.Get(server.URL + "/healthz/ping")
assert.NoError(err)
assert.Equal(http.StatusOK, resp.StatusCode)
}
// TestCustomHandlerChain verifies the handler chain with custom handler chain builder functions.
func TestCustomHandlerChain(t *testing.T) {
config, _ := setUp(t)
var protected, called bool
config.BuildHandlerChainFunc = func(apiHandler http.Handler, c *Config) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
protected = true
apiHandler.ServeHTTP(w, req)
})
}
handler := http.HandlerFunc(func(r http.ResponseWriter, req *http.Request) {
called = true
})
s, err := config.Complete(nil).New("test", EmptyDelegate)
if err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}
s.Handler.NonGoRestfulMux.Handle("/nonswagger", handler)
s.Handler.NonGoRestfulMux.Handle("/secret", handler)
type Test struct {
handler http.Handler
path string
protected bool
}
for i, test := range []Test{
{s.Handler, "/nonswagger", true},
{s.Handler, "/secret", true},
} {
protected, called = false, false
var w io.Reader
req, err := http.NewRequest("GET", test.path, w)
if err != nil {
t.Errorf("%d: Unexpected http error: %v", i, err)
continue
}
test.handler.ServeHTTP(httptest.NewRecorder(), req)
if !called {
t.Errorf("%d: Expected handler to be called.", i)
}
if test.protected != protected {
t.Errorf("%d: Expected protected=%v, got protected=%v.", i, test.protected, protected)
}
}
}
// TestNotRestRoutesHaveAuth checks that special non-routes are behind authz/authn.
func TestNotRestRoutesHaveAuth(t *testing.T) {
config, _ := setUp(t)
authz := mockAuthorizer{}
config.LegacyAPIGroupPrefixes = sets.NewString("/apiPrefix")
config.Authorization.Authorizer = &authz
config.EnableSwaggerUI = true
config.EnableIndex = true
config.EnableProfiling = true
config.SwaggerConfig = DefaultSwaggerConfig()
kubeVersion := fakeVersion()
config.Version = &kubeVersion
s, err := config.Complete(nil).New("test", EmptyDelegate)
if err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}
for _, test := range []struct {
route string
}{
{"/"},
{"/swagger-ui/"},
{"/debug/pprof/"},
{"/version"},
} {
resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", test.route, nil)
s.Handler.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("route %q expected to work: code %d", test.route, resp.Code)
continue
}
if authz.lastURI != test.route {
t.Errorf("route %q expected to go through authorization, last route did: %q", test.route, authz.lastURI)
}
}
}
type mockAuthorizer struct {
lastURI string
}
func (authz *mockAuthorizer) Authorize(a authorizer.Attributes) (authorized authorizer.Decision, reason string, err error) {
authz.lastURI = a.GetPath()
return authorizer.DecisionAllow, "", nil
}
type mockAuthenticator struct {
lastURI string
}
func (authn *mockAuthenticator) AuthenticateRequest(req *http.Request) (user.Info, bool, error) {
authn.lastURI = req.RequestURI
return &user.DefaultInfo{
Name: "foo",
}, true, nil
}
func decodeResponse(resp *http.Response, obj interface{}) error {
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err := json.Unmarshal(data, obj); err != nil {
return err
}
return nil
}
type testGetterStorage struct {
Version string
}
func (p *testGetterStorage) New() runtime.Object {
return &metav1.APIGroup{
TypeMeta: metav1.TypeMeta{
Kind: "Getter",
APIVersion: p.Version,
},
}
}
func (p *testGetterStorage) Get(ctx apirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
return nil, nil
}
type testNoVerbsStorage struct {
Version string
}
func (p *testNoVerbsStorage) New() runtime.Object {
return &metav1.APIGroup{
TypeMeta: metav1.TypeMeta{
Kind: "NoVerbs",
APIVersion: p.Version,
},
}
}
func fakeVersion() version.Info {
return version.Info{
Major: "42",
Minor: "42",
GitVersion: "42",
GitCommit: "34973274ccef6ab4dfaaf86599792fa9c3fe4689",
GitTreeState: "Dirty",
BuildDate: time.Now().String(),
GoVersion: goruntime.Version(),
Compiler: goruntime.Compiler,
Platform: fmt.Sprintf("%s/%s", goruntime.GOOS, goruntime.GOARCH),
}
}
// TestGracefulShutdown verifies server shutdown after request handler finish.
func TestGracefulShutdown(t *testing.T) {
config, _ := setUp(t)
var graceShutdown bool
wg := sync.WaitGroup{}
wg.Add(1)
config.BuildHandlerChainFunc = func(apiHandler http.Handler, c *Config) http.Handler {
handler := genericfilters.WithWaitGroup(apiHandler, c.RequestContextMapper, c.LongRunningFunc, c.HandlerChainWaitGroup)
handler = genericapifilters.WithRequestInfo(handler, c.RequestInfoResolver, c.RequestContextMapper)
handler = apirequest.WithRequestContext(handler, c.RequestContextMapper)
return handler
}
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
wg.Done()
time.Sleep(2 * time.Second)
w.WriteHeader(http.StatusOK)
graceShutdown = true
})
s, err := config.Complete(nil).New("test", EmptyDelegate)
if err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}
s.Handler.NonGoRestfulMux.Handle("/test", handler)
insecureServer := &http.Server{
Addr: "0.0.0.0:0",
Handler: s.Handler,
}
stopCh := make(chan struct{})
ln, err := net.Listen("tcp", insecureServer.Addr)
if err != nil {
t.Errorf("failed to listen on %v: %v", insecureServer.Addr, err)
}
// get port
serverPort := ln.Addr().(*net.TCPAddr).Port
err = RunServer(insecureServer, ln, 10*time.Second, stopCh)
if err != nil {
t.Errorf("RunServer err: %v", err)
}
graceCh := make(chan struct{})
// mock a client request
go func() {
resp, err := http.Get("http://127.0.0.1:" + strconv.Itoa(serverPort) + "/test")
if err != nil {
t.Errorf("Unexpected http error: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected http status code: %v", resp.StatusCode)
}
close(graceCh)
}()
// close stopCh after request sent to server to guarantee request handler is running.
wg.Wait()
close(stopCh)
// wait for wait group handler finish
s.HandlerChainWaitGroup.Wait()
// check server all handlers finished.
if !graceShutdown {
t.Errorf("server shutdown not gracefully.")
}
// check client to make sure receive response.
select {
case <-graceCh:
t.Logf("server shutdown gracefully.")
case <-time.After(30 * time.Second):
t.Errorf("Timed out waiting for response.")
}
}

View file

@ -1,36 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["healthz_test.go"],
embed = [":go_default_library"],
)
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"healthz.go",
],
importpath = "k8s.io/apiserver/pkg/server/healthz",
deps = ["//vendor/github.com/golang/glog:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -1,112 +0,0 @@
/*
Copyright 2014 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 healthz
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestInstallHandler(t *testing.T) {
mux := http.NewServeMux()
InstallHandler(mux)
req, err := http.NewRequest("GET", "http://example.com/healthz", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected %v, got %v", http.StatusOK, w.Code)
}
if w.Body.String() != "ok" {
t.Errorf("expected %v, got %v", "ok", w.Body.String())
}
}
func TestMulitipleChecks(t *testing.T) {
tests := []struct {
path string
expectedResponse string
expectedStatus int
addBadCheck bool
}{
{"/healthz?verbose", "[+]ping ok\nhealthz check passed\n", http.StatusOK, false},
{"/healthz/ping", "ok", http.StatusOK, false},
{"/healthz", "ok", http.StatusOK, false},
{"/healthz?verbose", "[+]ping ok\n[-]bad failed: reason withheld\nhealthz check failed\n", http.StatusInternalServerError, true},
{"/healthz/ping", "ok", http.StatusOK, true},
{"/healthz/bad", "internal server error: this will fail\n", http.StatusInternalServerError, true},
{"/healthz", "[+]ping ok\n[-]bad failed: reason withheld\nhealthz check failed\n", http.StatusInternalServerError, true},
}
for i, test := range tests {
mux := http.NewServeMux()
checks := []HealthzChecker{PingHealthz}
if test.addBadCheck {
checks = append(checks, NamedCheck("bad", func(_ *http.Request) error {
return errors.New("this will fail")
}))
}
InstallHandler(mux, checks...)
req, err := http.NewRequest("GET", fmt.Sprintf("http://example.com%v", test.path), nil)
if err != nil {
t.Fatalf("case[%d] Unexpected error: %v", i, err)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != test.expectedStatus {
t.Errorf("case[%d] Expected: %v, got: %v", i, test.expectedStatus, w.Code)
}
if w.Body.String() != test.expectedResponse {
t.Errorf("case[%d] Expected:\n%v\ngot:\n%v\n", i, test.expectedResponse, w.Body.String())
}
}
}
func TestCheckerNames(t *testing.T) {
n1 := "n1"
n2 := "n2"
c1 := &healthzCheck{name: n1}
c2 := &healthzCheck{name: n2}
testCases := []struct {
desc string
have []HealthzChecker
want []string
}{
{"no checker", []HealthzChecker{}, []string{}},
{"one checker", []HealthzChecker{c1}, []string{n1}},
{"other checker", []HealthzChecker{c2}, []string{n2}},
{"checker order", []HealthzChecker{c1, c2}, []string{n1, n2}},
{"different checker order", []HealthzChecker{c2, c1}, []string{n2, n1}},
}
for _, tc := range testCases {
result := checkerNames(tc.have...)
t.Run(tc.desc, func(t *testing.T) {
if reflect.DeepEqual(tc.want, result) {
t.Errorf("want %#v, got %#v", tc.want, result)
}
})
}
}

View file

@ -1,40 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["feature_gate_test.go"],
embed = [":go_default_library"],
deps = ["//vendor/github.com/spf13/pflag:go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["feature_gate.go"],
importpath = "k8s.io/apiserver/pkg/util/feature",
deps = [
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/github.com/spf13/pflag:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//staging/src/k8s.io/apiserver/pkg/util/feature/testing:all-srcs",
],
tags = ["automanaged"],
)

View file

@ -1,191 +0,0 @@
/*
Copyright 2016 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 feature
import (
"fmt"
"strings"
"testing"
"github.com/spf13/pflag"
)
func TestFeatureGateFlag(t *testing.T) {
// gates for testing
const testAlphaGate Feature = "TestAlpha"
const testBetaGate Feature = "TestBeta"
tests := []struct {
arg string
expect map[Feature]bool
parseError string
}{
{
arg: "",
expect: map[Feature]bool{
allAlphaGate: false,
testAlphaGate: false,
testBetaGate: false,
},
},
{
arg: "fooBarBaz=maybeidk",
expect: map[Feature]bool{
allAlphaGate: false,
testAlphaGate: false,
testBetaGate: false,
},
parseError: "unrecognized key: fooBarBaz",
},
{
arg: "AllAlpha=false",
expect: map[Feature]bool{
allAlphaGate: false,
testAlphaGate: false,
testBetaGate: false,
},
},
{
arg: "AllAlpha=true",
expect: map[Feature]bool{
allAlphaGate: true,
testAlphaGate: true,
testBetaGate: false,
},
},
{
arg: "AllAlpha=banana",
expect: map[Feature]bool{
allAlphaGate: false,
testAlphaGate: false,
testBetaGate: false,
},
parseError: "invalid value of AllAlpha",
},
{
arg: "AllAlpha=false,TestAlpha=true",
expect: map[Feature]bool{
allAlphaGate: false,
testAlphaGate: true,
testBetaGate: false,
},
},
{
arg: "TestAlpha=true,AllAlpha=false",
expect: map[Feature]bool{
allAlphaGate: false,
testAlphaGate: true,
testBetaGate: false,
},
},
{
arg: "AllAlpha=true,TestAlpha=false",
expect: map[Feature]bool{
allAlphaGate: true,
testAlphaGate: false,
testBetaGate: false,
},
},
{
arg: "TestAlpha=false,AllAlpha=true",
expect: map[Feature]bool{
allAlphaGate: true,
testAlphaGate: false,
testBetaGate: false,
},
},
{
arg: "TestBeta=true,AllAlpha=false",
expect: map[Feature]bool{
allAlphaGate: false,
testAlphaGate: false,
testBetaGate: true,
},
},
}
for i, test := range tests {
fs := pflag.NewFlagSet("testfeaturegateflag", pflag.ContinueOnError)
f := NewFeatureGate()
f.Add(map[Feature]FeatureSpec{
testAlphaGate: {Default: false, PreRelease: Alpha},
testBetaGate: {Default: false, PreRelease: Beta},
})
f.AddFlag(fs)
err := fs.Parse([]string{fmt.Sprintf("--%s=%s", flagName, test.arg)})
if test.parseError != "" {
if !strings.Contains(err.Error(), test.parseError) {
t.Errorf("%d: Parse() Expected %v, Got %v", i, test.parseError, err)
}
} else if err != nil {
t.Errorf("%d: Parse() Expected nil, Got %v", i, err)
}
for k, v := range test.expect {
if actual := f.enabled.Load().(map[Feature]bool)[k]; actual != v {
t.Errorf("%d: expected %s=%v, Got %v", i, k, v, actual)
}
}
}
}
func TestFeatureGateOverride(t *testing.T) {
const testAlphaGate Feature = "TestAlpha"
const testBetaGate Feature = "TestBeta"
// Don't parse the flag, assert defaults are used.
var f FeatureGate = NewFeatureGate()
f.Add(map[Feature]FeatureSpec{
testAlphaGate: {Default: false, PreRelease: Alpha},
testBetaGate: {Default: false, PreRelease: Beta},
})
f.Set("TestAlpha=true,TestBeta=true")
if f.Enabled(testAlphaGate) != true {
t.Errorf("Expected true")
}
if f.Enabled(testBetaGate) != true {
t.Errorf("Expected true")
}
f.Set("TestAlpha=false")
if f.Enabled(testAlphaGate) != false {
t.Errorf("Expected false")
}
if f.Enabled(testBetaGate) != true {
t.Errorf("Expected true")
}
}
func TestFeatureGateFlagDefaults(t *testing.T) {
// gates for testing
const testAlphaGate Feature = "TestAlpha"
const testBetaGate Feature = "TestBeta"
// Don't parse the flag, assert defaults are used.
var f FeatureGate = NewFeatureGate()
f.Add(map[Feature]FeatureSpec{
testAlphaGate: {Default: false, PreRelease: Alpha},
testBetaGate: {Default: true, PreRelease: Beta},
})
if f.Enabled(testAlphaGate) != false {
t.Errorf("Expected false")
}
if f.Enabled(testBetaGate) != true {
t.Errorf("Expected true")
}
}

View file

@ -1,30 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["logs.go"],
importpath = "k8s.io/apiserver/pkg/util/logs",
deps = [
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/github.com/spf13/pflag:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)