kubeadm: use t.Run in app/phases

Used T.Run API for kubeadm tests in app/phases/*

This should improve testing output and make it more visible
which test is doing what.

Signed-off-by: Ed Bartosh <eduard.bartosh@intel.com>
This commit is contained in:
Ed Bartosh 2019-03-27 19:39:30 +01:00
parent 9518d522ec
commit 296df304a4
7 changed files with 654 additions and 575 deletions

View File

@ -58,6 +58,7 @@ func TestCreateServiceAccount(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset() client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil { if tc.createErr != nil {
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) { client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
@ -70,7 +71,7 @@ func TestCreateServiceAccount(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name) t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
} }
continue return
} else if !tc.expectErr && err != nil { } else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err) t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
} }
@ -86,17 +87,18 @@ func TestCreateServiceAccount(t *testing.T) {
tc.name, action.GetVerb(), action.GetResource().Resource) tc.name, action.GetVerb(), action.GetResource().Resource)
} }
} }
})
} }
} }
func TestCompileManifests(t *testing.T) { func TestCompileManifests(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
manifest string manifest string
data interface{} data interface{}
expected bool
}{ }{
{ {
name: "KubeDNSDeployment manifest",
manifest: KubeDNSDeployment, manifest: KubeDNSDeployment,
data: struct{ DeploymentName, KubeDNSImage, DNSMasqImage, SidecarImage, DNSBindAddr, DNSProbeAddr, DNSDomain, ControlPlaneTaintKey string }{ data: struct{ DeploymentName, KubeDNSImage, DNSMasqImage, SidecarImage, DNSBindAddr, DNSProbeAddr, DNSDomain, ControlPlaneTaintKey string }{
DeploymentName: "foo", DeploymentName: "foo",
@ -108,32 +110,25 @@ func TestCompileManifests(t *testing.T) {
DNSDomain: "foo", DNSDomain: "foo",
ControlPlaneTaintKey: "foo", ControlPlaneTaintKey: "foo",
}, },
expected: true,
}, },
{ {
name: "KubeDNSService manifest",
manifest: KubeDNSService, manifest: KubeDNSService,
data: struct{ DNSIP string }{ data: struct{ DNSIP string }{
DNSIP: "foo", DNSIP: "foo",
}, },
expected: true,
}, },
{ {
name: "CoreDNSDeployment manifest",
manifest: CoreDNSDeployment, manifest: CoreDNSDeployment,
data: struct{ DeploymentName, Image, ControlPlaneTaintKey string }{ data: struct{ DeploymentName, Image, ControlPlaneTaintKey string }{
DeploymentName: "foo", DeploymentName: "foo",
Image: "foo", Image: "foo",
ControlPlaneTaintKey: "foo", ControlPlaneTaintKey: "foo",
}, },
expected: true,
},
{
manifest: KubeDNSService,
data: struct{ DNSIP string }{
DNSIP: "foo",
},
expected: true,
}, },
{ {
name: "CoreDNSConfigMap manifest",
manifest: CoreDNSConfigMap, manifest: CoreDNSConfigMap,
data: struct{ DNSDomain, Federation, UpstreamNameserver, StubDomain string }{ data: struct{ DNSDomain, Federation, UpstreamNameserver, StubDomain string }{
DNSDomain: "foo", DNSDomain: "foo",
@ -141,35 +136,35 @@ func TestCompileManifests(t *testing.T) {
UpstreamNameserver: "foo", UpstreamNameserver: "foo",
StubDomain: "foo", StubDomain: "foo",
}, },
expected: true,
}, },
} }
for _, rt := range tests { for _, rt := range tests {
_, actual := kubeadmutil.ParseTemplate(rt.manifest, rt.data) t.Run(rt.name, func(t *testing.T) {
if (actual == nil) != rt.expected { _, err := kubeadmutil.ParseTemplate(rt.manifest, rt.data)
t.Errorf( if err != nil {
"failed CompileManifests:\n\texpected: %t\n\t actual: %t", t.Errorf("unexpected ParseTemplate failure: %+v", err)
rt.expected,
(actual == nil),
)
} }
})
} }
} }
func TestGetDNSIP(t *testing.T) { func TestGetDNSIP(t *testing.T) {
var tests = []struct { var tests = []struct {
svcSubnet, expectedDNSIP string name, svcSubnet, expectedDNSIP string
}{ }{
{ {
name: "subnet mask 12",
svcSubnet: "10.96.0.0/12", svcSubnet: "10.96.0.0/12",
expectedDNSIP: "10.96.0.10", expectedDNSIP: "10.96.0.10",
}, },
{ {
name: "subnet mask 26",
svcSubnet: "10.87.116.64/26", svcSubnet: "10.87.116.64/26",
expectedDNSIP: "10.87.116.74", expectedDNSIP: "10.87.116.74",
}, },
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
dnsIP, err := kubeadmconstants.GetDNSIP(rt.svcSubnet) dnsIP, err := kubeadmconstants.GetDNSIP(rt.svcSubnet)
if err != nil { if err != nil {
t.Fatalf("couldn't get dnsIP : %v", err) t.Fatalf("couldn't get dnsIP : %v", err)
@ -183,16 +178,19 @@ func TestGetDNSIP(t *testing.T) {
actualDNSIP, actualDNSIP,
) )
} }
})
} }
} }
func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) { func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
testCases := []struct { testCases := []struct {
name string
configMap *v1.ConfigMap configMap *v1.ConfigMap
expectOne string expectOne string
expectTwo string expectTwo string
}{ }{
{ {
name: "valid call 1",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns", Name: "kube-dns",
@ -234,6 +232,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
}`, }`,
}, },
{ {
name: "empty call",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kubedns", Name: "kubedns",
@ -244,6 +243,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
expectOne: "", expectOne: "",
}, },
{ {
name: "valid call 2",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns", Name: "kube-dns",
@ -285,6 +285,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
}`, }`,
}, },
{ {
name: "missing stubDomains",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns", Name: "kube-dns",
@ -299,6 +300,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
out, err := translateStubDomainOfKubeDNSToForwardCoreDNS(kubeDNSStubDomain, testCase.configMap) out, err := translateStubDomainOfKubeDNSToForwardCoreDNS(kubeDNSStubDomain, testCase.configMap)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
@ -306,15 +308,18 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
if !strings.Contains(out, testCase.expectOne) && !strings.Contains(out, testCase.expectTwo) { if !strings.Contains(out, testCase.expectOne) && !strings.Contains(out, testCase.expectTwo) {
t.Errorf("expected to find %q or %q in output: %q", testCase.expectOne, testCase.expectTwo, out) t.Errorf("expected to find %q or %q in output: %q", testCase.expectOne, testCase.expectTwo, out)
} }
})
} }
} }
func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) { func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
testCases := []struct { testCases := []struct {
name string
configMap *v1.ConfigMap configMap *v1.ConfigMap
expect string expect string
}{ }{
{ {
name: "expect resolv.conf",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns", Name: "kube-dns",
@ -325,6 +330,7 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
expect: "/etc/resolv.conf", expect: "/etc/resolv.conf",
}, },
{ {
name: "expect list of Name Server IP addresses",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kubedns", Name: "kubedns",
@ -339,6 +345,7 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
expect: "8.8.8.8 8.8.4.4 4.4.4.4", expect: "8.8.8.8 8.8.4.4 4.4.4.4",
}, },
{ {
name: "no stubDomains: expect list of Name Server IP addresses",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kubedns", Name: "kubedns",
@ -353,6 +360,7 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
out, err := translateUpstreamNameServerOfKubeDNSToUpstreamProxyCoreDNS(kubeDNSUpstreamNameservers, testCase.configMap) out, err := translateUpstreamNameServerOfKubeDNSToUpstreamProxyCoreDNS(kubeDNSUpstreamNameservers, testCase.configMap)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
@ -360,16 +368,19 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
if !strings.Contains(out, testCase.expect) { if !strings.Contains(out, testCase.expect) {
t.Errorf("expected to find %q in output: %q", testCase.expect, out) t.Errorf("expected to find %q in output: %q", testCase.expect, out)
} }
})
} }
} }
func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) { func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
testCases := []struct { testCases := []struct {
name string
configMap *v1.ConfigMap configMap *v1.ConfigMap
expectOne string expectOne string
expectTwo string expectTwo string
}{ }{
{ {
name: "valid call",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns", Name: "kube-dns",
@ -394,6 +405,7 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
}`, }`,
}, },
{ {
name: "empty data",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kubedns", Name: "kubedns",
@ -404,6 +416,7 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
expectOne: "", expectOne: "",
}, },
{ {
name: "missing federations data",
configMap: &v1.ConfigMap{ configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns", Name: "kube-dns",
@ -419,6 +432,7 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
out, err := translateFederationsofKubeDNSToCoreDNS(kubeDNSFederation, "cluster.local", testCase.configMap) out, err := translateFederationsofKubeDNSToCoreDNS(kubeDNSFederation, "cluster.local", testCase.configMap)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
@ -426,15 +440,18 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
if !strings.Contains(out, testCase.expectOne) && !strings.Contains(out, testCase.expectTwo) { if !strings.Contains(out, testCase.expectOne) && !strings.Contains(out, testCase.expectTwo) {
t.Errorf("expected to find %q or %q in output: %q", testCase.expectOne, testCase.expectTwo, out) t.Errorf("expected to find %q or %q in output: %q", testCase.expectOne, testCase.expectTwo, out)
} }
})
} }
} }
func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) { func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
testCases := []struct { testCases := []struct {
name string
manifest string manifest string
data interface{} data interface{}
}{ }{
{ {
name: "KubeDNSDeployment",
manifest: KubeDNSDeployment, manifest: KubeDNSDeployment,
data: struct{ DeploymentName, KubeDNSImage, DNSMasqImage, SidecarImage, DNSBindAddr, DNSProbeAddr, DNSDomain, ControlPlaneTaintKey string }{ data: struct{ DeploymentName, KubeDNSImage, DNSMasqImage, SidecarImage, DNSBindAddr, DNSProbeAddr, DNSDomain, ControlPlaneTaintKey string }{
DeploymentName: "foo", DeploymentName: "foo",
@ -448,6 +465,7 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
}, },
}, },
{ {
name: "CoreDNSDeployment",
manifest: CoreDNSDeployment, manifest: CoreDNSDeployment,
data: struct{ DeploymentName, Image, ControlPlaneTaintKey string }{ data: struct{ DeploymentName, Image, ControlPlaneTaintKey string }{
DeploymentName: "foo", DeploymentName: "foo",
@ -457,6 +475,7 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
deploymentBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data) deploymentBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
deployment := &apps.Deployment{} deployment := &apps.Deployment{}
if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), deploymentBytes, deployment); err != nil { if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), deploymentBytes, deployment); err != nil {
@ -465,5 +484,6 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
if deployment.Spec.Template.Spec.PriorityClassName != "system-cluster-critical" { if deployment.Spec.Template.Spec.PriorityClassName != "system-cluster-critical" {
t.Errorf("expected to see system-cluster-critical priority class name. Got %q instead", deployment.Spec.Template.Spec.PriorityClassName) t.Errorf("expected to see system-cluster-critical priority class name. Got %q instead", deployment.Spec.Template.Spec.PriorityClassName)
} }
})
} }
} }

View File

@ -62,6 +62,7 @@ func TestCreateServiceAccount(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset() client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil { if tc.createErr != nil {
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) { client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
@ -74,7 +75,7 @@ func TestCreateServiceAccount(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name) t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
} }
continue return
} else if !tc.expectErr && err != nil { } else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err) t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
} }
@ -90,17 +91,19 @@ func TestCreateServiceAccount(t *testing.T) {
tc.name, action.GetVerb(), action.GetResource().Resource) tc.name, action.GetVerb(), action.GetResource().Resource)
} }
} }
})
} }
} }
func TestCompileManifests(t *testing.T) { func TestCompileManifests(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
manifest string manifest string
data interface{} data interface{}
expected bool expected bool
}{ }{
{ {
name: "KubeProxyConfigMap19",
manifest: KubeProxyConfigMap19, manifest: KubeProxyConfigMap19,
data: struct { data: struct {
ControlPlaneEndpoint, ProxyConfig, ProxyConfigMap, ProxyConfigMapKey string ControlPlaneEndpoint, ProxyConfig, ProxyConfigMap, ProxyConfigMapKey string
@ -110,28 +113,24 @@ func TestCompileManifests(t *testing.T) {
ProxyConfigMap: "bar", ProxyConfigMap: "bar",
ProxyConfigMapKey: "baz", ProxyConfigMapKey: "baz",
}, },
expected: true,
}, },
{ {
name: "KubeProxyDaemonSet19",
manifest: KubeProxyDaemonSet19, manifest: KubeProxyDaemonSet19,
data: struct{ Image, ProxyConfigMap, ProxyConfigMapKey string }{ data: struct{ Image, ProxyConfigMap, ProxyConfigMapKey string }{
Image: "foo", Image: "foo",
ProxyConfigMap: "bar", ProxyConfigMap: "bar",
ProxyConfigMapKey: "baz", ProxyConfigMapKey: "baz",
}, },
expected: true,
}, },
} }
for _, rt := range tests { for _, rt := range tests {
_, actual := kubeadmutil.ParseTemplate(rt.manifest, rt.data) t.Run(rt.name, func(t *testing.T) {
if (actual == nil) != rt.expected { _, err := kubeadmutil.ParseTemplate(rt.manifest, rt.data)
t.Errorf( if err != nil {
"failed to compile %s manifest:\n\texpected: %t\n\t actual: %t", t.Errorf("unexpected ParseTemplate faiure: %+v", err)
rt.manifest,
rt.expected,
(actual == nil),
)
} }
})
} }
} }
@ -173,7 +172,7 @@ func TestEnsureProxyAddon(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create a fake client and set up default test configuration // Create a fake client and set up default test configuration
client := clientsetfake.NewSimpleClientset() client := clientsetfake.NewSimpleClientset()
// TODO: Consider using a YAML file instead for this that makes it possible to specify YAML documents for the ComponentConfigs // TODO: Consider using a YAML file instead for this that makes it possible to specify YAML documents for the ComponentConfigs
@ -207,7 +206,7 @@ func TestEnsureProxyAddon(t *testing.T) {
intControlPlane, err := configutil.DefaultedInitConfiguration(controlPlaneConfig) intControlPlane, err := configutil.DefaultedInitConfiguration(controlPlaneConfig)
if err != nil { if err != nil {
t.Errorf("test failed to convert external to internal version") t.Errorf("test failed to convert external to internal version")
break return
} }
intControlPlane.ComponentConfigs.KubeProxy = &kubeproxyconfig.KubeProxyConfiguration{ intControlPlane.ComponentConfigs.KubeProxy = &kubeproxyconfig.KubeProxyConfiguration{
BindAddress: "", BindAddress: "",
@ -224,7 +223,7 @@ func TestEnsureProxyAddon(t *testing.T) {
// Run dynamic defaulting again as we changed the internal cfg // Run dynamic defaulting again as we changed the internal cfg
if err := configutil.SetInitDynamicDefaults(intControlPlane); err != nil { if err := configutil.SetInitDynamicDefaults(intControlPlane); err != nil {
t.Errorf("test failed to set dynamic defaults: %v", err) t.Errorf("test failed to set dynamic defaults: %v", err)
break return
} }
err = EnsureProxyAddon(&intControlPlane.ClusterConfiguration, &intControlPlane.LocalAPIEndpoint, client) err = EnsureProxyAddon(&intControlPlane.ClusterConfiguration, &intControlPlane.LocalAPIEndpoint, client)
@ -256,15 +255,18 @@ func TestEnsureProxyAddon(t *testing.T) {
tc.expClusterCIDR, tc.expClusterCIDR,
intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR) intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR)
} }
})
} }
} }
func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) { func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
testCases := []struct { testCases := []struct {
name string
manifest string manifest string
data interface{} data interface{}
}{ }{
{ {
name: "KubeProxyDaemonSet19",
manifest: KubeProxyDaemonSet19, manifest: KubeProxyDaemonSet19,
data: struct{ Image, ProxyConfigMap, ProxyConfigMapKey string }{ data: struct{ Image, ProxyConfigMap, ProxyConfigMapKey string }{
Image: "foo", Image: "foo",
@ -274,6 +276,7 @@ func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
daemonSetBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data) daemonSetBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
daemonSet := &apps.DaemonSet{} daemonSet := &apps.DaemonSet{}
if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), daemonSetBytes, daemonSet); err != nil { if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), daemonSetBytes, daemonSet); err != nil {
@ -282,5 +285,6 @@ func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
if daemonSet.Spec.Template.Spec.PriorityClassName != "system-node-critical" { if daemonSet.Spec.Template.Spec.PriorityClassName != "system-node-critical" {
t.Errorf("expected to see system-node-critical priority class name. Got %q instead", daemonSet.Spec.Template.Spec.PriorityClassName) t.Errorf("expected to see system-node-critical priority class name. Got %q instead", daemonSet.Spec.Template.Spec.PriorityClassName)
} }
})
} }
} }

View File

@ -95,6 +95,7 @@ func TestCreateBootstrapConfigMapIfNotExists(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset() client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil { if tc.createErr != nil {
client.PrependReactor("create", "configmaps", func(action core.Action) (bool, runtime.Object, error) { client.PrependReactor("create", "configmaps", func(action core.Action) (bool, runtime.Object, error) {
@ -108,6 +109,7 @@ func TestCreateBootstrapConfigMapIfNotExists(t *testing.T) {
} else if !tc.expectErr && err != nil { } else if !tc.expectErr && err != nil {
t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) returned unexpected error: %v", tc.name, err) t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) returned unexpected error: %v", tc.name, err)
} }
})
} }
} }
} }

View File

@ -55,57 +55,67 @@ func TestGetStaticPodSpecs(t *testing.T) {
specs := GetStaticPodSpecs(cfg, &kubeadmapi.APIEndpoint{}, k8sVersion) specs := GetStaticPodSpecs(cfg, &kubeadmapi.APIEndpoint{}, k8sVersion)
var assertions = []struct { var tests = []struct {
name string
staticPodName string staticPodName string
}{ }{
{ {
name: "KubeAPIServer",
staticPodName: kubeadmconstants.KubeAPIServer, staticPodName: kubeadmconstants.KubeAPIServer,
}, },
{ {
name: "KubeControllerManager",
staticPodName: kubeadmconstants.KubeControllerManager, staticPodName: kubeadmconstants.KubeControllerManager,
}, },
{ {
name: "KubeScheduler",
staticPodName: kubeadmconstants.KubeScheduler, staticPodName: kubeadmconstants.KubeScheduler,
}, },
} }
for _, assertion := range assertions { for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// assert the spec for the staticPodName exists // assert the spec for the staticPodName exists
if spec, ok := specs[assertion.staticPodName]; ok { if spec, ok := specs[tc.staticPodName]; ok {
// Assert each specs refers to the right pod // Assert each specs refers to the right pod
if spec.Spec.Containers[0].Name != assertion.staticPodName { if spec.Spec.Containers[0].Name != tc.staticPodName {
t.Errorf("getKubeConfigSpecs spec for %s contains pod %s, expects %s", assertion.staticPodName, spec.Spec.Containers[0].Name, assertion.staticPodName) t.Errorf("getKubeConfigSpecs spec for %s contains pod %s, expects %s", tc.staticPodName, spec.Spec.Containers[0].Name, tc.staticPodName)
} }
} else { } else {
t.Errorf("getStaticPodSpecs didn't create spec for %s ", assertion.staticPodName) t.Errorf("getStaticPodSpecs didn't create spec for %s ", tc.staticPodName)
} }
})
} }
} }
func TestCreateStaticPodFilesAndWrappers(t *testing.T) { func TestCreateStaticPodFilesAndWrappers(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
components []string components []string
}{ }{
{ {
name: "KubeAPIServer KubeAPIServer KubeScheduler",
components: []string{kubeadmconstants.KubeAPIServer, kubeadmconstants.KubeControllerManager, kubeadmconstants.KubeScheduler}, components: []string{kubeadmconstants.KubeAPIServer, kubeadmconstants.KubeControllerManager, kubeadmconstants.KubeScheduler},
}, },
{ {
name: "KubeAPIServer",
components: []string{kubeadmconstants.KubeAPIServer}, components: []string{kubeadmconstants.KubeAPIServer},
}, },
{ {
name: "KubeControllerManager",
components: []string{kubeadmconstants.KubeControllerManager}, components: []string{kubeadmconstants.KubeControllerManager},
}, },
{ {
name: "KubeScheduler",
components: []string{kubeadmconstants.KubeScheduler}, components: []string{kubeadmconstants.KubeScheduler},
}, },
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Create temp folder for the test case // Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -120,7 +130,7 @@ func TestCreateStaticPodFilesAndWrappers(t *testing.T) {
err := CreateStaticPodFiles(manifestPath, cfg, &kubeadmapi.APIEndpoint{}, test.components...) err := CreateStaticPodFiles(manifestPath, cfg, &kubeadmapi.APIEndpoint{}, test.components...)
if err != nil { if err != nil {
t.Errorf("Error executing createStaticPodFunction: %v", err) t.Errorf("Error executing createStaticPodFunction: %v", err)
continue return
} }
// Assert expected files are there // Assert expected files are there
@ -129,6 +139,7 @@ func TestCreateStaticPodFilesAndWrappers(t *testing.T) {
for _, fileName := range test.components { for _, fileName := range test.components {
testutil.AssertFileExists(t, manifestPath, fileName+".yaml") testutil.AssertFileExists(t, manifestPath, fileName+".yaml")
} }
})
} }
} }
@ -626,12 +637,14 @@ func TestGetControllerManagerCommand(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := getControllerManagerCommand(rt.cfg, version.MustParseSemantic(rt.cfg.KubernetesVersion)) actual := getControllerManagerCommand(rt.cfg, version.MustParseSemantic(rt.cfg.KubernetesVersion))
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) {
errorDiffArguments(t, rt.name, actual, rt.expected) errorDiffArguments(t, rt.name, actual, rt.expected)
} }
})
} }
} }
@ -703,16 +716,17 @@ func TestCalcNodeCidrSize(t *testing.T) {
}, },
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
actualPrefix := calcNodeCidrSize(test.podSubnet) actualPrefix := calcNodeCidrSize(test.podSubnet)
if actualPrefix != test.expectedPrefix { if actualPrefix != test.expectedPrefix {
t.Errorf("Case [%s]\nCalc of node CIDR size for pod subnet %q failed: Expected %q, saw %q", t.Errorf("Case [%s]\nCalc of node CIDR size for pod subnet %q failed: Expected %q, saw %q",
test.name, test.podSubnet, test.expectedPrefix, actualPrefix) test.name, test.podSubnet, test.expectedPrefix, actualPrefix)
} }
})
} }
} }
func TestGetControllerManagerCommandExternalCA(t *testing.T) { func TestGetControllerManagerCommandExternalCA(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
cfg *kubeadmapi.InitConfiguration cfg *kubeadmapi.InitConfiguration
@ -780,6 +794,7 @@ func TestGetControllerManagerCommandExternalCA(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Create temp folder for the test case // Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -806,6 +821,7 @@ func TestGetControllerManagerCommandExternalCA(t *testing.T) {
if !reflect.DeepEqual(actual, expected) { if !reflect.DeepEqual(actual, expected) {
errorDiffArguments(t, test.name, actual, expected) errorDiffArguments(t, test.name, actual, expected)
} }
})
} }
} }
@ -828,12 +844,14 @@ func TestGetSchedulerCommand(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actual := getSchedulerCommand(rt.cfg) actual := getSchedulerCommand(rt.cfg)
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) {
errorDiffArguments(t, rt.name, actual, rt.expected) errorDiffArguments(t, rt.name, actual, rt.expected)
} }
})
} }
} }
@ -901,7 +919,6 @@ func TestGetAuthzModes(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) { t.Run(rt.name, func(t *testing.T) {
actual := getAuthzModes(strings.Join(rt.authMode, ",")) actual := getAuthzModes(strings.Join(rt.authMode, ","))
if actual != rt.expected { if actual != rt.expected {

View File

@ -32,12 +32,12 @@ func TestGetEtcdCertVolumes(t *testing.T) {
hostPathDirectoryOrCreate := v1.HostPathDirectoryOrCreate hostPathDirectoryOrCreate := v1.HostPathDirectoryOrCreate
k8sCertifcatesDir := "/etc/kubernetes/pki" k8sCertifcatesDir := "/etc/kubernetes/pki"
var tests = []struct { var tests = []struct {
ca, cert, key string name, ca, cert, key string
vol []v1.Volume vol []v1.Volume
volMount []v1.VolumeMount volMount []v1.VolumeMount
}{ }{
{ {
// Should ignore files in /etc/ssl/certs name: "Should ignore files in /etc/ssl/certs",
ca: "/etc/ssl/certs/my-etcd-ca.crt", ca: "/etc/ssl/certs/my-etcd-ca.crt",
cert: "/etc/ssl/certs/my-etcd.crt", cert: "/etc/ssl/certs/my-etcd.crt",
key: "/etc/ssl/certs/my-etcd.key", key: "/etc/ssl/certs/my-etcd.key",
@ -45,7 +45,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
volMount: []v1.VolumeMount{}, volMount: []v1.VolumeMount{},
}, },
{ {
// Should ignore files in subdirs of /etc/ssl/certs name: "Should ignore files in subdirs of /etc/ssl/certs",
ca: "/etc/ssl/certs/etcd/my-etcd-ca.crt", ca: "/etc/ssl/certs/etcd/my-etcd-ca.crt",
cert: "/etc/ssl/certs/etcd/my-etcd.crt", cert: "/etc/ssl/certs/etcd/my-etcd.crt",
key: "/etc/ssl/certs/etcd/my-etcd.key", key: "/etc/ssl/certs/etcd/my-etcd.key",
@ -53,7 +53,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
volMount: []v1.VolumeMount{}, volMount: []v1.VolumeMount{},
}, },
{ {
// Should ignore files in /etc/pki name: "Should ignore files in /etc/pki",
ca: "/etc/pki/my-etcd-ca.crt", ca: "/etc/pki/my-etcd-ca.crt",
cert: "/etc/pki/my-etcd.crt", cert: "/etc/pki/my-etcd.crt",
key: "/etc/pki/my-etcd.key", key: "/etc/pki/my-etcd.key",
@ -61,7 +61,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
volMount: []v1.VolumeMount{}, volMount: []v1.VolumeMount{},
}, },
{ {
// Should ignore files in Kubernetes PKI directory (and subdirs) name: "Should ignore files in Kubernetes PKI directory (and subdirs)",
ca: k8sCertifcatesDir + "/ca/my-etcd-ca.crt", ca: k8sCertifcatesDir + "/ca/my-etcd-ca.crt",
cert: k8sCertifcatesDir + "/my-etcd.crt", cert: k8sCertifcatesDir + "/my-etcd.crt",
key: k8sCertifcatesDir + "/my-etcd.key", key: k8sCertifcatesDir + "/my-etcd.key",
@ -69,7 +69,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
volMount: []v1.VolumeMount{}, volMount: []v1.VolumeMount{},
}, },
{ {
// All in the same dir name: "All certs are in the same dir",
ca: "/var/lib/certs/etcd/my-etcd-ca.crt", ca: "/var/lib/certs/etcd/my-etcd-ca.crt",
cert: "/var/lib/certs/etcd/my-etcd.crt", cert: "/var/lib/certs/etcd/my-etcd.crt",
key: "/var/lib/certs/etcd/my-etcd.key", key: "/var/lib/certs/etcd/my-etcd.key",
@ -93,7 +93,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
}, },
}, },
{ {
// One file + two files in separate dirs name: "One file + two files in separate dirs",
ca: "/etc/certs/etcd/my-etcd-ca.crt", ca: "/etc/certs/etcd/my-etcd-ca.crt",
cert: "/var/lib/certs/etcd/my-etcd.crt", cert: "/var/lib/certs/etcd/my-etcd.crt",
key: "/var/lib/certs/etcd/my-etcd.key", key: "/var/lib/certs/etcd/my-etcd.key",
@ -131,7 +131,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
}, },
}, },
{ {
// All three files in different directories name: "All three files in different directories",
ca: "/etc/certs/etcd/my-etcd-ca.crt", ca: "/etc/certs/etcd/my-etcd-ca.crt",
cert: "/var/lib/certs/etcd/my-etcd.crt", cert: "/var/lib/certs/etcd/my-etcd.crt",
key: "/var/lib/certs/private/my-etcd.key", key: "/var/lib/certs/private/my-etcd.key",
@ -183,7 +183,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
}, },
}, },
{ {
// The most top-level dir should be used name: "The most top-level dir should be used",
ca: "/etc/certs/etcd/my-etcd-ca.crt", ca: "/etc/certs/etcd/my-etcd-ca.crt",
cert: "/etc/certs/etcd/serving/my-etcd.crt", cert: "/etc/certs/etcd/serving/my-etcd.crt",
key: "/etc/certs/etcd/serving/my-etcd.key", key: "/etc/certs/etcd/serving/my-etcd.key",
@ -207,7 +207,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
}, },
}, },
{ {
// The most top-level dir should be used, regardless of order name: "The most top-level dir should be used, regardless of order",
ca: "/etc/certs/etcd/ca/my-etcd-ca.crt", ca: "/etc/certs/etcd/ca/my-etcd-ca.crt",
cert: "/etc/certs/etcd/my-etcd.crt", cert: "/etc/certs/etcd/my-etcd.crt",
key: "/etc/certs/etcd/my-etcd.key", key: "/etc/certs/etcd/my-etcd.key",
@ -233,6 +233,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actualVol, actualVolMount := getEtcdCertVolumes(&kubeadmapi.ExternalEtcd{ actualVol, actualVolMount := getEtcdCertVolumes(&kubeadmapi.ExternalEtcd{
CAFile: rt.ca, CAFile: rt.ca,
CertFile: rt.cert, CertFile: rt.cert,
@ -252,6 +253,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
actualVolMount, actualVolMount,
) )
} }
})
} }
} }
@ -472,12 +474,13 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
ReadOnly: true, ReadOnly: true,
} }
var tests = []struct { var tests = []struct {
name string
cfg *kubeadmapi.ClusterConfiguration cfg *kubeadmapi.ClusterConfiguration
vol map[string]map[string]v1.Volume vol map[string]map[string]v1.Volume
volMount map[string]map[string]v1.VolumeMount volMount map[string]map[string]v1.VolumeMount
}{ }{
{ {
// Should ignore files in /etc/ssl/certs name: "Should ignore files in /etc/ssl/certs",
cfg: &kubeadmapi.ClusterConfiguration{ cfg: &kubeadmapi.ClusterConfiguration{
CertificatesDir: testCertsDir, CertificatesDir: testCertsDir,
Etcd: kubeadmapi.Etcd{}, Etcd: kubeadmapi.Etcd{},
@ -486,7 +489,7 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
volMount: volMountMap, volMount: volMountMap,
}, },
{ {
// Should ignore files in /etc/ssl/certs and in CertificatesDir name: "Should ignore files in /etc/ssl/certs and in CertificatesDir",
cfg: &kubeadmapi.ClusterConfiguration{ cfg: &kubeadmapi.ClusterConfiguration{
CertificatesDir: testCertsDir, CertificatesDir: testCertsDir,
Etcd: kubeadmapi.Etcd{ Etcd: kubeadmapi.Etcd{
@ -514,6 +517,7 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
defer func() { caCertsExtraVolumePaths = []string{"/etc/pki", "/usr/share/ca-certificates"} }() defer func() { caCertsExtraVolumePaths = []string{"/etc/pki", "/usr/share/ca-certificates"} }()
for _, rt := range tests { for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
mounts := getHostPathVolumesForTheControlPlane(rt.cfg) mounts := getHostPathVolumesForTheControlPlane(rt.cfg)
// Avoid unit test errors when the flexvolume is mounted // Avoid unit test errors when the flexvolume is mounted
@ -537,6 +541,7 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
mounts.volumeMounts, mounts.volumeMounts,
) )
} }
})
} }
} }
@ -609,6 +614,7 @@ func TestAddExtraHostPathMounts(t *testing.T) {
} }
mounts.AddExtraHostPathMounts("component", hostPathMounts) mounts.AddExtraHostPathMounts("component", hostPathMounts)
for _, hostMount := range hostPathMounts { for _, hostMount := range hostPathMounts {
t.Run(hostMount.Name, func(t *testing.T) {
volumeName := hostMount.Name volumeName := hostMount.Name
if _, ok := mounts.volumes["component"][volumeName]; !ok { if _, ok := mounts.volumes["component"][volumeName]; !ok {
t.Errorf("Expected to find volume %q", volumeName) t.Errorf("Expected to find volume %q", volumeName)
@ -636,5 +642,6 @@ func TestAddExtraHostPathMounts(t *testing.T) {
if volMount.ReadOnly != hostMount.ReadOnly { if volMount.ReadOnly != hostMount.ReadOnly {
t.Errorf("Expected volume readOnly setting %t", hostMount.ReadOnly) t.Errorf("Expected volume readOnly setting %t", hostMount.ReadOnly)
} }
})
} }
} }

View File

@ -109,7 +109,7 @@ func TestGetKubeConfigSpecs(t *testing.T) {
}, },
} }
for _, cfg := range cfgs { for i, cfg := range cfgs {
var assertions = []struct { var assertions = []struct {
kubeConfigFile string kubeConfigFile string
clientName string clientName string
@ -136,6 +136,7 @@ func TestGetKubeConfigSpecs(t *testing.T) {
} }
for _, assertion := range assertions { for _, assertion := range assertions {
t.Run(fmt.Sprintf("%d-%s", i, assertion.clientName), func(t *testing.T) {
// Executes getKubeConfigSpecs // Executes getKubeConfigSpecs
specs, err := getKubeConfigSpecs(cfg) specs, err := getKubeConfigSpecs(cfg)
if err != nil { if err != nil {
@ -148,7 +149,7 @@ func TestGetKubeConfigSpecs(t *testing.T) {
// assert the spec for the kubeConfigFile exists // assert the spec for the kubeConfigFile exists
if spec, ok = specs[assertion.kubeConfigFile]; !ok { if spec, ok = specs[assertion.kubeConfigFile]; !ok {
t.Errorf("getKubeConfigSpecs didn't create spec for %s ", assertion.kubeConfigFile) t.Errorf("getKubeConfigSpecs didn't create spec for %s ", assertion.kubeConfigFile)
continue return
} }
// Assert clientName // Assert clientName
@ -177,6 +178,7 @@ func TestGetKubeConfigSpecs(t *testing.T) {
if spec.ClientCertAuth == nil || spec.ClientCertAuth.CAKey == nil { if spec.ClientCertAuth == nil || spec.ClientCertAuth.CAKey == nil {
t.Errorf("getKubeConfigSpecs didn't loaded CAKey into spec for %s!", assertion.kubeConfigFile) t.Errorf("getKubeConfigSpecs didn't loaded CAKey into spec for %s!", assertion.kubeConfigFile)
} }
})
} }
} }
} }
@ -217,23 +219,28 @@ func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
configWithAnotherClusterAddress := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://3.4.5.6:3456", "myOrg1", "test-cluster", "myOrg2") configWithAnotherClusterAddress := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://3.4.5.6:3456", "myOrg1", "test-cluster", "myOrg2")
var tests = []struct { var tests = []struct {
name string
existingKubeConfig *clientcmdapi.Config existingKubeConfig *clientcmdapi.Config
kubeConfig *clientcmdapi.Config kubeConfig *clientcmdapi.Config
expectedError bool expectedError bool
}{ }{
{ // if there is no existing KubeConfig, creates the kubeconfig { // if there is no existing KubeConfig, creates the kubeconfig
name: "KubeConfig doesn't exist",
kubeConfig: config, kubeConfig: config,
}, },
{ // if KubeConfig is equal to the existingKubeConfig - refers to the same cluster -, use the existing (Test idempotency) { // if KubeConfig is equal to the existingKubeConfig - refers to the same cluster -, use the existing (Test idempotency)
name: "KubeConfig refers to the same cluster",
existingKubeConfig: config, existingKubeConfig: config,
kubeConfig: config, kubeConfig: config,
}, },
{ // if KubeConfig is not equal to the existingKubeConfig - refers to the another cluster (a cluster with another Ca) -, raise error { // if KubeConfig is not equal to the existingKubeConfig - refers to the another cluster (a cluster with another Ca) -, raise error
name: "KubeConfig refers to the cluster with another CA",
existingKubeConfig: config, existingKubeConfig: config,
kubeConfig: configWithAnotherClusterCa, kubeConfig: configWithAnotherClusterCa,
expectedError: true, expectedError: true,
}, },
{ // if KubeConfig is not equal to the existingKubeConfig - refers to the another cluster (a cluster with another address) -, raise error { // if KubeConfig is not equal to the existingKubeConfig - refers to the another cluster (a cluster with another address) -, raise error
name: "KubeConfig referst to the cluster with another address",
existingKubeConfig: config, existingKubeConfig: config,
kubeConfig: configWithAnotherClusterAddress, kubeConfig: configWithAnotherClusterAddress,
expectedError: true, expectedError: true,
@ -241,6 +248,7 @@ func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Create temp folder for the test case // Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -263,22 +271,26 @@ func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
// Assert that the created file is there // Assert that the created file is there
testutil.AssertFileExists(t, tmpdir, "test.conf") testutil.AssertFileExists(t, tmpdir, "test.conf")
})
} }
} }
func TestCreateKubeconfigFilesAndWrappers(t *testing.T) { func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
var tests = []struct { var tests = []struct {
name string
createKubeConfigFunction func(outDir string, cfg *kubeadmapi.InitConfiguration) error createKubeConfigFunction func(outDir string, cfg *kubeadmapi.InitConfiguration) error
expectedFiles []string expectedFiles []string
expectedError bool expectedError bool
}{ }{
{ // Test createKubeConfigFiles fails for unknown kubeconfig is requested { // Test createKubeConfigFiles fails for unknown kubeconfig is requested
name: "createKubeConfigFiles",
createKubeConfigFunction: func(outDir string, cfg *kubeadmapi.InitConfiguration) error { createKubeConfigFunction: func(outDir string, cfg *kubeadmapi.InitConfiguration) error {
return createKubeConfigFiles(outDir, cfg, "unknown.conf") return createKubeConfigFiles(outDir, cfg, "unknown.conf")
}, },
expectedError: true, expectedError: true,
}, },
{ // Test CreateInitKubeConfigFiles (wrapper to createKubeConfigFile) { // Test CreateInitKubeConfigFiles (wrapper to createKubeConfigFile)
name: "CreateInitKubeConfigFiles",
createKubeConfigFunction: CreateInitKubeConfigFiles, createKubeConfigFunction: CreateInitKubeConfigFiles,
expectedFiles: []string{ expectedFiles: []string{
kubeadmconstants.AdminKubeConfigFileName, kubeadmconstants.AdminKubeConfigFileName,
@ -288,6 +300,7 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
}, },
}, },
{ // Test CreateJoinControlPlaneKubeConfigFiles (wrapper to createKubeConfigFile) { // Test CreateJoinControlPlaneKubeConfigFiles (wrapper to createKubeConfigFile)
name: "CreateJoinControlPlaneKubeConfigFiles",
createKubeConfigFunction: CreateJoinControlPlaneKubeConfigFiles, createKubeConfigFunction: CreateJoinControlPlaneKubeConfigFiles,
expectedFiles: []string{ expectedFiles: []string{
kubeadmconstants.AdminKubeConfigFileName, kubeadmconstants.AdminKubeConfigFileName,
@ -298,6 +311,7 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Create temp folder for the test case // Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -317,20 +331,20 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
err := test.createKubeConfigFunction(tmpdir, cfg) err := test.createKubeConfigFunction(tmpdir, cfg)
if test.expectedError && err == nil { if test.expectedError && err == nil {
t.Errorf("createKubeConfigFunction didn't failed when expected to fail") t.Errorf("createKubeConfigFunction didn't failed when expected to fail")
continue return
} }
if !test.expectedError && err != nil { if !test.expectedError && err != nil {
t.Errorf("createKubeConfigFunction failed") t.Errorf("createKubeConfigFunction failed")
continue return
} }
// Assert expected files are there // Assert expected files are there
testutil.AssertFileExists(t, tmpdir, test.expectedFiles...) testutil.AssertFileExists(t, tmpdir, test.expectedFiles...)
})
} }
} }
func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) { func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) {
// Temporary folders for the test case (without a CA) // Temporary folders for the test case (without a CA)
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -343,14 +357,17 @@ func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
name string
writeKubeConfigFunction func(out io.Writer) error writeKubeConfigFunction func(out io.Writer) error
}{ }{
{ // Test WriteKubeConfigWithClientCert {
name: "WriteKubeConfigWithClientCert",
writeKubeConfigFunction: func(out io.Writer) error { writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"}) return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"})
}, },
}, },
{ // Test WriteKubeConfigWithToken {
name: "WriteKubeConfigWithToken",
writeKubeConfigFunction: func(out io.Writer) error { writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithToken(out, cfg, "myUser", "12345") return WriteKubeConfigWithToken(out, cfg, "myUser", "12345")
}, },
@ -358,17 +375,18 @@ func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
// executes writeKubeConfigFunction // executes writeKubeConfigFunction
if err := test.writeKubeConfigFunction(buf); err == nil { if err := test.writeKubeConfigFunction(buf); err == nil {
t.Error("writeKubeConfigFunction didnt failed when expected") t.Error("writeKubeConfigFunction didnt failed when expected")
} }
})
} }
} }
func TestWriteKubeConfig(t *testing.T) { func TestWriteKubeConfig(t *testing.T) {
// Temporary folders for the test case // Temporary folders for the test case
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -391,17 +409,20 @@ func TestWriteKubeConfig(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
name string
writeKubeConfigFunction func(out io.Writer) error writeKubeConfigFunction func(out io.Writer) error
withClientCert bool withClientCert bool
withToken bool withToken bool
}{ }{
{ // Test WriteKubeConfigWithClientCert {
name: "WriteKubeConfigWithClientCert",
writeKubeConfigFunction: func(out io.Writer) error { writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"}) return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"})
}, },
withClientCert: true, withClientCert: true,
}, },
{ // Test WriteKubeConfigWithToken {
name: "WriteKubeConfigWithToken",
writeKubeConfigFunction: func(out io.Writer) error { writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithToken(out, cfg, "myUser", "12345") return WriteKubeConfigWithToken(out, cfg, "myUser", "12345")
}, },
@ -410,19 +431,20 @@ func TestWriteKubeConfig(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
// executes writeKubeConfigFunction // executes writeKubeConfigFunction
if err := test.writeKubeConfigFunction(buf); err != nil { if err := test.writeKubeConfigFunction(buf); err != nil {
t.Error("writeKubeConfigFunction failed") t.Error("writeKubeConfigFunction failed")
continue return
} }
// reads kubeconfig written to stdout // reads kubeconfig written to stdout
config, err := clientcmd.Load(buf.Bytes()) config, err := clientcmd.Load(buf.Bytes())
if err != nil { if err != nil {
t.Errorf("Couldn't read kubeconfig file from buffer: %v", err) t.Errorf("Couldn't read kubeconfig file from buffer: %v", err)
continue return
} }
// checks that CLI flags are properly propagated // checks that CLI flags are properly propagated
@ -437,6 +459,7 @@ func TestWriteKubeConfig(t *testing.T) {
// checks that kubeconfig files have expected token // checks that kubeconfig files have expected token
kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithToken(t, config, "myUser", "12345") kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithToken(t, config, "myUser", "12345")
} }
})
} }
} }
@ -475,6 +498,7 @@ func TestValidateKubeConfig(t *testing.T) {
} }
for name, test := range tests { for name, test := range tests {
t.Run(name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -494,6 +518,7 @@ func TestValidateKubeConfig(t *testing.T) {
err, err,
) )
} }
})
} }
} }
@ -581,6 +606,7 @@ func TestValidateKubeconfigsForExternalCA(t *testing.T) {
} }
for name, test := range tests { for name, test := range tests {
t.Run(name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
@ -600,6 +626,7 @@ func TestValidateKubeconfigsForExternalCA(t *testing.T) {
err, err,
) )
} }
})
} }
} }

View File

@ -107,6 +107,7 @@ func TestMarkControlPlane(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
hostname, err := node.GetHostname("") hostname, err := node.GetHostname("")
if err != nil { if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected error: %v", tc.name, err) t.Fatalf("MarkControlPlane(%s): unexpected error: %v", tc.name, err)
@ -170,6 +171,7 @@ func TestMarkControlPlane(t *testing.T) {
if tc.expectedPatch != patchRequest { if tc.expectedPatch != patchRequest {
t.Errorf("MarkControlPlane(%s) wanted patch %v, got %v", tc.name, tc.expectedPatch, patchRequest) t.Errorf("MarkControlPlane(%s) wanted patch %v, got %v", tc.name, tc.expectedPatch, patchRequest)
} }
})
} }
} }