vendor files

This commit is contained in:
Serguei Bezverkhi
2018-01-09 13:57:14 -05:00
parent 558bc6c02a
commit 7b24313bd6
16547 changed files with 4527373 additions and 0 deletions

37
vendor/k8s.io/kubernetes/cmd/kubeadm/test/BUILD generated vendored Normal file
View File

@ -0,0 +1,37 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["util.go"],
importpath = "k8s.io/kubernetes/cmd/kubeadm/test",
deps = [
"//cmd/kubeadm/app/apis/kubeadm:go_default_library",
"//cmd/kubeadm/app/constants:go_default_library",
"//cmd/kubeadm/app/phases/certs/pkiutil:go_default_library",
"//cmd/kubeadm/test/certs:go_default_library",
"//vendor/github.com/renstrom/dedent:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//cmd/kubeadm/test/certs:all-srcs",
"//cmd/kubeadm/test/cmd:all-srcs",
"//cmd/kubeadm/test/kubeconfig:all-srcs",
],
tags = ["automanaged"],
)

26
vendor/k8s.io/kubernetes/cmd/kubeadm/test/certs/BUILD generated vendored Normal file
View File

@ -0,0 +1,26 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["util.go"],
importpath = "k8s.io/kubernetes/cmd/kubeadm/test/certs",
deps = ["//cmd/kubeadm/app/phases/certs/pkiutil:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

134
vendor/k8s.io/kubernetes/cmd/kubeadm/test/certs/util.go generated vendored Normal file
View File

@ -0,0 +1,134 @@
/*
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 certs
import (
"crypto/rsa"
"crypto/x509"
"net"
"testing"
"k8s.io/kubernetes/cmd/kubeadm/app/phases/certs/pkiutil"
)
// SetupCertificateAuthorithy is a utility function for kubeadm testing that creates a
// CertificateAuthorithy cert/key pair
func SetupCertificateAuthorithy(t *testing.T) (*x509.Certificate, *rsa.PrivateKey) {
caCert, caKey, err := pkiutil.NewCertificateAuthority()
if err != nil {
t.Fatalf("failure while generating CA certificate and key: %v", err)
}
return caCert, caKey
}
// AssertCertificateIsCa is a utility function for kubeadm testing that asserts if a given certificate is a CA
func AssertCertificateIsCa(t *testing.T, cert *x509.Certificate) {
if !cert.IsCA {
t.Error("cert is not a valida CA")
}
}
// AssertCertificateIsSignedByCa is a utility function for kubeadm testing that asserts if a given certificate is signed
// by the expected CA
func AssertCertificateIsSignedByCa(t *testing.T, cert *x509.Certificate, signingCa *x509.Certificate) {
if err := cert.CheckSignatureFrom(signingCa); err != nil {
t.Error("cert is not signed by signing CA as expected")
}
}
// AssertCertificateHasCommonName is a utility function for kubeadm testing that asserts if a given certificate has
// the expected SubjectCommonName
func AssertCertificateHasCommonName(t *testing.T, cert *x509.Certificate, commonName string) {
if cert.Subject.CommonName != commonName {
t.Errorf("cert has Subject.CommonName %s, expected %s", cert.Subject.CommonName, commonName)
}
}
// AssertCertificateHasOrganizations is a utility function for kubeadm testing that asserts if a given certificate has
// the expected Subject.Organization
func AssertCertificateHasOrganizations(t *testing.T, cert *x509.Certificate, organizations ...string) {
for _, organization := range organizations {
found := false
for i := range cert.Subject.Organization {
if cert.Subject.Organization[i] == organization {
found = true
}
}
if !found {
t.Errorf("cert does not contain Subject.Organization %s as expected", organization)
}
}
}
// AssertCertificateHasClientAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has
// the expected ExtKeyUsageClientAuth
func AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate) {
for i := range cert.ExtKeyUsage {
if cert.ExtKeyUsage[i] == x509.ExtKeyUsageClientAuth {
return
}
}
t.Error("cert has not ClientAuth usage as expected")
}
// AssertCertificateHasServerAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has
// the expected ExtKeyUsageServerAuth
func AssertCertificateHasServerAuthUsage(t *testing.T, cert *x509.Certificate) {
for i := range cert.ExtKeyUsage {
if cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {
return
}
}
t.Error("cert is not a ServerAuth")
}
// AssertCertificateHasDNSNames is a utility function for kubeadm testing that asserts if a given certificate has
// the expected DNSNames
func AssertCertificateHasDNSNames(t *testing.T, cert *x509.Certificate, DNSNames ...string) {
for _, DNSName := range DNSNames {
found := false
for _, val := range cert.DNSNames {
if val == DNSName {
found = true
break
}
}
if !found {
t.Errorf("cert does not contain DNSName %s", DNSName)
}
}
}
// AssertCertificateHasIPAddresses is a utility function for kubeadm testing that asserts if a given certificate has
// the expected IPAddresses
func AssertCertificateHasIPAddresses(t *testing.T, cert *x509.Certificate, IPAddresses ...net.IP) {
for _, IPAddress := range IPAddresses {
found := false
for _, val := range cert.IPAddresses {
if val.Equal(IPAddress) {
found = true
break
}
}
if !found {
t.Errorf("cert does not contain IPAddress %s", IPAddress)
}
}
}

47
vendor/k8s.io/kubernetes/cmd/kubeadm/test/cmd/BUILD generated vendored Normal file
View File

@ -0,0 +1,47 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["util.go"],
importpath = "k8s.io/kubernetes/cmd/kubeadm/test/cmd",
deps = ["//vendor/github.com/spf13/cobra:go_default_library"],
)
go_test(
name = "go_default_test",
srcs = [
"completion_test.go",
"init_test.go",
"join_test.go",
"token_test.go",
"version_test.go",
],
args = ["--kubeadm-path=../../kubeadm"],
data = ["//cmd/kubeadm"],
importpath = "k8s.io/kubernetes/cmd/kubeadm/test/cmd",
library = ":go_default_library",
tags = [
"integration",
"skip",
],
deps = ["//vendor/github.com/ghodss/yaml: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

@ -0,0 +1,47 @@
/*
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 kubeadm
import "testing"
func TestCmdCompletion(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var tests = []struct {
args string
expected bool
}{
{"", false}, // shell not specified
{"foo", false}, // unsupported shell type
}
for _, rt := range tests {
_, _, actual := RunCmd(*kubeadmPath, "completion", rt.args)
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdCompletion running 'kubeadm completion %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
}
}

View File

@ -0,0 +1,167 @@
/*
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 kubeadm
import "testing"
// kubeadmReset executes "kubeadm reset" and restarts kubelet.
func kubeadmReset() error {
_, _, err := RunCmd(*kubeadmPath, "reset")
return err
}
func TestCmdInitToken(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--discovery=token://abcd:1234567890abcd", false}, // invalid token size
{"--discovery=token://Abcdef:1234567890abcdef", false}, // invalid token non-lowercase
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "init", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdInitToken running 'kubeadm init %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdInitKubernetesVersion(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--kubernetes-version=foobar", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "init", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdInitKubernetesVersion running 'kubeadm init %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdInitConfig(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--config=foobar", false},
{"--config=/does/not/exist/foo/bar", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "init", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdInitConfig running 'kubeadm init %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdInitAPIPort(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--api-port=foobar", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "init", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdInitAPIPort running 'kubeadm init %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdInitArgsMixed(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--api-port=1000 --config=/etc/kubernets/kubeadm.config", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "init", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdInitArgsMixed running 'kubeadm init %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}

View File

@ -0,0 +1,249 @@
/*
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 kubeadm
import "testing"
func TestCmdJoinConfig(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--config=foobar", false},
{"--config=/does/not/exist/foo/bar", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinConfig running 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdJoinDiscoveryFile(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--discovery-file=foobar", false},
{"--discovery-file=file:wrong", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinDiscoveryFile running 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdJoinDiscoveryToken(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--discovery-token=foobar", false},
{"--discovery-token=token://asdf:asdf", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinDiscoveryToken running 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdJoinNodeName(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--node-name=foobar", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinNodeName running 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdJoinTLSBootstrapToken(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--tls-bootstrap-token=foobar", false},
{"--tls-bootstrap-token=token://asdf:asdf", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinTLSBootstrapToken running 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdJoinToken(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--token=foobar", false},
{"--token=token://asdf:asdf", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinToken running 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdJoinBadArgs(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--discovery-token=abcdef.1234567890123456 --discovery-file=file:///tmp/foo.bar", false}, // DiscoveryToken, DiscoveryFile can't both be set
{"", false}, // DiscoveryToken or DiscoveryFile must be set
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinBadArgs 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}
func TestCmdJoinArgsMixed(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var initTest = []struct {
args string
expected bool
}{
{"--discovery-token=abcdef.1234567890abcdef --config=/etc/kubernets/kubeadm.config", false},
}
for _, rt := range initTest {
_, _, actual := RunCmd(*kubeadmPath, "join", rt.args, "--skip-preflight-checks")
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdJoinArgsMixed running 'kubeadm join %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}

View File

@ -0,0 +1,100 @@
/*
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 kubeadm
import (
"flag"
"os"
"path/filepath"
"regexp"
"testing"
)
const (
TokenExpectedRegex = "^\\S{6}\\.\\S{16}\n$"
)
var kubeadmPath = flag.String("kubeadm-path", filepath.Join(os.Getenv("KUBE_ROOT"), "cluster/kubeadm.sh"), "Location of kubeadm")
var kubeadmCmdSkip = flag.Bool("kubeadm-cmd-skip", false, "Skip kubeadm cmd tests")
func TestCmdTokenGenerate(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
stdout, _, err := RunCmd(*kubeadmPath, "token", "generate")
if err != nil {
t.Fatalf("'kubeadm token generate' exited uncleanly: %v", err)
}
matched, err := regexp.MatchString(TokenExpectedRegex, stdout)
if err != nil {
t.Fatalf("encountered an error while trying to match 'kubeadm token generate' stdout: %v", err)
}
if !matched {
t.Errorf("'kubeadm token generate' stdout did not match expected regex; wanted: [%q], got: [%s]", TokenExpectedRegex, stdout)
}
}
func TestCmdTokenGenerateTypoError(t *testing.T) {
/*
Since we expect users to do things like this:
$ TOKEN=$(kubeadm token generate)
we want to make sure that if they have a typo in their command, we exit
with a non-zero status code after showing the command's usage, so that
the usage itself isn't captured as a token without the user noticing.
*/
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
_, _, err := RunCmd(*kubeadmPath, "token", "genorate") // subtle typo
if err == nil {
t.Error("'kubeadm token genorate' (a deliberate typo) exited without an error when we expected non-zero exit status")
}
}
func TestCmdTokenDelete(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var tests = []struct {
args string
expected bool
}{
{"", false}, // no token provided
{"foobar", false}, // invalid token
}
for _, rt := range tests {
_, _, actual := RunCmd(*kubeadmPath, "token", "delete", rt.args)
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdTokenDelete running 'kubeadm token %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
kubeadmReset()
}
}

75
vendor/k8s.io/kubernetes/cmd/kubeadm/test/cmd/util.go generated vendored Normal file
View File

@ -0,0 +1,75 @@
/*
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 kubeadm
import (
"bytes"
"fmt"
"os/exec"
"testing"
"github.com/spf13/cobra"
)
// Forked from test/e2e/framework because the e2e framework is quite bloated
// for our purposes here, and modified to remove undesired logging.
// RunCmd is a utility function for kubeadm testing that executes a specified command
func RunCmd(command string, args ...string) (string, string, error) {
var bout, berr bytes.Buffer
cmd := exec.Command(command, args...)
cmd.Stdout = &bout
cmd.Stderr = &berr
err := cmd.Run()
stdout, stderr := bout.String(), berr.String()
if err != nil {
return "", "", fmt.Errorf("error running %s %v; \ngot error %v, \nstdout %q, \nstderr %q",
command, args, err, stdout, stderr)
}
return stdout, stderr, nil
}
// RunSubCommand is a utility function for kubeadm testing that executes a Cobra sub command
func RunSubCommand(t *testing.T, subCmds []*cobra.Command, command string, args ...string) {
subCmd := getSubCommand(t, subCmds, command)
subCmd.SetArgs(args)
if err := subCmd.Execute(); err != nil {
t.Fatalf("Could not execute subcommand: %s", command)
}
}
// AssertSubCommandHasFlags is a utility function for kubeadm testing that assert if a Cobra sub command has expected flags
func AssertSubCommandHasFlags(t *testing.T, subCmds []*cobra.Command, command string, flags ...string) {
subCmd := getSubCommand(t, subCmds, command)
for _, flag := range flags {
if subCmd.Flags().Lookup(flag) == nil {
t.Errorf("Could not find expecte flag %s for command %s", flag, command)
}
}
}
func getSubCommand(t *testing.T, subCmds []*cobra.Command, name string) *cobra.Command {
for _, subCmd := range subCmds {
if subCmd.Name() == name {
return subCmd
}
}
t.Fatalf("Unable to find sub command %s", name)
return nil
}

View File

@ -0,0 +1,130 @@
/*
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 kubeadm
import (
"encoding/json"
"regexp"
"testing"
"github.com/ghodss/yaml"
)
const (
ShortExpectedRegex = "^v.+\n$"
NormalExpectedRegex = "^kubeadm version: &version\\.Info{Major:\".+\", Minor:\".+\", GitVersion:\".+\", GitCommit:\".+\", GitTreeState:\".+\", BuildDate:\".+\", GoVersion:\".+\", Compiler:\".+\", Platform:\".+\"}\n$"
)
var (
VersionInfo = []string{"major", "minor", "gitVersion", "gitCommit", "gitTreeState", "buildDate", "goVersion", "compiler", "platform"}
)
func TestCmdVersion(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var versionTest = []struct {
args string
regex string
expected bool
}{
{"--output=valid", "", false},
{"--output=short", ShortExpectedRegex, true},
{"", NormalExpectedRegex, true},
}
for _, rt := range versionTest {
stdout, _, actual := RunCmd(*kubeadmPath, "version", rt.args)
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdVersion running 'kubeadm version %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
if rt.expected {
matched, err := regexp.MatchString(rt.regex, stdout)
if err != nil {
t.Fatalf("encountered an error while trying to match 'kubeadm version %s' stdout: %v", rt.args, err)
}
if !matched {
t.Errorf("'kubeadm version %s' stdout did not match expected regex; wanted: [%q], got: [%s]", rt.args, rt.regex, stdout)
}
}
}
}
func TestCmdVersionOutputJsonOrYaml(t *testing.T) {
if *kubeadmCmdSkip {
t.Log("kubeadm cmd tests being skipped")
t.Skip()
}
var versionTest = []struct {
args string
format string
expected bool
}{
{"--output=json", "json", true},
{"--output=yaml", "yaml", true},
}
for _, rt := range versionTest {
stdout, _, actual := RunCmd(*kubeadmPath, "version", rt.args)
if (actual == nil) != rt.expected {
t.Errorf(
"failed CmdVersion running 'kubeadm version %s' with an error: %v\n\texpected: %t\n\t actual: %t",
rt.args,
actual,
rt.expected,
(actual == nil),
)
}
if rt.expected {
var obj interface{}
switch rt.format {
case "json":
err := json.Unmarshal([]byte(stdout), &obj)
if err != nil {
t.Errorf("failed to parse json from 'kubeadm version %s': %s", rt.args, err)
}
case "yaml":
err := yaml.Unmarshal([]byte(stdout), &obj)
if err != nil {
t.Errorf("failed to parse yaml from 'kubeadm version %s': %s", rt.args, err)
}
}
m := obj.(map[string]interface{})
if m["clientVersion"] == nil {
t.Errorf("failed to get the infomation of clientVersion from 'kubeadm version %s'", rt.args)
}
info := m["clientVersion"].(map[string]interface{})
for _, key := range VersionInfo {
if len(info[key].(string)) == 0 {
t.Errorf("failed to get the infomation of %s from 'kubeadm version %s'", key, rt.args)
}
}
}
}
}

View File

@ -0,0 +1,29 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["util.go"],
importpath = "k8s.io/kubernetes/cmd/kubeadm/test/kubeconfig",
deps = [
"//cmd/kubeadm/test/certs:go_default_library",
"//vendor/k8s.io/client-go/tools/clientcmd/api: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

@ -0,0 +1,100 @@
/*
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 kubeconfig
import (
"crypto/x509"
"encoding/pem"
"testing"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
certstestutil "k8s.io/kubernetes/cmd/kubeadm/test/certs"
)
// AssertKubeConfigCurrentCluster is a utility function for kubeadm testing that asserts if the CurrentCluster in
// the given KubeConfig object contains refers to a specific cluster
func AssertKubeConfigCurrentCluster(t *testing.T, config *clientcmdapi.Config, expectedAPIServerAddress string, expectedAPIServerCaCert *x509.Certificate) {
currentContext := config.Contexts[config.CurrentContext]
currentCluster := config.Clusters[currentContext.Cluster]
// Assert expectedAPIServerAddress
if currentCluster.Server != expectedAPIServerAddress {
t.Errorf("kubeconfig.currentCluster.Server is [%s], expected [%s]", currentCluster.Server, expectedAPIServerAddress)
}
// Assert the APIServerCaCert
if len(currentCluster.CertificateAuthorityData) == 0 {
t.Error("kubeconfig.currentCluster.CertificateAuthorityData is empty, expected not empty")
return
}
block, _ := pem.Decode(currentCluster.CertificateAuthorityData)
currentAPIServerCaCert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
t.Errorf("kubeconfig.currentCluster.CertificateAuthorityData is not a valid CA: %v", err)
return
}
if !currentAPIServerCaCert.Equal(expectedAPIServerCaCert) {
t.Errorf("kubeconfig.currentCluster.CertificateAuthorityData not correspond to the expected CA cert")
}
}
// AssertKubeConfigCurrentAuthInfoWithClientCert is a utility function for kubeadm testing that asserts if the CurrentAuthInfo in
// the given KubeConfig object contains a clientCert that refers to a specific client name, is signed by the expected CA, includes the expected organizations
func AssertKubeConfigCurrentAuthInfoWithClientCert(t *testing.T, config *clientcmdapi.Config, signinCa *x509.Certificate, expectedClientName string, expectedOrganizations ...string) {
currentContext := config.Contexts[config.CurrentContext]
currentAuthInfo := config.AuthInfos[currentContext.AuthInfo]
// assert clientCert
if len(currentAuthInfo.ClientCertificateData) == 0 {
t.Error("kubeconfig.currentAuthInfo.ClientCertificateData is empty, expected not empty")
return
}
block, _ := pem.Decode(config.AuthInfos[currentContext.AuthInfo].ClientCertificateData)
currentClientCert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
t.Errorf("kubeconfig.currentAuthInfo.ClientCertificateData is not a valid CA: %v", err)
return
}
// Asserts the clientCert is signed by the signinCa
certstestutil.AssertCertificateIsSignedByCa(t, currentClientCert, signinCa)
// Asserts the clientCert has ClientAuth ExtKeyUsage
certstestutil.AssertCertificateHasClientAuthUsage(t, currentClientCert)
// Asserts the clientCert has expected expectedUserName as CommonName
certstestutil.AssertCertificateHasCommonName(t, currentClientCert, expectedClientName)
// Asserts the clientCert has expected Organizations
certstestutil.AssertCertificateHasOrganizations(t, currentClientCert, expectedOrganizations...)
}
// AssertKubeConfigCurrentAuthInfoWithToken is a utility function for kubeadm testing that asserts if the CurrentAuthInfo in
// the given KubeConfig object refers to expected token
func AssertKubeConfigCurrentAuthInfoWithToken(t *testing.T, config *clientcmdapi.Config, expectedClientName, expectedToken string) {
currentContext := config.Contexts[config.CurrentContext]
currentAuthInfo := config.AuthInfos[currentContext.AuthInfo]
// assert token
if currentAuthInfo.Token != expectedToken {
t.Errorf("kubeconfig.currentAuthInfo.Token [%s], expected [%s]", currentAuthInfo.Token, expectedToken)
return
}
}

137
vendor/k8s.io/kubernetes/cmd/kubeadm/test/util.go generated vendored Normal file
View File

@ -0,0 +1,137 @@
/*
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 test
import (
"html/template"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/renstrom/dedent"
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
"k8s.io/kubernetes/cmd/kubeadm/app/phases/certs/pkiutil"
certtestutil "k8s.io/kubernetes/cmd/kubeadm/test/certs"
)
// SetupTempDir is a utility function for kubeadm testing, that creates a temporary directory
// NB. it is up to the caller to cleanup the folder at the end of the test with defer os.RemoveAll(tmpdir)
func SetupTempDir(t *testing.T) string {
tmpdir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("Couldn't create tmpdir")
}
return tmpdir
}
// SetupMasterConfigurationFile is a utility function for kubeadm testing that writes a master configuration file
// into /config subfolder of a given temporary directory.
// The funtion returns the path of the created master configuration file.
func SetupMasterConfigurationFile(t *testing.T, tmpdir string, cfg *kubeadmapi.MasterConfiguration) string {
cfgPath := filepath.Join(tmpdir, "config/masterconfig.yaml")
if err := os.MkdirAll(filepath.Dir(cfgPath), os.FileMode(0755)); err != nil {
t.Fatalf("Couldn't create cfgDir")
}
cfgTemplate := template.Must(template.New("init").Parse(dedent.Dedent(`
apiVersion: kubeadm.k8s.io/v1alpha1
kind: MasterConfiguration
certificatesDir: {{.CertificatesDir}}
api:
advertiseAddress: {{.API.AdvertiseAddress}}
bindPort: {{.API.BindPort}}
nodeName: {{.NodeName}}
`)))
f, err := os.Create(cfgPath)
if err != nil {
t.Fatalf("error creating masterconfig file %s: %v", cfgPath, err)
}
err = cfgTemplate.Execute(f, cfg)
if err != nil {
t.Fatalf("error generating masterconfig file %s: %v", cfgPath, err)
}
f.Close()
return cfgPath
}
// SetupEmptyFiles is a utility function for kubeadm testing that creates one or more empty files (touch)
func SetupEmptyFiles(t *testing.T, tmpdir string, fileNames ...string) {
for _, fileName := range fileNames {
newFile, err := os.Create(filepath.Join(tmpdir, fileName))
if err != nil {
t.Fatalf("Error creating file %s in %s: %v", fileName, tmpdir, err)
}
newFile.Close()
}
}
// SetupPkiDirWithCertificateAuthorithy is a utility function for kubeadm testing that creates a
// CertificateAuthorithy cert/key pair into /pki subfolder of a given temporary directory.
// The funtion returns the path of the created pki.
func SetupPkiDirWithCertificateAuthorithy(t *testing.T, tmpdir string) string {
caCert, caKey := certtestutil.SetupCertificateAuthorithy(t)
certDir := filepath.Join(tmpdir, "pki")
if err := pkiutil.WriteCertAndKey(certDir, kubeadmconstants.CACertAndKeyBaseName, caCert, caKey); err != nil {
t.Fatalf("failure while saving CA certificate and key: %v", err)
}
return certDir
}
// AssertFilesCount is a utility function for kubeadm testing that asserts if the given folder contains
// count files.
func AssertFilesCount(t *testing.T, dirName string, count int) {
files, err := ioutil.ReadDir(dirName)
if err != nil {
t.Fatalf("Couldn't read files from tmpdir: %s", err)
}
countFiles := 0
for _, f := range files {
if !f.IsDir() {
countFiles++
}
}
if countFiles != count {
t.Errorf("dir does contains %d, %d expected", len(files), count)
for _, f := range files {
t.Error(f.Name())
}
}
}
// AssertFileExists is a utility function for kubeadm testing that asserts if the given folder contains
// the given files.
func AssertFileExists(t *testing.T, dirName string, fileNames ...string) {
for _, fileName := range fileNames {
path := filepath.Join(dirName, fileName)
if _, err := os.Stat(path); os.IsNotExist(err) {
t.Errorf("file %s does not exist", fileName)
}
}
}