Merge pull request #72433 from bart0sh/PR0050-kubeadm-app-util-use-T.Run

kubeadm: use T.Run API in app/util
pull/564/head
Kubernetes Prow Robot 2018-12-30 03:45:41 -08:00 committed by GitHub
commit 13e59ab9ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 667 additions and 528 deletions

View File

@ -29,28 +29,33 @@ import (
func TestLogDryRunAction(t *testing.T) { func TestLogDryRunAction(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
action core.Action action core.Action
expectedBytes []byte expectedBytes []byte
buf *bytes.Buffer buf *bytes.Buffer
}{ }{
{ {
name: "action GET on services",
action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", "kubernetes"), action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", "kubernetes"),
expectedBytes: []byte(`[dryrun] Would perform action GET on resource "services" in API group "core/v1" expectedBytes: []byte(`[dryrun] Would perform action GET on resource "services" in API group "core/v1"
[dryrun] Resource name: "kubernetes" [dryrun] Resource name: "kubernetes"
`), `),
}, },
{ {
name: "action GET on clusterrolebindings",
action: core.NewRootGetAction(schema.GroupVersionResource{Group: rbac.GroupName, Version: rbac.SchemeGroupVersion.Version, Resource: "clusterrolebindings"}, "system:node"), action: core.NewRootGetAction(schema.GroupVersionResource{Group: rbac.GroupName, Version: rbac.SchemeGroupVersion.Version, Resource: "clusterrolebindings"}, "system:node"),
expectedBytes: []byte(`[dryrun] Would perform action GET on resource "clusterrolebindings" in API group "rbac.authorization.k8s.io/v1" expectedBytes: []byte(`[dryrun] Would perform action GET on resource "clusterrolebindings" in API group "rbac.authorization.k8s.io/v1"
[dryrun] Resource name: "system:node" [dryrun] Resource name: "system:node"
`), `),
}, },
{ {
name: "action LIST on services",
action: core.NewListAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, schema.GroupVersionKind{Version: "v1", Kind: "Service"}, "default", metav1.ListOptions{}), action: core.NewListAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, schema.GroupVersionKind{Version: "v1", Kind: "Service"}, "default", metav1.ListOptions{}),
expectedBytes: []byte(`[dryrun] Would perform action LIST on resource "services" in API group "core/v1" expectedBytes: []byte(`[dryrun] Would perform action LIST on resource "services" in API group "core/v1"
`), `),
}, },
{ {
name: "action CREATE on services",
action: core.NewCreateAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", &v1.Service{ action: core.NewCreateAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", &v1.Service{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "foo", Name: "foo",
@ -72,6 +77,7 @@ func TestLogDryRunAction(t *testing.T) {
`), `),
}, },
{ {
name: "action PATCH on nodes",
action: core.NewPatchAction(schema.GroupVersionResource{Version: "v1", Resource: "nodes"}, "default", "my-node", "application/strategic-merge-patch+json", []byte(`{"spec":{"taints":[{"key": "foo", "value": "bar"}]}}`)), action: core.NewPatchAction(schema.GroupVersionResource{Version: "v1", Resource: "nodes"}, "default", "my-node", "application/strategic-merge-patch+json", []byte(`{"spec":{"taints":[{"key": "foo", "value": "bar"}]}}`)),
expectedBytes: []byte(`[dryrun] Would perform action PATCH on resource "nodes" in API group "core/v1" expectedBytes: []byte(`[dryrun] Would perform action PATCH on resource "nodes" in API group "core/v1"
[dryrun] Resource name: "my-node" [dryrun] Resource name: "my-node"
@ -80,6 +86,7 @@ func TestLogDryRunAction(t *testing.T) {
`), `),
}, },
{ {
name: "action DELETE on pods",
action: core.NewDeleteAction(schema.GroupVersionResource{Version: "v1", Resource: "pods"}, "default", "my-pod"), action: core.NewDeleteAction(schema.GroupVersionResource{Version: "v1", Resource: "pods"}, "default", "my-pod"),
expectedBytes: []byte(`[dryrun] Would perform action DELETE on resource "pods" in API group "core/v1" expectedBytes: []byte(`[dryrun] Would perform action DELETE on resource "pods" in API group "core/v1"
[dryrun] Resource name: "my-pod" [dryrun] Resource name: "my-pod"
@ -87,6 +94,7 @@ func TestLogDryRunAction(t *testing.T) {
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
rt.buf = bytes.NewBufferString("") rt.buf = bytes.NewBufferString("")
logDryRunAction(rt.action, rt.buf, DefaultMarshalFunc) logDryRunAction(rt.action, rt.buf, DefaultMarshalFunc)
actualBytes := rt.buf.Bytes() actualBytes := rt.buf.Bytes()
@ -98,5 +106,6 @@ func TestLogDryRunAction(t *testing.T) {
actualBytes, actualBytes,
) )
} }
})
} }
} }

View File

@ -32,54 +32,63 @@ func TestHandleGetAction(t *testing.T) {
idr := NewInitDryRunGetter(masterName, serviceSubnet) idr := NewInitDryRunGetter(masterName, serviceSubnet)
var tests = []struct { var tests = []struct {
name string
action core.GetActionImpl action core.GetActionImpl
expectedHandled bool expectedHandled bool
expectedObjectJSON []byte expectedObjectJSON []byte
expectedErr bool expectedErr bool
}{ }{
{ {
name: "get default services",
action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", "kubernetes"), action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", "kubernetes"),
expectedHandled: true, expectedHandled: true,
expectedObjectJSON: []byte(`{"metadata":{"name":"kubernetes","namespace":"default","creationTimestamp":null,"labels":{"component":"apiserver","provider":"kubernetes"}},"spec":{"ports":[{"name":"https","port":443,"targetPort":6443}],"clusterIP":"10.96.0.1"},"status":{"loadBalancer":{}}}`), expectedObjectJSON: []byte(`{"metadata":{"name":"kubernetes","namespace":"default","creationTimestamp":null,"labels":{"component":"apiserver","provider":"kubernetes"}},"spec":{"ports":[{"name":"https","port":443,"targetPort":6443}],"clusterIP":"10.96.0.1"},"status":{"loadBalancer":{}}}`),
expectedErr: false, expectedErr: false,
}, },
{ {
name: "get nodes",
action: core.NewRootGetAction(schema.GroupVersionResource{Version: "v1", Resource: "nodes"}, masterName), action: core.NewRootGetAction(schema.GroupVersionResource{Version: "v1", Resource: "nodes"}, masterName),
expectedHandled: true, expectedHandled: true,
expectedObjectJSON: []byte(`{"metadata":{"name":"master-foo","creationTimestamp":null,"labels":{"kubernetes.io/hostname":"master-foo"}},"spec":{},"status":{"daemonEndpoints":{"kubeletEndpoint":{"Port":0}},"nodeInfo":{"machineID":"","systemUUID":"","bootID":"","kernelVersion":"","osImage":"","containerRuntimeVersion":"","kubeletVersion":"","kubeProxyVersion":"","operatingSystem":"","architecture":""}}}`), expectedObjectJSON: []byte(`{"metadata":{"name":"master-foo","creationTimestamp":null,"labels":{"kubernetes.io/hostname":"master-foo"}},"spec":{},"status":{"daemonEndpoints":{"kubeletEndpoint":{"Port":0}},"nodeInfo":{"machineID":"","systemUUID":"","bootID":"","kernelVersion":"","osImage":"","containerRuntimeVersion":"","kubeletVersion":"","kubeProxyVersion":"","operatingSystem":"","architecture":""}}}`),
expectedErr: false, expectedErr: false,
}, },
{ {
name: "get clusterrolebinings",
action: core.NewRootGetAction(schema.GroupVersionResource{Group: rbac.GroupName, Version: rbac.SchemeGroupVersion.Version, Resource: "clusterrolebindings"}, "system:node"), action: core.NewRootGetAction(schema.GroupVersionResource{Group: rbac.GroupName, Version: rbac.SchemeGroupVersion.Version, Resource: "clusterrolebindings"}, "system:node"),
expectedHandled: true, expectedHandled: true,
expectedObjectJSON: []byte(``), expectedObjectJSON: []byte(``),
expectedErr: true, // we expect a NotFound error here expectedErr: true, // we expect a NotFound error here
}, },
{ {
name: "get kube-system secret bootstrap-token-abcdef",
action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "secrets"}, "kube-system", "bootstrap-token-abcdef"), action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "secrets"}, "kube-system", "bootstrap-token-abcdef"),
expectedHandled: true, expectedHandled: true,
expectedObjectJSON: []byte(``), expectedObjectJSON: []byte(``),
expectedErr: true, // we expect a NotFound error here expectedErr: true, // we expect a NotFound error here
}, },
{ // an ask for a kubernetes service in the _kube-system_ ns should not be answered { // an ask for a kubernetes service in the _kube-system_ ns should not be answered
name: "get kube-system services",
action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "kube-system", "kubernetes"), action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "kube-system", "kubernetes"),
expectedHandled: false, expectedHandled: false,
expectedObjectJSON: []byte(``), expectedObjectJSON: []byte(``),
expectedErr: false, expectedErr: false,
}, },
{ // an ask for an other service than kubernetes should not be answered { // an ask for an other service than kubernetes should not be answered
name: "get default my-other-service",
action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", "my-other-service"), action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "services"}, "default", "my-other-service"),
expectedHandled: false, expectedHandled: false,
expectedObjectJSON: []byte(``), expectedObjectJSON: []byte(``),
expectedErr: false, expectedErr: false,
}, },
{ // an ask for an other node than the master should not be answered { // an ask for an other node than the master should not be answered
name: "get other-node",
action: core.NewRootGetAction(schema.GroupVersionResource{Version: "v1", Resource: "nodes"}, "other-node"), action: core.NewRootGetAction(schema.GroupVersionResource{Version: "v1", Resource: "nodes"}, "other-node"),
expectedHandled: false, expectedHandled: false,
expectedObjectJSON: []byte(``), expectedObjectJSON: []byte(``),
expectedErr: false, expectedErr: false,
}, },
{ // an ask for a secret in any other ns than kube-system should not be answered { // an ask for a secret in any other ns than kube-system should not be answered
name: "get default secret bootstrap-token-abcdef",
action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "secrets"}, "default", "bootstrap-token-abcdef"), action: core.NewGetAction(schema.GroupVersionResource{Version: "v1", Resource: "secrets"}, "default", "bootstrap-token-abcdef"),
expectedHandled: false, expectedHandled: false,
expectedObjectJSON: []byte(``), expectedObjectJSON: []byte(``),
@ -87,6 +96,7 @@ func TestHandleGetAction(t *testing.T) {
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
handled, obj, actualErr := idr.HandleGetAction(rt.action) handled, obj, actualErr := idr.HandleGetAction(rt.action)
objBytes := []byte(``) objBytes := []byte(``)
if obj != nil { if obj != nil {
@ -122,5 +132,6 @@ func TestHandleGetAction(t *testing.T) {
rt.action, rt.action,
) )
} }
})
} }
} }

View File

@ -24,11 +24,13 @@ import (
func TestBuildArgumentListFromMap(t *testing.T) { func TestBuildArgumentListFromMap(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
base map[string]string base map[string]string
overrides map[string]string overrides map[string]string
expected []string expected []string
}{ }{
{ // override an argument from the base {
name: "override an argument from the base",
base: map[string]string{ base: map[string]string{
"admission-control": "NamespaceLifecycle", "admission-control": "NamespaceLifecycle",
"insecure-bind-address": "127.0.0.1", "insecure-bind-address": "127.0.0.1",
@ -43,7 +45,8 @@ func TestBuildArgumentListFromMap(t *testing.T) {
"--insecure-bind-address=127.0.0.1", "--insecure-bind-address=127.0.0.1",
}, },
}, },
{ // add an argument that is not in base {
name: "add an argument that is not in base",
base: map[string]string{ base: map[string]string{
"insecure-bind-address": "127.0.0.1", "insecure-bind-address": "127.0.0.1",
"allow-privileged": "true", "allow-privileged": "true",
@ -57,7 +60,8 @@ func TestBuildArgumentListFromMap(t *testing.T) {
"--insecure-bind-address=127.0.0.1", "--insecure-bind-address=127.0.0.1",
}, },
}, },
{ // allow empty strings in base {
name: "allow empty strings in base",
base: map[string]string{ base: map[string]string{
"insecure-bind-address": "127.0.0.1", "insecure-bind-address": "127.0.0.1",
"allow-privileged": "true", "allow-privileged": "true",
@ -73,7 +77,8 @@ func TestBuildArgumentListFromMap(t *testing.T) {
"--something-that-allows-empty-string=", "--something-that-allows-empty-string=",
}, },
}, },
{ // allow empty strings in overrides {
name: "allow empty strings in overrides",
base: map[string]string{ base: map[string]string{
"insecure-bind-address": "127.0.0.1", "insecure-bind-address": "127.0.0.1",
"allow-privileged": "true", "allow-privileged": "true",
@ -93,20 +98,23 @@ func TestBuildArgumentListFromMap(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := BuildArgumentListFromMap(rt.base, rt.overrides) actual := BuildArgumentListFromMap(rt.base, rt.overrides)
if !reflect.DeepEqual(actual, rt.expected) { if !reflect.DeepEqual(actual, rt.expected) {
t.Errorf("failed BuildArgumentListFromMap:\nexpected:\n%v\nsaw:\n%v", rt.expected, actual) t.Errorf("failed BuildArgumentListFromMap:\nexpected:\n%v\nsaw:\n%v", rt.expected, actual)
} }
})
} }
} }
func TestParseArgumentListToMap(t *testing.T) { func TestParseArgumentListToMap(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
args []string args []string
expectedMap map[string]string expectedMap map[string]string
}{ }{
{ {
// normal case name: "normal case",
args: []string{ args: []string{
"--admission-control=NamespaceLifecycle,LimitRanger", "--admission-control=NamespaceLifecycle,LimitRanger",
"--insecure-bind-address=127.0.0.1", "--insecure-bind-address=127.0.0.1",
@ -119,7 +127,7 @@ func TestParseArgumentListToMap(t *testing.T) {
}, },
}, },
{ {
// test that feature-gates is working name: "test that feature-gates is working",
args: []string{ args: []string{
"--admission-control=NamespaceLifecycle,LimitRanger", "--admission-control=NamespaceLifecycle,LimitRanger",
"--insecure-bind-address=127.0.0.1", "--insecure-bind-address=127.0.0.1",
@ -134,7 +142,7 @@ func TestParseArgumentListToMap(t *testing.T) {
}, },
}, },
{ {
// test that a binary can be the first arg name: "test that a binary can be the first arg",
args: []string{ args: []string{
"kube-apiserver", "kube-apiserver",
"--admission-control=NamespaceLifecycle,LimitRanger", "--admission-control=NamespaceLifecycle,LimitRanger",
@ -152,21 +160,24 @@ func TestParseArgumentListToMap(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actualMap := ParseArgumentListToMap(rt.args) actualMap := ParseArgumentListToMap(rt.args)
if !reflect.DeepEqual(actualMap, rt.expectedMap) { if !reflect.DeepEqual(actualMap, rt.expectedMap) {
t.Errorf("failed ParseArgumentListToMap:\nexpected:\n%v\nsaw:\n%v", rt.expectedMap, actualMap) t.Errorf("failed ParseArgumentListToMap:\nexpected:\n%v\nsaw:\n%v", rt.expectedMap, actualMap)
} }
})
} }
} }
func TestReplaceArgument(t *testing.T) { func TestReplaceArgument(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
args []string args []string
mutateFunc func(map[string]string) map[string]string mutateFunc func(map[string]string) map[string]string
expectedArgs []string expectedArgs []string
}{ }{
{ {
// normal case name: "normal case",
args: []string{ args: []string{
"kube-apiserver", "kube-apiserver",
"--admission-control=NamespaceLifecycle,LimitRanger", "--admission-control=NamespaceLifecycle,LimitRanger",
@ -185,7 +196,7 @@ func TestReplaceArgument(t *testing.T) {
}, },
}, },
{ {
// normal case name: "another normal case",
args: []string{ args: []string{
"kube-apiserver", "kube-apiserver",
"--admission-control=NamespaceLifecycle,LimitRanger", "--admission-control=NamespaceLifecycle,LimitRanger",
@ -207,21 +218,24 @@ func TestReplaceArgument(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actualArgs := ReplaceArgument(rt.args, rt.mutateFunc) actualArgs := ReplaceArgument(rt.args, rt.mutateFunc)
sort.Strings(actualArgs) sort.Strings(actualArgs)
sort.Strings(rt.expectedArgs) sort.Strings(rt.expectedArgs)
if !reflect.DeepEqual(actualArgs, rt.expectedArgs) { if !reflect.DeepEqual(actualArgs, rt.expectedArgs) {
t.Errorf("failed ReplaceArgument:\nexpected:\n%v\nsaw:\n%v", rt.expectedArgs, actualArgs) t.Errorf("failed ReplaceArgument:\nexpected:\n%v\nsaw:\n%v", rt.expectedArgs, actualArgs)
} }
})
} }
} }
func TestRoundtrip(t *testing.T) { func TestRoundtrip(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
args []string args []string
}{ }{
{ {
// normal case name: "normal case",
args: []string{ args: []string{
"--admission-control=NamespaceLifecycle,LimitRanger", "--admission-control=NamespaceLifecycle,LimitRanger",
"--insecure-bind-address=127.0.0.1", "--insecure-bind-address=127.0.0.1",
@ -229,7 +243,7 @@ func TestRoundtrip(t *testing.T) {
}, },
}, },
{ {
// test that feature-gates is working name: "test that feature-gates is working",
args: []string{ args: []string{
"--admission-control=NamespaceLifecycle,LimitRanger", "--admission-control=NamespaceLifecycle,LimitRanger",
"--insecure-bind-address=127.0.0.1", "--insecure-bind-address=127.0.0.1",
@ -240,6 +254,7 @@ func TestRoundtrip(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
// These two methods should be each other's opposite functions, test that by chaining the methods and see if you get the same result back // These two methods should be each other's opposite functions, test that by chaining the methods and see if you get the same result back
actual := BuildArgumentListFromMap(ParseArgumentListToMap(rt.args), map[string]string{}) actual := BuildArgumentListFromMap(ParseArgumentListToMap(rt.args), map[string]string{})
sort.Strings(actual) sort.Strings(actual)
@ -248,78 +263,80 @@ func TestRoundtrip(t *testing.T) {
if !reflect.DeepEqual(actual, rt.args) { if !reflect.DeepEqual(actual, rt.args) {
t.Errorf("failed TestRoundtrip:\nexpected:\n%v\nsaw:\n%v", rt.args, actual) t.Errorf("failed TestRoundtrip:\nexpected:\n%v\nsaw:\n%v", rt.args, actual)
} }
})
} }
} }
func TestParseArgument(t *testing.T) { func TestParseArgument(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
arg string arg string
expectedKey string expectedKey string
expectedVal string expectedVal string
expectedErr bool expectedErr bool
}{ }{
{ {
// cannot be empty name: "arg cannot be empty",
arg: "", arg: "",
expectedErr: true, expectedErr: true,
}, },
{ {
// must contain -- and = name: "arg must contain -- and =",
arg: "a", arg: "a",
expectedErr: true, expectedErr: true,
}, },
{ {
// must contain -- and = name: "arg must contain -- and =",
arg: "a-z", arg: "a-z",
expectedErr: true, expectedErr: true,
}, },
{ {
// must contain -- name: "arg must contain --",
arg: "a=b", arg: "a=b",
expectedErr: true, expectedErr: true,
}, },
{ {
// must contain a key name: "arg must contain a key",
arg: "--=b", arg: "--=b",
expectedErr: true, expectedErr: true,
}, },
{ {
// can contain key but no value name: "arg can contain key but no value",
arg: "--a=", arg: "--a=",
expectedKey: "a", expectedKey: "a",
expectedVal: "", expectedVal: "",
expectedErr: false, expectedErr: false,
}, },
{ {
// simple case name: "simple case",
arg: "--a=b", arg: "--a=b",
expectedKey: "a", expectedKey: "a",
expectedVal: "b", expectedVal: "b",
expectedErr: false, expectedErr: false,
}, },
{ {
// keys/values with '-' should be supported name: "keys/values with '-' should be supported",
arg: "--very-long-flag-name=some-value", arg: "--very-long-flag-name=some-value",
expectedKey: "very-long-flag-name", expectedKey: "very-long-flag-name",
expectedVal: "some-value", expectedVal: "some-value",
expectedErr: false, expectedErr: false,
}, },
{ {
// numbers should be handled correctly name: "numbers should be handled correctly",
arg: "--some-number=0.2", arg: "--some-number=0.2",
expectedKey: "some-number", expectedKey: "some-number",
expectedVal: "0.2", expectedVal: "0.2",
expectedErr: false, expectedErr: false,
}, },
{ {
// lists should be handled correctly name: "lists should be handled correctly",
arg: "--admission-control=foo,bar,baz", arg: "--admission-control=foo,bar,baz",
expectedKey: "admission-control", expectedKey: "admission-control",
expectedVal: "foo,bar,baz", expectedVal: "foo,bar,baz",
expectedErr: false, expectedErr: false,
}, },
{ {
// more than one '=' should be allowed name: "more than one '=' should be allowed",
arg: "--feature-gates=EnableFoo=true,EnableBar=false", arg: "--feature-gates=EnableFoo=true,EnableBar=false",
expectedKey: "feature-gates", expectedKey: "feature-gates",
expectedVal: "EnableFoo=true,EnableBar=false", expectedVal: "EnableFoo=true,EnableBar=false",
@ -328,6 +345,7 @@ func TestParseArgument(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
key, val, actual := parseArgument(rt.arg) key, val, actual := parseArgument(rt.arg)
if (actual != nil) != rt.expectedErr { if (actual != nil) != rt.expectedErr {
t.Errorf("failed parseArgument:\nexpected error:\n%t\nsaw error:\n%v", rt.expectedErr, actual) t.Errorf("failed parseArgument:\nexpected error:\n%t\nsaw error:\n%v", rt.expectedErr, actual)
@ -335,5 +353,6 @@ func TestParseArgument(t *testing.T) {
if (key != rt.expectedKey) || (val != rt.expectedVal) { if (key != rt.expectedKey) || (val != rt.expectedVal) {
t.Errorf("failed parseArgument:\nexpected key: %s\nsaw key: %s\nexpected value: %s\nsaw value: %s", rt.expectedKey, key, rt.expectedVal, val) t.Errorf("failed parseArgument:\nexpected key: %s\nsaw key: %s\nexpected value: %s\nsaw value: %s", rt.expectedKey, key, rt.expectedVal, val)
} }
})
} }
} }

View File

@ -197,19 +197,21 @@ func TestGetMasterEndpoint(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actualEndpoint, actualError := GetMasterEndpoint(rt.cfg) actualEndpoint, actualError := GetMasterEndpoint(rt.cfg)
if (actualError != nil) && !rt.expectedError { if (actualError != nil) && !rt.expectedError {
t.Errorf("%s unexpected failure: %v", rt.name, actualError) t.Errorf("%s unexpected failure: %v", rt.name, actualError)
continue return
} else if (actualError == nil) && rt.expectedError { } else if (actualError == nil) && rt.expectedError {
t.Errorf("%s passed when expected to fail", rt.name) t.Errorf("%s passed when expected to fail", rt.name)
continue return
} }
if actualEndpoint != rt.expectedEndpoint { if actualEndpoint != rt.expectedEndpoint {
t.Errorf("%s returned invalid endpoint %s, expected %s", rt.name, actualEndpoint, rt.expectedEndpoint) t.Errorf("%s returned invalid endpoint %s, expected %s", rt.name, actualEndpoint, rt.expectedEndpoint)
} }
})
} }
} }
@ -316,24 +318,26 @@ func TestParseHostPort(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actualHost, actualPort, actualError := ParseHostPort(rt.hostport) actualHost, actualPort, actualError := ParseHostPort(rt.hostport)
if (actualError != nil) && !rt.expectedError { if (actualError != nil) && !rt.expectedError {
t.Errorf("%s unexpected failure: %v", rt.name, actualError) t.Errorf("%s unexpected failure: %v", rt.name, actualError)
continue return
} else if (actualError == nil) && rt.expectedError { } else if (actualError == nil) && rt.expectedError {
t.Errorf("%s passed when expected to fail", rt.name) t.Errorf("%s passed when expected to fail", rt.name)
continue return
} }
if actualHost != rt.expectedHost { if actualHost != rt.expectedHost {
t.Errorf("%s returned invalid host %s, expected %s", rt.name, actualHost, rt.expectedHost) t.Errorf("%s returned invalid host %s, expected %s", rt.name, actualHost, rt.expectedHost)
continue return
} }
if actualPort != rt.expectedPort { if actualPort != rt.expectedPort {
t.Errorf("%s returned invalid port %s, expected %s", rt.name, actualPort, rt.expectedPort) t.Errorf("%s returned invalid port %s, expected %s", rt.name, actualPort, rt.expectedPort)
} }
})
} }
} }
@ -368,18 +372,20 @@ func TestParsePort(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actualPort, actualError := ParsePort(rt.port) actualPort, actualError := ParsePort(rt.port)
if (actualError != nil) && !rt.expectedError { if (actualError != nil) && !rt.expectedError {
t.Errorf("%s unexpected failure: %v", rt.name, actualError) t.Errorf("%s unexpected failure: %v", rt.name, actualError)
continue return
} else if (actualError == nil) && rt.expectedError { } else if (actualError == nil) && rt.expectedError {
t.Errorf("%s passed when expected to fail", rt.name) t.Errorf("%s passed when expected to fail", rt.name)
continue return
} }
if actualPort != rt.expectedPort { if actualPort != rt.expectedPort {
t.Errorf("%s returned invalid port %d, expected %d", rt.name, actualPort, rt.expectedPort) t.Errorf("%s returned invalid port %d, expected %d", rt.name, actualPort, rt.expectedPort)
} }
})
} }
} }

View File

@ -31,16 +31,18 @@ func TestCheckErr(t *testing.T) {
codeReturned = code codeReturned = code
} }
var tokenTest = []struct { var tests = []struct {
name string
e error e error
expected int expected int
}{ }{
{nil, 0}, {"error is nil", nil, 0},
{errors.New(""), DefaultErrorExitCode}, {"empty error", errors.New(""), DefaultErrorExitCode},
{&pferror{}, PreFlightExitCode}, {"preflight error", &pferror{}, PreFlightExitCode},
} }
for _, rt := range tokenTest { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
codeReturned = 0 codeReturned = 0
checkErr(rt.e, errHandle) checkErr(rt.e, errHandle)
if codeReturned != rt.expected { if codeReturned != rt.expected {
@ -50,6 +52,7 @@ func TestCheckErr(t *testing.T) {
codeReturned, codeReturned,
) )
} }
})
} }
} }
@ -58,10 +61,12 @@ func TestFormatErrMsg(t *testing.T) {
errMsg2 := "specified version to upgrade to v1.9.0-alpha.3 is higher than the kubeadm version v1.9.0-alpha.1.3121+84178212527295-dirty. Upgrade kubeadm first using the tool you used to install kubeadm" errMsg2 := "specified version to upgrade to v1.9.0-alpha.3 is higher than the kubeadm version v1.9.0-alpha.1.3121+84178212527295-dirty. Upgrade kubeadm first using the tool you used to install kubeadm"
testCases := []struct { testCases := []struct {
name string
errs []error errs []error
expect string expect string
}{ }{
{ {
name: "two errors",
errs: []error{ errs: []error{
errors.New(errMsg1), errors.New(errMsg1),
errors.New(errMsg2), errors.New(errMsg2),
@ -69,6 +74,7 @@ func TestFormatErrMsg(t *testing.T) {
expect: "\t- " + errMsg1 + "\n" + "\t- " + errMsg2 + "\n", expect: "\t- " + errMsg1 + "\n" + "\t- " + errMsg2 + "\n",
}, },
{ {
name: "one error",
errs: []error{ errs: []error{
errors.New(errMsg1), errors.New(errMsg1),
}, },
@ -77,9 +83,11 @@ func TestFormatErrMsg(t *testing.T) {
} }
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
got := FormatErrMsg(testCase.errs) got := FormatErrMsg(testCase.errs)
if got != testCase.expect { if got != testCase.expect {
t.Errorf("FormatErrMsg error, expect: %v, got: %v", testCase.expect, got) t.Errorf("FormatErrMsg error, expect: %v, got: %v", testCase.expect, got)
} }
})
} }
} }

View File

@ -81,14 +81,16 @@ type configClientWithToken struct {
func TestCreateWithCerts(t *testing.T) { func TestCreateWithCerts(t *testing.T) {
var createBasicTest = []struct { var createBasicTest = []struct {
name string
cc configClient cc configClient
ccWithCerts configClientWithCerts ccWithCerts configClientWithCerts
expected string expected string
}{ }{
{configClient{}, configClientWithCerts{}, ""}, {"empty config", configClient{}, configClientWithCerts{}, ""},
{configClient{clusterName: "kubernetes"}, configClientWithCerts{}, ""}, {"clusterName kubernetes", configClient{clusterName: "kubernetes"}, configClientWithCerts{}, ""},
} }
for _, rt := range createBasicTest { for _, rt := range createBasicTest {
t.Run(rt.name, func(t *testing.T) {
cwc := CreateWithCerts( cwc := CreateWithCerts(
rt.cc.serverURL, rt.cc.serverURL,
rt.cc.clusterName, rt.cc.clusterName,
@ -104,19 +106,22 @@ func TestCreateWithCerts(t *testing.T) {
cwc.Kind, cwc.Kind,
) )
} }
})
} }
} }
func TestCreateWithToken(t *testing.T) { func TestCreateWithToken(t *testing.T) {
var createBasicTest = []struct { var createBasicTest = []struct {
name string
cc configClient cc configClient
ccWithToken configClientWithToken ccWithToken configClientWithToken
expected string expected string
}{ }{
{configClient{}, configClientWithToken{}, ""}, {"empty config", configClient{}, configClientWithToken{}, ""},
{configClient{clusterName: "kubernetes"}, configClientWithToken{}, ""}, {"clusterName kubernetes", configClient{clusterName: "kubernetes"}, configClientWithToken{}, ""},
} }
for _, rt := range createBasicTest { for _, rt := range createBasicTest {
t.Run(rt.name, func(t *testing.T) {
cwc := CreateWithToken( cwc := CreateWithToken(
rt.cc.serverURL, rt.cc.serverURL,
rt.cc.clusterName, rt.cc.clusterName,
@ -131,6 +136,7 @@ func TestCreateWithToken(t *testing.T) {
cwc.Kind, cwc.Kind,
) )
} }
})
} }
} }
@ -152,6 +158,7 @@ func TestWriteKubeconfigToDisk(t *testing.T) {
{"test2", configClient{clusterName: "kubernetes", userName: "user2", serverURL: "localhost:8080"}, configClientWithToken{token: "cba"}, nil, []byte(configOut2)}, {"test2", configClient{clusterName: "kubernetes", userName: "user2", serverURL: "localhost:8080"}, configClientWithToken{token: "cba"}, nil, []byte(configOut2)},
} }
for _, rt := range writeConfig { for _, rt := range writeConfig {
t.Run(rt.name, func(t *testing.T) {
c := CreateWithToken( c := CreateWithToken(
rt.cc.serverURL, rt.cc.serverURL,
rt.cc.clusterName, rt.cc.clusterName,
@ -176,5 +183,6 @@ func TestWriteKubeconfigToDisk(t *testing.T) {
newFile, newFile,
) )
} }
})
} }
} }

View File

@ -70,22 +70,24 @@ func TestNewCertificateAuthority(t *testing.T) {
func TestNewCertAndKey(t *testing.T) { func TestNewCertAndKey(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
caKeySize int caKeySize int
expected bool expected bool
}{ }{
{ {
// RSA key too small name: "RSA key too small",
caKeySize: 128, caKeySize: 128,
expected: false, expected: false,
}, },
{ {
// Should succeed name: "Should succeed",
caKeySize: 2048, caKeySize: 2048,
expected: true, expected: true,
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
caKey, err := rsa.GenerateKey(rand.Reader, rt.caKeySize) caKey, err := rsa.GenerateKey(rand.Reader, rt.caKeySize)
if err != nil { if err != nil {
t.Fatalf("Couldn't create rsa Private Key") t.Fatalf("Couldn't create rsa Private Key")
@ -104,6 +106,7 @@ func TestNewCertAndKey(t *testing.T) {
(actual == nil), (actual == nil),
) )
} }
})
} }
} }
@ -111,10 +114,12 @@ func TestHasServerAuth(t *testing.T) {
caCert, caKey, _ := NewCertificateAuthority(&certutil.Config{CommonName: "kubernetes"}) caCert, caKey, _ := NewCertificateAuthority(&certutil.Config{CommonName: "kubernetes"})
var tests = []struct { var tests = []struct {
name string
config certutil.Config config certutil.Config
expected bool expected bool
}{ }{
{ {
name: "has ServerAuth",
config: certutil.Config{ config: certutil.Config{
CommonName: "test", CommonName: "test",
Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
@ -122,6 +127,7 @@ func TestHasServerAuth(t *testing.T) {
expected: true, expected: true,
}, },
{ {
name: "doesn't have ServerAuth",
config: certutil.Config{ config: certutil.Config{
CommonName: "test", CommonName: "test",
Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
@ -131,6 +137,7 @@ func TestHasServerAuth(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
cert, _, err := NewCertAndKey(caCert, caKey, &rt.config) cert, _, err := NewCertAndKey(caCert, caKey, &rt.config)
if err != nil { if err != nil {
t.Fatalf("Couldn't create cert: %v", err) t.Fatalf("Couldn't create cert: %v", err)
@ -143,6 +150,7 @@ func TestHasServerAuth(t *testing.T) {
actual, actual,
) )
} }
})
} }
} }
@ -245,22 +253,26 @@ func TestCertOrKeyExist(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
desc string
path string path string
name string name string
expected bool expected bool
}{ }{
{ {
desc: "empty path and name",
path: "", path: "",
name: "", name: "",
expected: false, expected: false,
}, },
{ {
desc: "valid path and name",
path: tmpdir, path: tmpdir,
name: "foo", name: "foo",
expected: true, expected: true,
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := CertOrKeyExist(rt.path, rt.name) actual := CertOrKeyExist(rt.path, rt.name)
if actual != rt.expected { if actual != rt.expected {
t.Errorf( t.Errorf(
@ -269,6 +281,7 @@ func TestCertOrKeyExist(t *testing.T) {
actual, actual,
) )
} }
})
} }
} }
@ -295,22 +308,26 @@ func TestTryLoadCertAndKeyFromDisk(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
desc string
path string path string
name string name string
expected bool expected bool
}{ }{
{ {
desc: "empty path and name",
path: "", path: "",
name: "", name: "",
expected: false, expected: false,
}, },
{ {
desc: "valid path and name",
path: tmpdir, path: tmpdir,
name: "foo", name: "foo",
expected: true, expected: true,
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.desc, func(t *testing.T) {
_, _, actual := TryLoadCertAndKeyFromDisk(rt.path, rt.name) _, _, actual := TryLoadCertAndKeyFromDisk(rt.path, rt.name)
if (actual == nil) != rt.expected { if (actual == nil) != rt.expected {
t.Errorf( t.Errorf(
@ -319,6 +336,7 @@ func TestTryLoadCertAndKeyFromDisk(t *testing.T) {
(actual == nil), (actual == nil),
) )
} }
})
} }
} }
@ -345,22 +363,26 @@ func TestTryLoadCertFromDisk(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
desc string
path string path string
name string name string
expected bool expected bool
}{ }{
{ {
desc: "empty path and name",
path: "", path: "",
name: "", name: "",
expected: false, expected: false,
}, },
{ {
desc: "valid path and name",
path: tmpdir, path: tmpdir,
name: "foo", name: "foo",
expected: true, expected: true,
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.desc, func(t *testing.T) {
_, actual := TryLoadCertFromDisk(rt.path, rt.name) _, actual := TryLoadCertFromDisk(rt.path, rt.name)
if (actual == nil) != rt.expected { if (actual == nil) != rt.expected {
t.Errorf( t.Errorf(
@ -369,6 +391,7 @@ func TestTryLoadCertFromDisk(t *testing.T) {
(actual == nil), (actual == nil),
) )
} }
})
} }
} }
@ -395,22 +418,26 @@ func TestTryLoadKeyFromDisk(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
desc string
path string path string
name string name string
expected bool expected bool
}{ }{
{ {
desc: "empty path and name",
path: "", path: "",
name: "", name: "",
expected: false, expected: false,
}, },
{ {
desc: "valid path and name",
path: tmpdir, path: tmpdir,
name: "foo", name: "foo",
expected: true, expected: true,
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.desc, func(t *testing.T) {
_, actual := TryLoadKeyFromDisk(rt.path, rt.name) _, actual := TryLoadKeyFromDisk(rt.path, rt.name)
if (actual == nil) != rt.expected { if (actual == nil) != rt.expected {
t.Errorf( t.Errorf(
@ -419,6 +446,7 @@ func TestTryLoadKeyFromDisk(t *testing.T) {
(actual == nil), (actual == nil),
) )
} }
})
} }
} }
@ -463,12 +491,14 @@ func TestPathForCSR(t *testing.T) {
func TestGetAPIServerAltNames(t *testing.T) { func TestGetAPIServerAltNames(t *testing.T) {
var tests = []struct { var tests = []struct {
desc string
name string name string
cfg *kubeadmapi.InitConfiguration cfg *kubeadmapi.InitConfiguration
expectedDNSNames []string expectedDNSNames []string
expectedIPAddresses []string expectedIPAddresses []string
}{ }{
{ {
desc: "empty name",
name: "", name: "",
cfg: &kubeadmapi.InitConfiguration{ cfg: &kubeadmapi.InitConfiguration{
LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4"}, LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4"},
@ -485,6 +515,7 @@ func TestGetAPIServerAltNames(t *testing.T) {
expectedIPAddresses: []string{"10.96.0.1", "1.2.3.4", "10.1.245.94", "10.1.245.95"}, expectedIPAddresses: []string{"10.96.0.1", "1.2.3.4", "10.1.245.94", "10.1.245.95"},
}, },
{ {
desc: "ControlPlaneEndpoint IP",
name: "ControlPlaneEndpoint IP", name: "ControlPlaneEndpoint IP",
cfg: &kubeadmapi.InitConfiguration{ cfg: &kubeadmapi.InitConfiguration{
LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4"}, LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4"},
@ -503,6 +534,7 @@ func TestGetAPIServerAltNames(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.desc, func(t *testing.T) {
altNames, err := GetAPIServerAltNames(rt.cfg) altNames, err := GetAPIServerAltNames(rt.cfg)
if err != nil { if err != nil {
t.Fatalf("failed calling GetAPIServerAltNames: %s: %v", rt.name, err) t.Fatalf("failed calling GetAPIServerAltNames: %s: %v", rt.name, err)
@ -535,6 +567,7 @@ func TestGetAPIServerAltNames(t *testing.T) {
t.Errorf("%s: altNames does not contain IPAddress %s but %v", rt.name, IPAddress, altNames.IPs) t.Errorf("%s: altNames does not contain IPAddress %s but %v", rt.name, IPAddress, altNames.IPs)
} }
} }
})
} }
} }
@ -569,6 +602,7 @@ func TestGetEtcdAltNames(t *testing.T) {
expectedDNSNames := []string{"myNode", "localhost", proxy} expectedDNSNames := []string{"myNode", "localhost", proxy}
for _, DNSName := range expectedDNSNames { for _, DNSName := range expectedDNSNames {
t.Run(DNSName, func(t *testing.T) {
found := false found := false
for _, val := range altNames.DNSNames { for _, val := range altNames.DNSNames {
if val == DNSName { if val == DNSName {
@ -580,10 +614,12 @@ func TestGetEtcdAltNames(t *testing.T) {
if !found { if !found {
t.Errorf("altNames does not contain DNSName %s", DNSName) t.Errorf("altNames does not contain DNSName %s", DNSName)
} }
})
} }
expectedIPAddresses := []string{"1.2.3.4", "127.0.0.1", net.IPv6loopback.String(), proxyIP} expectedIPAddresses := []string{"1.2.3.4", "127.0.0.1", net.IPv6loopback.String(), proxyIP}
for _, IPAddress := range expectedIPAddresses { for _, IPAddress := range expectedIPAddresses {
t.Run(IPAddress, func(t *testing.T) {
found := false found := false
for _, val := range altNames.IPs { for _, val := range altNames.IPs {
if val.Equal(net.ParseIP(IPAddress)) { if val.Equal(net.ParseIP(IPAddress)) {
@ -595,6 +631,7 @@ func TestGetEtcdAltNames(t *testing.T) {
if !found { if !found {
t.Errorf("altNames does not contain IPAddress %s", IPAddress) t.Errorf("altNames does not contain IPAddress %s", IPAddress)
} }
})
} }
} }
@ -627,6 +664,7 @@ func TestGetEtcdPeerAltNames(t *testing.T) {
expectedDNSNames := []string{hostname, proxy} expectedDNSNames := []string{hostname, proxy}
for _, DNSName := range expectedDNSNames { for _, DNSName := range expectedDNSNames {
t.Run(DNSName, func(t *testing.T) {
found := false found := false
for _, val := range altNames.DNSNames { for _, val := range altNames.DNSNames {
if val == DNSName { if val == DNSName {
@ -638,7 +676,6 @@ func TestGetEtcdPeerAltNames(t *testing.T) {
if !found { if !found {
t.Errorf("altNames does not contain DNSName %s", DNSName) t.Errorf("altNames does not contain DNSName %s", DNSName)
} }
}
expectedIPAddresses := []string{advertiseIP, proxyIP} expectedIPAddresses := []string{advertiseIP, proxyIP}
for _, IPAddress := range expectedIPAddresses { for _, IPAddress := range expectedIPAddresses {
@ -654,4 +691,6 @@ func TestGetEtcdPeerAltNames(t *testing.T) {
t.Errorf("altNames does not contain IPAddress %s", IPAddress) t.Errorf("altNames does not contain IPAddress %s", IPAddress)
} }
} }
})
}
} }

View File

@ -166,6 +166,7 @@ func TestComponentProbe(t *testing.T) {
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := ComponentProbe(rt.cfg, rt.component, rt.port, rt.path, rt.scheme) actual := ComponentProbe(rt.cfg, rt.component, rt.port, rt.path, rt.scheme)
if actual.Handler.HTTPGet.Host != rt.expected { if actual.Handler.HTTPGet.Host != rt.expected {
t.Errorf("%s test case failed:\n\texpected: %s\n\t actual: %s", t.Errorf("%s test case failed:\n\texpected: %s\n\t actual: %s",
@ -187,6 +188,7 @@ func TestComponentProbe(t *testing.T) {
rt.name, rt.scheme, rt.name, rt.scheme,
actual.Handler.HTTPGet.Scheme) actual.Handler.HTTPGet.Scheme)
} }
})
} }
} }
@ -330,6 +332,7 @@ func TestEtcdProbe(t *testing.T) {
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
// TODO: Make EtcdProbe accept a ClusterConfiguration object instead of InitConfiguration // TODO: Make EtcdProbe accept a ClusterConfiguration object instead of InitConfiguration
initcfg := &kubeadmapi.InitConfiguration{ initcfg := &kubeadmapi.InitConfiguration{
ClusterConfiguration: *rt.cfg, ClusterConfiguration: *rt.cfg,
@ -340,6 +343,7 @@ func TestEtcdProbe(t *testing.T) {
rt.name, rt.expected, rt.name, rt.expected,
actual.Handler.Exec.Command[2]) actual.Handler.Exec.Command[2])
} }
})
} }
} }
@ -376,6 +380,7 @@ func TestComponentPod(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
c := v1.Container{Name: rt.name} c := v1.Container{Name: rt.name}
actual := ComponentPod(c, map[string]v1.Volume{}) actual := ComponentPod(c, map[string]v1.Volume{})
if !reflect.DeepEqual(rt.expected, actual) { if !reflect.DeepEqual(rt.expected, actual) {
@ -385,6 +390,7 @@ func TestComponentPod(t *testing.T) {
actual, actual,
) )
} }
})
} }
} }
@ -413,6 +419,7 @@ func TestNewVolume(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := NewVolume(rt.name, rt.path, rt.pathType) actual := NewVolume(rt.name, rt.path, rt.pathType)
if !reflect.DeepEqual(actual, rt.expected) { if !reflect.DeepEqual(actual, rt.expected) {
t.Errorf( t.Errorf(
@ -421,6 +428,7 @@ func TestNewVolume(t *testing.T) {
actual, actual,
) )
} }
})
} }
} }
@ -454,6 +462,7 @@ func TestNewVolumeMount(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := NewVolumeMount(rt.name, rt.path, rt.ro) actual := NewVolumeMount(rt.name, rt.path, rt.ro)
if !reflect.DeepEqual(actual, rt.expected) { if !reflect.DeepEqual(actual, rt.expected) {
t.Errorf( t.Errorf(
@ -462,6 +471,7 @@ func TestNewVolumeMount(t *testing.T) {
actual, actual,
) )
} }
})
} }
} }
func TestVolumeMapToSlice(t *testing.T) { func TestVolumeMapToSlice(t *testing.T) {
@ -508,11 +518,13 @@ func TestVolumeMountMapToSlice(t *testing.T) {
func TestGetExtraParameters(t *testing.T) { func TestGetExtraParameters(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
overrides map[string]string overrides map[string]string
defaults map[string]string defaults map[string]string
expected []string expected []string
}{ }{
{ {
name: "with admission-control default NamespaceLifecycle",
overrides: map[string]string{ overrides: map[string]string{
"admission-control": "NamespaceLifecycle,LimitRanger", "admission-control": "NamespaceLifecycle,LimitRanger",
}, },
@ -528,6 +540,7 @@ func TestGetExtraParameters(t *testing.T) {
}, },
}, },
{ {
name: "without admission-control default",
overrides: map[string]string{ overrides: map[string]string{
"admission-control": "NamespaceLifecycle,LimitRanger", "admission-control": "NamespaceLifecycle,LimitRanger",
}, },
@ -544,12 +557,14 @@ func TestGetExtraParameters(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := GetExtraParameters(rt.overrides, rt.defaults) actual := GetExtraParameters(rt.overrides, rt.defaults)
sort.Strings(actual) sort.Strings(actual)
sort.Strings(rt.expected) sort.Strings(rt.expected)
if !reflect.DeepEqual(actual, rt.expected) { if !reflect.DeepEqual(actual, rt.expected) {
t.Errorf("failed getExtraParameters:\nexpected:\n%v\nsaw:\n%v", rt.expected, actual) t.Errorf("failed getExtraParameters:\nexpected:\n%v\nsaw:\n%v", rt.expected, actual)
} }
})
} }
} }
@ -599,6 +614,7 @@ func TestReadStaticPodFromDisk(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.description, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -620,6 +636,7 @@ func TestReadStaticPodFromDisk(t *testing.T) {
actualErr, actualErr,
) )
} }
})
} }
} }
@ -657,6 +674,7 @@ func TestManifestFilesAreEqual(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.description, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -690,5 +708,6 @@ func TestManifestFilesAreEqual(t *testing.T) {
actualErr, actualErr,
) )
} }
})
} }
} }

View File

@ -30,13 +30,14 @@ const (
func TestParseTemplate(t *testing.T) { func TestParseTemplate(t *testing.T) {
var tmplTests = []struct { var tmplTests = []struct {
name string
template string template string
data interface{} data interface{}
output string output string
errExpected bool errExpected bool
}{ }{
// should parse a valid template and set the right values
{ {
name: "should parse a valid template and set the right values",
template: validTmpl, template: validTmpl,
data: struct{ ImageRepository, Arch string }{ data: struct{ ImageRepository, Arch string }{
ImageRepository: "k8s.gcr.io", ImageRepository: "k8s.gcr.io",
@ -45,8 +46,8 @@ func TestParseTemplate(t *testing.T) {
output: validTmplOut, output: validTmplOut,
errExpected: false, errExpected: false,
}, },
// should noop if there aren't any {{ .foo }} present
{ {
name: "should noop if there aren't any {{ .foo }} present",
template: doNothing, template: doNothing,
data: struct{ ImageRepository, Arch string }{ data: struct{ ImageRepository, Arch string }{
ImageRepository: "k8s.gcr.io", ImageRepository: "k8s.gcr.io",
@ -55,15 +56,15 @@ func TestParseTemplate(t *testing.T) {
output: doNothing, output: doNothing,
errExpected: false, errExpected: false,
}, },
// invalid syntax, passing nil
{ {
name: "invalid syntax, passing nil",
template: invalidTmpl1, template: invalidTmpl1,
data: nil, data: nil,
output: "", output: "",
errExpected: true, errExpected: true,
}, },
// invalid syntax
{ {
name: "invalid syntax",
template: invalidTmpl2, template: invalidTmpl2,
data: struct{}{}, data: struct{}{},
output: "", output: "",
@ -71,6 +72,7 @@ func TestParseTemplate(t *testing.T) {
}, },
} }
for _, tt := range tmplTests { for _, tt := range tmplTests {
t.Run(tt.name, func(t *testing.T) {
outbytes, err := ParseTemplate(tt.template, tt.data) outbytes, err := ParseTemplate(tt.template, tt.data)
if tt.errExpected != (err != nil) { if tt.errExpected != (err != nil) {
t.Errorf( t.Errorf(
@ -86,5 +88,6 @@ func TestParseTemplate(t *testing.T) {
outbytes, outbytes,
) )
} }
})
} }
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package util package util
import ( import (
"fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"path" "path"
@ -48,6 +49,7 @@ func TestValidVersion(t *testing.T) {
"v1.6.1+coreos.0", "v1.6.1+coreos.0",
} }
for _, s := range validVersions { for _, s := range validVersions {
t.Run(s, func(t *testing.T) {
ver, err := KubernetesReleaseVersion(s) ver, err := KubernetesReleaseVersion(s)
t.Log("Valid: ", s, ver, err) t.Log("Valid: ", s, ver, err)
if err != nil { if err != nil {
@ -56,6 +58,7 @@ func TestValidVersion(t *testing.T) {
if ver != s { if ver != s {
t.Errorf("KubernetesReleaseVersion should return same valid version string. %q != %q", s, ver) t.Errorf("KubernetesReleaseVersion should return same valid version string. %q != %q", s, ver)
} }
})
} }
} }
@ -68,6 +71,7 @@ func TestInvalidVersion(t *testing.T) {
"something1.2", "something1.2",
} }
for _, s := range invalidVersions { for _, s := range invalidVersions {
t.Run(s, func(t *testing.T) {
ver, err := KubernetesReleaseVersion(s) ver, err := KubernetesReleaseVersion(s)
t.Log("Invalid: ", s, ver, err) t.Log("Invalid: ", s, ver, err)
if err == nil { if err == nil {
@ -76,6 +80,7 @@ func TestInvalidVersion(t *testing.T) {
if ver != "" { if ver != "" {
t.Errorf("KubernetesReleaseVersion should return empty string in case of error. Returned %q for version %q", ver, s) t.Errorf("KubernetesReleaseVersion should return empty string in case of error. Returned %q for version %q", ver, s)
} }
})
} }
} }
@ -86,6 +91,7 @@ func TestValidConvenientForUserVersion(t *testing.T) {
"1.6.1_coreos.0", "1.6.1_coreos.0",
} }
for _, s := range validVersions { for _, s := range validVersions {
t.Run(s, func(t *testing.T) {
ver, err := KubernetesReleaseVersion(s) ver, err := KubernetesReleaseVersion(s)
t.Log("Valid: ", s, ver, err) t.Log("Valid: ", s, ver, err)
if err != nil { if err != nil {
@ -94,6 +100,7 @@ func TestValidConvenientForUserVersion(t *testing.T) {
if ver != "v"+s { if ver != "v"+s {
t.Errorf("KubernetesReleaseVersion should return semantic version string. %q vs. %q", s, ver) t.Errorf("KubernetesReleaseVersion should return semantic version string. %q vs. %q", s, ver)
} }
})
} }
} }
@ -128,6 +135,7 @@ func TestVersionFromNetwork(t *testing.T) {
kubeReleaseBucketURL = server.URL kubeReleaseBucketURL = server.URL
for k, v := range cases { for k, v := range cases {
t.Run(k, func(t *testing.T) {
ver, err := KubernetesReleaseVersion(k) ver, err := KubernetesReleaseVersion(k)
t.Logf("Key: %q. Result: %q, Error: %v", k, ver, err) t.Logf("Key: %q. Result: %q, Error: %v", k, ver, err)
switch { switch {
@ -138,6 +146,7 @@ func TestVersionFromNetwork(t *testing.T) {
case ver != v.Expected: case ver != v.Expected:
t.Errorf("KubernetesReleaseVersion: unexpected result for key %q. Expected: %q Actual: %q", k, v.Expected, ver) t.Errorf("KubernetesReleaseVersion: unexpected result for key %q. Expected: %q Actual: %q", k, v.Expected, ver)
} }
})
} }
} }
@ -158,11 +167,13 @@ func TestVersionToTag(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
t.Run(fmt.Sprintf("input:%s/expected:%s", tc.input, tc.expected), func(t *testing.T) {
tag := KubernetesVersionToImageTag(tc.input) tag := KubernetesVersionToImageTag(tc.input)
t.Logf("KubernetesVersionToImageTag: Input: %q. Result: %q. Expected: %q", tc.input, tag, tc.expected) t.Logf("KubernetesVersionToImageTag: Input: %q. Result: %q. Expected: %q", tc.input, tag, tc.expected)
if tag != tc.expected { if tag != tc.expected {
t.Errorf("failed KubernetesVersionToImageTag: Input: %q. Result: %q. Expected: %q", tc.input, tag, tc.expected) t.Errorf("failed KubernetesVersionToImageTag: Input: %q. Result: %q. Expected: %q", tc.input, tag, tc.expected)
} }
})
} }
} }
@ -194,6 +205,7 @@ func TestSplitVersion(t *testing.T) {
kubeReleaseBucketURL = "https://dl.k8s.io" kubeReleaseBucketURL = "https://dl.k8s.io"
for _, tc := range cases { for _, tc := range cases {
t.Run(fmt.Sprintf("input:%s/label:%s", tc.input, tc.label), func(t *testing.T) {
bucket, label, err := splitVersion(tc.input) bucket, label, err := splitVersion(tc.input)
switch { switch {
case err != nil && tc.valid: case err != nil && tc.valid:
@ -205,7 +217,7 @@ func TestSplitVersion(t *testing.T) {
case label != tc.label: case label != tc.label:
t.Errorf("splitVersion: unexpected label result for key %q. Expected: %q Actual: %q", tc.input, tc.label, label) t.Errorf("splitVersion: unexpected label result for key %q. Expected: %q Actual: %q", tc.input, tc.label, label)
} }
})
} }
} }
@ -227,13 +239,14 @@ func TestKubernetesIsCIVersion(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
t.Run(fmt.Sprintf("input:%s/expected:%t", tc.input, tc.expected), func(t *testing.T) {
result := KubernetesIsCIVersion(tc.input) result := KubernetesIsCIVersion(tc.input)
t.Logf("KubernetesIsCIVersion: Input: %q. Result: %v. Expected: %v", tc.input, result, tc.expected) t.Logf("KubernetesIsCIVersion: Input: %q. Result: %v. Expected: %v", tc.input, result, tc.expected)
if result != tc.expected { if result != tc.expected {
t.Errorf("failed KubernetesIsCIVersion: Input: %q. Result: %v. Expected: %v", tc.input, result, tc.expected) t.Errorf("failed KubernetesIsCIVersion: Input: %q. Result: %v. Expected: %v", tc.input, result, tc.expected)
} }
})
} }
} }
// Validate KubernetesReleaseVersion but with bucket prefixes // Validate KubernetesReleaseVersion but with bucket prefixes
@ -258,6 +271,7 @@ func TestCIBuildVersion(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
t.Run(fmt.Sprintf("input:%s/expected:%s", tc.input, tc.expected), func(t *testing.T) {
ver, err := KubernetesReleaseVersion(tc.input) ver, err := KubernetesReleaseVersion(tc.input)
t.Logf("Input: %q. Result: %q, Error: %v", tc.input, ver, err) t.Logf("Input: %q. Result: %q, Error: %v", tc.input, ver, err)
switch { switch {
@ -268,6 +282,7 @@ func TestCIBuildVersion(t *testing.T) {
case ver != tc.expected: case ver != tc.expected:
t.Errorf("KubernetesReleaseVersion: unexpected result for input %q. Expected: %q Actual: %q", tc.input, tc.expected, ver) t.Errorf("KubernetesReleaseVersion: unexpected result for input %q. Expected: %q Actual: %q", tc.input, tc.expected, ver)
} }
})
} }
} }
@ -284,10 +299,12 @@ func TestNormalizedBuildVersionVersion(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
t.Run(fmt.Sprintf("input:%s/expected:%s", tc.input, tc.expected), func(t *testing.T) {
output := normalizedBuildVersion(tc.input) output := normalizedBuildVersion(tc.input)
if output != tc.expected { if output != tc.expected {
t.Errorf("normalizedBuildVersion: unexpected output %q for input %q. Expected: %q", output, tc.input, tc.expected) t.Errorf("normalizedBuildVersion: unexpected output %q for input %q. Expected: %q", output, tc.input, tc.expected)
} }
})
} }
} }