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,45 +58,47 @@ func TestCreateServiceAccount(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
client := clientsetfake.NewSimpleClientset() t.Run(tc.name, func(t *testing.T) {
if tc.createErr != nil { client := clientsetfake.NewSimpleClientset()
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) { if tc.createErr != nil {
return true, nil, tc.createErr client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
}) return true, nil, tc.createErr
} })
err := CreateServiceAccount(client)
if tc.expectErr {
if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
} }
continue
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
wantResourcesCreated := 1 err := CreateServiceAccount(client)
if len(client.Actions()) != wantResourcesCreated { if tc.expectErr {
t.Errorf("CreateServiceAccounts(%s) should have made %d actions, but made %d", tc.name, wantResourcesCreated, len(client.Actions())) if err == nil {
} t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
}
for _, action := range client.Actions() { return
if action.GetVerb() != "create" || action.GetResource().Resource != "serviceaccounts" { } else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) called [%v %v], but wanted [create serviceaccounts]", t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
tc.name, action.GetVerb(), action.GetResource().Resource)
} }
}
wantResourcesCreated := 1
if len(client.Actions()) != wantResourcesCreated {
t.Errorf("CreateServiceAccounts(%s) should have made %d actions, but made %d", tc.name, wantResourcesCreated, len(client.Actions()))
}
for _, action := range client.Actions() {
if action.GetVerb() != "create" || action.GetResource().Resource != "serviceaccounts" {
t.Errorf("CreateServiceAccounts(%s) called [%v %v], but wanted [create serviceaccounts]",
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,58 +136,61 @@ 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 {
dnsIP, err := kubeadmconstants.GetDNSIP(rt.svcSubnet) t.Run(rt.name, func(t *testing.T) {
if err != nil { dnsIP, err := kubeadmconstants.GetDNSIP(rt.svcSubnet)
t.Fatalf("couldn't get dnsIP : %v", err) if err != nil {
} t.Fatalf("couldn't get dnsIP : %v", err)
}
actualDNSIP := dnsIP.String() actualDNSIP := dnsIP.String()
if actualDNSIP != rt.expectedDNSIP { if actualDNSIP != rt.expectedDNSIP {
t.Errorf( t.Errorf(
"failed GetDNSIP\n\texpected: %s\n\t actual: %s", "failed GetDNSIP\n\texpected: %s\n\t actual: %s",
rt.expectedDNSIP, rt.expectedDNSIP,
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,22 +300,26 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
out, err := translateStubDomainOfKubeDNSToForwardCoreDNS(kubeDNSStubDomain, testCase.configMap) t.Run(testCase.name, func(t *testing.T) {
if err != nil { out, err := translateStubDomainOfKubeDNSToForwardCoreDNS(kubeDNSStubDomain, testCase.configMap)
t.Errorf("unexpected error: %v", err) if err != nil {
} t.Errorf("unexpected error: %v", err)
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) 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)
}
})
} }
} }
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,23 +360,27 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
out, err := translateUpstreamNameServerOfKubeDNSToUpstreamProxyCoreDNS(kubeDNSUpstreamNameservers, testCase.configMap) t.Run(testCase.name, func(t *testing.T) {
if err != nil { out, err := translateUpstreamNameServerOfKubeDNSToUpstreamProxyCoreDNS(kubeDNSUpstreamNameservers, testCase.configMap)
t.Errorf("unexpected error: %v", err) if err != nil {
} t.Errorf("unexpected error: %v", err)
if !strings.Contains(out, testCase.expect) { }
t.Errorf("expected to find %q in output: %q", testCase.expect, out) if !strings.Contains(out, testCase.expect) {
} 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,22 +432,26 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
out, err := translateFederationsofKubeDNSToCoreDNS(kubeDNSFederation, "cluster.local", testCase.configMap) t.Run(testCase.name, func(t *testing.T) {
if err != nil { out, err := translateFederationsofKubeDNSToCoreDNS(kubeDNSFederation, "cluster.local", testCase.configMap)
t.Errorf("unexpected error: %v", err) if err != nil {
} t.Errorf("unexpected error: %v", err)
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) 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)
}
})
} }
} }
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,13 +475,15 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
deploymentBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data) t.Run(testCase.name, func(t *testing.T) {
deployment := &apps.Deployment{} deploymentBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), deploymentBytes, deployment); err != nil { deployment := &apps.Deployment{}
t.Errorf("unexpected error: %v", err) if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), deploymentBytes, deployment); err != nil {
} t.Errorf("unexpected error: %v", err)
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) 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)
}
})
} }
} }

View File

@ -62,45 +62,48 @@ func TestCreateServiceAccount(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
client := clientsetfake.NewSimpleClientset() t.Run(tc.name, func(t *testing.T) {
if tc.createErr != nil { client := clientsetfake.NewSimpleClientset()
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) { if tc.createErr != nil {
return true, nil, tc.createErr client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
}) return true, nil, tc.createErr
} })
err := CreateServiceAccount(client)
if tc.expectErr {
if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
} }
continue
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
wantResourcesCreated := 1 err := CreateServiceAccount(client)
if len(client.Actions()) != wantResourcesCreated { if tc.expectErr {
t.Errorf("CreateServiceAccounts(%s) should have made %d actions, but made %d", tc.name, wantResourcesCreated, len(client.Actions())) if err == nil {
} t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
}
for _, action := range client.Actions() { return
if action.GetVerb() != "create" || action.GetResource().Resource != "serviceaccounts" { } else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) called [%v %v], but wanted [create serviceaccounts]", t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
tc.name, action.GetVerb(), action.GetResource().Resource)
} }
}
wantResourcesCreated := 1
if len(client.Actions()) != wantResourcesCreated {
t.Errorf("CreateServiceAccounts(%s) should have made %d actions, but made %d", tc.name, wantResourcesCreated, len(client.Actions()))
}
for _, action := range client.Actions() {
if action.GetVerb() != "create" || action.GetResource().Resource != "serviceaccounts" {
t.Errorf("CreateServiceAccounts(%s) called [%v %v], but wanted [create serviceaccounts]",
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,98 +172,101 @@ 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
controlPlaneConfig := &kubeadmapiv1beta1.InitConfiguration{ controlPlaneConfig := &kubeadmapiv1beta1.InitConfiguration{
LocalAPIEndpoint: kubeadmapiv1beta1.APIEndpoint{ LocalAPIEndpoint: kubeadmapiv1beta1.APIEndpoint{
AdvertiseAddress: "1.2.3.4", AdvertiseAddress: "1.2.3.4",
BindPort: 1234, BindPort: 1234,
},
ClusterConfiguration: kubeadmapiv1beta1.ClusterConfiguration{
Networking: kubeadmapiv1beta1.Networking{
PodSubnet: "5.6.7.8/24",
}, },
ImageRepository: "someRepo", ClusterConfiguration: kubeadmapiv1beta1.ClusterConfiguration{
KubernetesVersion: constants.MinimumControlPlaneVersion.String(), Networking: kubeadmapiv1beta1.Networking{
}, PodSubnet: "5.6.7.8/24",
} },
ImageRepository: "someRepo",
KubernetesVersion: constants.MinimumControlPlaneVersion.String(),
},
}
// Simulate an error if necessary // Simulate an error if necessary
switch tc.simError { switch tc.simError {
case ServiceAccountError: case ServiceAccountError:
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) { client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, apierrors.NewUnauthorized("") return true, nil, apierrors.NewUnauthorized("")
}) })
case InvalidControlPlaneEndpoint: case InvalidControlPlaneEndpoint:
controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1.2.3" controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1.2.3"
case IPv6SetBindAddress: case IPv6SetBindAddress:
controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1:2::3:4" controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1:2::3:4"
controlPlaneConfig.Networking.PodSubnet = "2001:101::/96" controlPlaneConfig.Networking.PodSubnet = "2001:101::/96"
} }
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: "",
HealthzBindAddress: "0.0.0.0:10256", HealthzBindAddress: "0.0.0.0:10256",
MetricsBindAddress: "127.0.0.1:10249", MetricsBindAddress: "127.0.0.1:10249",
Conntrack: kubeproxyconfig.KubeProxyConntrackConfiguration{ Conntrack: kubeproxyconfig.KubeProxyConntrackConfiguration{
Max: pointer.Int32Ptr(2), Max: pointer.Int32Ptr(2),
MaxPerCore: pointer.Int32Ptr(1), MaxPerCore: pointer.Int32Ptr(1),
Min: pointer.Int32Ptr(1), Min: pointer.Int32Ptr(1),
TCPEstablishedTimeout: &metav1.Duration{Duration: 5 * time.Second}, TCPEstablishedTimeout: &metav1.Duration{Duration: 5 * time.Second},
TCPCloseWaitTimeout: &metav1.Duration{Duration: 5 * time.Second}, TCPCloseWaitTimeout: &metav1.Duration{Duration: 5 * time.Second},
}, },
} }
// 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)
// Compare actual to expected errors // Compare actual to expected errors
actErr := "No error" actErr := "No error"
if err != nil { if err != nil {
actErr = err.Error() actErr = err.Error()
} }
expErr := "No error" expErr := "No error"
if tc.expErrString != "" { if tc.expErrString != "" {
expErr = tc.expErrString expErr = tc.expErrString
} }
if !strings.Contains(actErr, expErr) { if !strings.Contains(actErr, expErr) {
t.Errorf( t.Errorf(
"%s test failed, expected: %s, got: %s", "%s test failed, expected: %s, got: %s",
tc.name, tc.name,
expErr, expErr,
actErr) actErr)
} }
if intControlPlane.ComponentConfigs.KubeProxy.BindAddress != tc.expBindAddr { if intControlPlane.ComponentConfigs.KubeProxy.BindAddress != tc.expBindAddr {
t.Errorf("%s test failed, expected: %s, got: %s", t.Errorf("%s test failed, expected: %s, got: %s",
tc.name, tc.name,
tc.expBindAddr, tc.expBindAddr,
intControlPlane.ComponentConfigs.KubeProxy.BindAddress) intControlPlane.ComponentConfigs.KubeProxy.BindAddress)
} }
if intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR != tc.expClusterCIDR { if intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR != tc.expClusterCIDR {
t.Errorf("%s test failed, expected: %s, got: %s", t.Errorf("%s test failed, expected: %s, got: %s",
tc.name, tc.name,
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,13 +276,15 @@ func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {
daemonSetBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data) t.Run(testCase.name, func(t *testing.T) {
daemonSet := &apps.DaemonSet{} daemonSetBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), daemonSetBytes, daemonSet); err != nil { daemonSet := &apps.DaemonSet{}
t.Errorf("unexpected error: %v", err) if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), daemonSetBytes, daemonSet); err != nil {
} t.Errorf("unexpected error: %v", err)
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) 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)
}
})
} }
} }

View File

@ -95,19 +95,21 @@ func TestCreateBootstrapConfigMapIfNotExists(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
client := clientsetfake.NewSimpleClientset() t.Run(tc.name, func(t *testing.T) {
if tc.createErr != nil { client := clientsetfake.NewSimpleClientset()
client.PrependReactor("create", "configmaps", func(action core.Action) (bool, runtime.Object, error) { if tc.createErr != nil {
return true, nil, tc.createErr client.PrependReactor("create", "configmaps", func(action core.Action) (bool, runtime.Object, error) {
}) return true, nil, tc.createErr
} })
}
err := CreateBootstrapConfigMapIfNotExists(client, file.Name()) err := CreateBootstrapConfigMapIfNotExists(client, file.Name())
if tc.expectErr && err == nil { if tc.expectErr && err == nil {
t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) wanted error, got nil", tc.name) t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) wanted error, got nil", tc.name)
} 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,80 +55,91 @@ 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
if spec, ok := specs[tc.staticPodName]; ok {
// assert the spec for the staticPodName exists // Assert each specs refers to the right pod
if spec, ok := specs[assertion.staticPodName]; ok { if spec.Spec.Containers[0].Name != tc.staticPodName {
t.Errorf("getKubeConfigSpecs spec for %s contains pod %s, expects %s", tc.staticPodName, spec.Spec.Containers[0].Name, tc.staticPodName)
}
// Assert each specs refers to the right pod } else {
if spec.Spec.Containers[0].Name != assertion.staticPodName { t.Errorf("getStaticPodSpecs didn't create spec for %s ", tc.staticPodName)
t.Errorf("getKubeConfigSpecs spec for %s contains pod %s, expects %s", assertion.staticPodName, spec.Spec.Containers[0].Name, assertion.staticPodName)
} }
})
} else {
t.Errorf("getStaticPodSpecs didn't create spec for %s ", assertion.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
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
// Create temp folder for the test case // Creates a Cluster Configuration
tmpdir := testutil.SetupTempDir(t) cfg := &kubeadmapi.ClusterConfiguration{
defer os.RemoveAll(tmpdir) KubernetesVersion: "v1.9.0",
}
// Creates a Cluster Configuration // Execute createStaticPodFunction
cfg := &kubeadmapi.ClusterConfiguration{ manifestPath := filepath.Join(tmpdir, kubeadmconstants.ManifestsSubDirName)
KubernetesVersion: "v1.9.0", err := CreateStaticPodFiles(manifestPath, cfg, &kubeadmapi.APIEndpoint{}, test.components...)
} if err != nil {
t.Errorf("Error executing createStaticPodFunction: %v", err)
return
}
// Execute createStaticPodFunction // Assert expected files are there
manifestPath := filepath.Join(tmpdir, kubeadmconstants.ManifestsSubDirName) testutil.AssertFilesCount(t, manifestPath, len(test.components))
err := CreateStaticPodFiles(manifestPath, cfg, &kubeadmapi.APIEndpoint{}, test.components...)
if err != nil {
t.Errorf("Error executing createStaticPodFunction: %v", err)
continue
}
// Assert expected files are there for _, fileName := range test.components {
testutil.AssertFilesCount(t, manifestPath, len(test.components)) testutil.AssertFileExists(t, manifestPath, fileName+".yaml")
}
for _, fileName := range test.components { })
testutil.AssertFileExists(t, manifestPath, fileName+".yaml")
}
} }
} }
@ -626,12 +637,14 @@ func TestGetControllerManagerCommand(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
actual := getControllerManagerCommand(rt.cfg, version.MustParseSemantic(rt.cfg.KubernetesVersion)) t.Run(rt.name, func(t *testing.T) {
sort.Strings(actual) actual := getControllerManagerCommand(rt.cfg, version.MustParseSemantic(rt.cfg.KubernetesVersion))
sort.Strings(rt.expected) sort.Strings(actual)
if !reflect.DeepEqual(actual, rt.expected) { sort.Strings(rt.expected)
errorDiffArguments(t, rt.name, actual, rt.expected) if !reflect.DeepEqual(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 {
actualPrefix := calcNodeCidrSize(test.podSubnet) t.Run(test.name, func(t *testing.T) {
if actualPrefix != test.expectedPrefix { actualPrefix := calcNodeCidrSize(test.podSubnet)
t.Errorf("Case [%s]\nCalc of node CIDR size for pod subnet %q failed: Expected %q, saw %q", if actualPrefix != test.expectedPrefix {
test.name, test.podSubnet, test.expectedPrefix, actualPrefix) 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)
}
})
} }
} }
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,32 +794,34 @@ func TestGetControllerManagerCommandExternalCA(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
// Create temp folder for the test case t.Run(test.name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t) // Create temp folder for the test case
defer os.RemoveAll(tmpdir) tmpdir := testutil.SetupTempDir(t)
test.cfg.CertificatesDir = tmpdir defer os.RemoveAll(tmpdir)
test.cfg.CertificatesDir = tmpdir
if err := certs.CreatePKIAssets(test.cfg); err != nil { if err := certs.CreatePKIAssets(test.cfg); err != nil {
t.Errorf("failed creating pki assets: %v", err) t.Errorf("failed creating pki assets: %v", err)
}
// delete ca.key and front-proxy-ca.key if test.caKeyPresent is false
if !test.caKeyPresent {
if err := os.Remove(filepath.Join(test.cfg.CertificatesDir, kubeadmconstants.CAKeyName)); err != nil {
t.Errorf("failed removing %s: %v", kubeadmconstants.CAKeyName, err)
} }
if err := os.Remove(filepath.Join(test.cfg.CertificatesDir, kubeadmconstants.FrontProxyCAKeyName)); err != nil {
t.Errorf("failed removing %s: %v", kubeadmconstants.FrontProxyCAKeyName, err)
}
}
actual := getControllerManagerCommand(&test.cfg.ClusterConfiguration, version.MustParseSemantic(test.cfg.KubernetesVersion)) // delete ca.key and front-proxy-ca.key if test.caKeyPresent is false
expected := test.expectedArgFunc(tmpdir) if !test.caKeyPresent {
sort.Strings(actual) if err := os.Remove(filepath.Join(test.cfg.CertificatesDir, kubeadmconstants.CAKeyName)); err != nil {
sort.Strings(expected) t.Errorf("failed removing %s: %v", kubeadmconstants.CAKeyName, err)
if !reflect.DeepEqual(actual, expected) { }
errorDiffArguments(t, test.name, actual, expected) if err := os.Remove(filepath.Join(test.cfg.CertificatesDir, kubeadmconstants.FrontProxyCAKeyName)); err != nil {
} t.Errorf("failed removing %s: %v", kubeadmconstants.FrontProxyCAKeyName, err)
}
}
actual := getControllerManagerCommand(&test.cfg.ClusterConfiguration, version.MustParseSemantic(test.cfg.KubernetesVersion))
expected := test.expectedArgFunc(tmpdir)
sort.Strings(actual)
sort.Strings(expected)
if !reflect.DeepEqual(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 {
actual := getSchedulerCommand(rt.cfg) t.Run(rt.name, func(t *testing.T) {
sort.Strings(actual) actual := getSchedulerCommand(rt.cfg)
sort.Strings(rt.expected) sort.Strings(actual)
if !reflect.DeepEqual(actual, rt.expected) { sort.Strings(rt.expected)
errorDiffArguments(t, rt.name, actual, rt.expected) if !reflect.DeepEqual(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,25 +233,27 @@ func TestGetEtcdCertVolumes(t *testing.T) {
} }
for _, rt := range tests { for _, rt := range tests {
actualVol, actualVolMount := getEtcdCertVolumes(&kubeadmapi.ExternalEtcd{ t.Run(rt.name, func(t *testing.T) {
CAFile: rt.ca, actualVol, actualVolMount := getEtcdCertVolumes(&kubeadmapi.ExternalEtcd{
CertFile: rt.cert, CAFile: rt.ca,
KeyFile: rt.key, CertFile: rt.cert,
}, k8sCertifcatesDir) KeyFile: rt.key,
if !reflect.DeepEqual(actualVol, rt.vol) { }, k8sCertifcatesDir)
t.Errorf( if !reflect.DeepEqual(actualVol, rt.vol) {
"failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v", t.Errorf(
rt.vol, "failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v",
actualVol, rt.vol,
) actualVol,
} )
if !reflect.DeepEqual(actualVolMount, rt.volMount) { }
t.Errorf( if !reflect.DeepEqual(actualVolMount, rt.volMount) {
"failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v", t.Errorf(
rt.volMount, "failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v",
actualVolMount, rt.volMount,
) 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,29 +517,31 @@ 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 {
mounts := getHostPathVolumesForTheControlPlane(rt.cfg) t.Run(rt.name, func(t *testing.T) {
mounts := getHostPathVolumesForTheControlPlane(rt.cfg)
// Avoid unit test errors when the flexvolume is mounted // Avoid unit test errors when the flexvolume is mounted
if _, ok := mounts.volumes[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok { if _, ok := mounts.volumes[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok {
delete(mounts.volumes[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName) delete(mounts.volumes[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName)
} }
if _, ok := mounts.volumeMounts[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok { if _, ok := mounts.volumeMounts[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok {
delete(mounts.volumeMounts[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName) delete(mounts.volumeMounts[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName)
} }
if !reflect.DeepEqual(mounts.volumes, rt.vol) { if !reflect.DeepEqual(mounts.volumes, rt.vol) {
t.Errorf( t.Errorf(
"failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v", "failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v",
rt.vol, rt.vol,
mounts.volumes, mounts.volumes,
) )
} }
if !reflect.DeepEqual(mounts.volumeMounts, rt.volMount) { if !reflect.DeepEqual(mounts.volumeMounts, rt.volMount) {
t.Errorf( t.Errorf(
"failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v", "failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v",
rt.volMount, rt.volMount,
mounts.volumeMounts, mounts.volumeMounts,
) )
} }
})
} }
} }
@ -609,32 +614,34 @@ func TestAddExtraHostPathMounts(t *testing.T) {
} }
mounts.AddExtraHostPathMounts("component", hostPathMounts) mounts.AddExtraHostPathMounts("component", hostPathMounts)
for _, hostMount := range hostPathMounts { for _, hostMount := range hostPathMounts {
volumeName := hostMount.Name t.Run(hostMount.Name, func(t *testing.T) {
if _, ok := mounts.volumes["component"][volumeName]; !ok { volumeName := hostMount.Name
t.Errorf("Expected to find volume %q", volumeName) if _, ok := mounts.volumes["component"][volumeName]; !ok {
} t.Errorf("Expected to find volume %q", volumeName)
vol := mounts.volumes["component"][volumeName] }
if vol.Name != volumeName { vol := mounts.volumes["component"][volumeName]
t.Errorf("Expected volume name %q", volumeName) if vol.Name != volumeName {
} t.Errorf("Expected volume name %q", volumeName)
if vol.HostPath.Path != hostMount.HostPath { }
t.Errorf("Expected host path %q", hostMount.HostPath) if vol.HostPath.Path != hostMount.HostPath {
} t.Errorf("Expected host path %q", hostMount.HostPath)
if _, ok := mounts.volumeMounts["component"][volumeName]; !ok { }
t.Errorf("Expected to find volume mount %q", volumeName) if _, ok := mounts.volumeMounts["component"][volumeName]; !ok {
} t.Errorf("Expected to find volume mount %q", volumeName)
if *vol.HostPath.Type != v1.HostPathType(hostMount.PathType) { }
t.Errorf("Expected to host path type %q", hostMount.PathType) if *vol.HostPath.Type != v1.HostPathType(hostMount.PathType) {
} t.Errorf("Expected to host path type %q", hostMount.PathType)
volMount, _ := mounts.volumeMounts["component"][volumeName] }
if volMount.Name != volumeName { volMount, _ := mounts.volumeMounts["component"][volumeName]
t.Errorf("Expected volume mount name %q", volumeName) if volMount.Name != volumeName {
} t.Errorf("Expected volume mount name %q", volumeName)
if volMount.MountPath != hostMount.MountPath { }
t.Errorf("Expected container path %q", hostMount.MountPath) if volMount.MountPath != hostMount.MountPath {
} t.Errorf("Expected container path %q", hostMount.MountPath)
if volMount.ReadOnly != hostMount.ReadOnly { }
t.Errorf("Expected volume readOnly setting %t", hostMount.ReadOnly) if volMount.ReadOnly != 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,47 +136,49 @@ func TestGetKubeConfigSpecs(t *testing.T) {
} }
for _, assertion := range assertions { for _, assertion := range assertions {
// Executes getKubeConfigSpecs t.Run(fmt.Sprintf("%d-%s", i, assertion.clientName), func(t *testing.T) {
specs, err := getKubeConfigSpecs(cfg) // Executes getKubeConfigSpecs
if err != nil { specs, err := getKubeConfigSpecs(cfg)
t.Fatal("getKubeConfigSpecs failed!") if err != nil {
} t.Fatal("getKubeConfigSpecs failed!")
}
var spec *kubeConfigSpec var spec *kubeConfigSpec
var ok bool var ok bool
// 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
if spec.ClientName != assertion.clientName { if spec.ClientName != assertion.clientName {
t.Errorf("getKubeConfigSpecs for %s clientName is %s, expected %s", assertion.kubeConfigFile, spec.ClientName, assertion.clientName) t.Errorf("getKubeConfigSpecs for %s clientName is %s, expected %s", assertion.kubeConfigFile, spec.ClientName, assertion.clientName)
} }
// Assert Organizations // Assert Organizations
if spec.ClientCertAuth == nil || !reflect.DeepEqual(spec.ClientCertAuth.Organizations, assertion.organizations) { if spec.ClientCertAuth == nil || !reflect.DeepEqual(spec.ClientCertAuth.Organizations, assertion.organizations) {
t.Errorf("getKubeConfigSpecs for %s Organizations is %v, expected %v", assertion.kubeConfigFile, spec.ClientCertAuth.Organizations, assertion.organizations) t.Errorf("getKubeConfigSpecs for %s Organizations is %v, expected %v", assertion.kubeConfigFile, spec.ClientCertAuth.Organizations, assertion.organizations)
} }
// Asserts InitConfiguration values injected into spec // Asserts InitConfiguration values injected into spec
controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint) controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if spec.APIServer != controlPlaneEndpoint { if spec.APIServer != controlPlaneEndpoint {
t.Errorf("getKubeConfigSpecs didn't injected cfg.APIServer endpoint into spec for %s", assertion.kubeConfigFile) t.Errorf("getKubeConfigSpecs didn't injected cfg.APIServer endpoint into spec for %s", assertion.kubeConfigFile)
} }
// Asserts CA certs and CA keys loaded into specs // Asserts CA certs and CA keys loaded into specs
if spec.CACert == nil { if spec.CACert == nil {
t.Errorf("getKubeConfigSpecs didn't loaded CACert into spec for %s!", assertion.kubeConfigFile) t.Errorf("getKubeConfigSpecs didn't loaded CACert into spec for %s!", assertion.kubeConfigFile)
} }
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,44 +248,49 @@ func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
// Create temp folder for the test case t.Run(test.name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t) // Create temp folder for the test case
defer os.RemoveAll(tmpdir) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
// Writes the existing kubeconfig file to disk // Writes the existing kubeconfig file to disk
if test.existingKubeConfig != nil { if test.existingKubeConfig != nil {
if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil { if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed")
}
}
// Writes the kubeconfig file to disk
err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.kubeConfig)
if test.expectedError && err == nil {
t.Errorf("createKubeConfigFileIfNotExists didn't failed when expected to fail")
}
if !test.expectedError && err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed") t.Errorf("createKubeConfigFileIfNotExists failed")
} }
}
// Writes the kubeconfig file to disk // Assert that the created file is there
err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.kubeConfig) testutil.AssertFileExists(t, tmpdir, "test.conf")
if test.expectedError && err == nil { })
t.Errorf("createKubeConfigFileIfNotExists didn't failed when expected to fail")
}
if !test.expectedError && err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed")
}
// Assert that the created file is there
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,39 +311,40 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
// Create temp folder for the test case t.Run(test.name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t) // Create temp folder for the test case
defer os.RemoveAll(tmpdir) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
// Adds a pki folder with a ca certs to the temp folder // Adds a pki folder with a ca certs to the temp folder
pkidir := testutil.SetupPkiDirWithCertificateAuthorithy(t, tmpdir) pkidir := testutil.SetupPkiDirWithCertificateAuthorithy(t, tmpdir)
// Creates an InitConfiguration pointing to the pkidir folder // Creates an InitConfiguration pointing to the pkidir folder
cfg := &kubeadmapi.InitConfiguration{ cfg := &kubeadmapi.InitConfiguration{
LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234}, LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
ClusterConfiguration: kubeadmapi.ClusterConfiguration{ ClusterConfiguration: kubeadmapi.ClusterConfiguration{
CertificatesDir: pkidir, CertificatesDir: pkidir,
}, },
} }
// Execs the createKubeConfigFunction // Execs the createKubeConfigFunction
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 {
buf := new(bytes.Buffer) t.Run(test.name, func(t *testing.T) {
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,33 +431,35 @@ func TestWriteKubeConfig(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
buf := new(bytes.Buffer) t.Run(test.name, func(t *testing.T) {
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
kubeconfigtestutil.AssertKubeConfigCurrentCluster(t, config, "https://1.2.3.4:1234", caCert) kubeconfigtestutil.AssertKubeConfigCurrentCluster(t, config, "https://1.2.3.4:1234", caCert)
if test.withClientCert { if test.withClientCert {
// checks that kubeconfig files have expected client cert // checks that kubeconfig files have expected client cert
kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithClientCert(t, config, caCert, "myUser") kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithClientCert(t, config, caCert, "myUser")
} }
if test.withToken { if test.withToken {
// 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,25 +498,27 @@ func TestValidateKubeConfig(t *testing.T) {
} }
for name, test := range tests { for name, test := range tests {
tmpdir := testutil.SetupTempDir(t) t.Run(name, func(t *testing.T) {
defer os.RemoveAll(tmpdir) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
if test.existingKubeConfig != nil { if test.existingKubeConfig != nil {
if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil { if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed") t.Errorf("createKubeConfigFileIfNotExists failed")
}
} }
}
err := validateKubeConfig(tmpdir, "test.conf", test.kubeConfig) err := validateKubeConfig(tmpdir, "test.conf", test.kubeConfig)
if (err != nil) != test.expectedError { if (err != nil) != test.expectedError {
t.Fatalf(dedent.Dedent( t.Fatalf(dedent.Dedent(
"validateKubeConfig failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"), "validateKubeConfig failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
name, name,
test.expectedError, test.expectedError,
(err != nil), (err != nil),
err, err,
) )
} }
})
} }
} }
@ -581,25 +606,27 @@ func TestValidateKubeconfigsForExternalCA(t *testing.T) {
} }
for name, test := range tests { for name, test := range tests {
tmpdir := testutil.SetupTempDir(t) t.Run(name, func(t *testing.T) {
defer os.RemoveAll(tmpdir) tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
for name, config := range test.filesToWrite { for name, config := range test.filesToWrite {
if err := createKubeConfigFileIfNotExists(tmpdir, name, config); err != nil { if err := createKubeConfigFileIfNotExists(tmpdir, name, config); err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed: %v", err) t.Errorf("createKubeConfigFileIfNotExists failed: %v", err)
}
} }
}
err := ValidateKubeconfigsForExternalCA(tmpdir, test.initConfig) err := ValidateKubeconfigsForExternalCA(tmpdir, test.initConfig)
if (err != nil) != test.expectedError { if (err != nil) != test.expectedError {
t.Fatalf(dedent.Dedent( t.Fatalf(dedent.Dedent(
"ValidateKubeconfigsForExternalCA failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"), "ValidateKubeconfigsForExternalCA failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
name, name,
test.expectedError, test.expectedError,
(err != nil), (err != nil),
err, err,
) )
} }
})
} }
} }

View File

@ -107,69 +107,71 @@ func TestMarkControlPlane(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
hostname, err := node.GetHostname("") t.Run(tc.name, func(t *testing.T) {
if err != nil { hostname, err := node.GetHostname("")
t.Fatalf("MarkControlPlane(%s): unexpected error: %v", tc.name, err) if err != nil {
} t.Fatalf("MarkControlPlane(%s): unexpected error: %v", tc.name, err)
controlPlaneNode := &v1.Node{ }
ObjectMeta: metav1.ObjectMeta{ controlPlaneNode := &v1.Node{
Name: hostname, ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{ Name: hostname,
v1.LabelHostname: hostname, Labels: map[string]string{
v1.LabelHostname: hostname,
},
}, },
},
}
if tc.existingLabel != "" {
controlPlaneNode.ObjectMeta.Labels[tc.existingLabel] = ""
}
if tc.existingTaints != nil {
controlPlaneNode.Spec.Taints = tc.existingTaints
}
jsonNode, err := json.Marshal(controlPlaneNode)
if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected encoding error: %v", tc.name, err)
}
var patchRequest string
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
if req.URL.Path != "/api/v1/nodes/"+hostname {
t.Errorf("MarkControlPlane(%s): request for unexpected HTTP resource: %v", tc.name, req.URL.Path)
http.Error(w, "", http.StatusNotFound)
return
} }
switch req.Method { if tc.existingLabel != "" {
case "GET": controlPlaneNode.ObjectMeta.Labels[tc.existingLabel] = ""
case "PATCH":
patchRequest = toString(req.Body)
default:
t.Errorf("MarkControlPlane(%s): request for unexpected HTTP verb: %v", tc.name, req.Method)
http.Error(w, "", http.StatusNotFound)
return
} }
w.WriteHeader(http.StatusOK) if tc.existingTaints != nil {
w.Write(jsonNode) controlPlaneNode.Spec.Taints = tc.existingTaints
})) }
defer s.Close()
cs, err := clientset.NewForConfig(&restclient.Config{Host: s.URL}) jsonNode, err := json.Marshal(controlPlaneNode)
if err != nil { if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected error building clientset: %v", tc.name, err) t.Fatalf("MarkControlPlane(%s): unexpected encoding error: %v", tc.name, err)
} }
if err := MarkControlPlane(cs, hostname, tc.newTaints); err != nil { var patchRequest string
t.Errorf("MarkControlPlane(%s) returned unexpected error: %v", tc.name, err) s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
} w.Header().Set("Content-Type", "application/json")
if tc.expectedPatch != patchRequest { if req.URL.Path != "/api/v1/nodes/"+hostname {
t.Errorf("MarkControlPlane(%s) wanted patch %v, got %v", tc.name, tc.expectedPatch, patchRequest) t.Errorf("MarkControlPlane(%s): request for unexpected HTTP resource: %v", tc.name, req.URL.Path)
} http.Error(w, "", http.StatusNotFound)
return
}
switch req.Method {
case "GET":
case "PATCH":
patchRequest = toString(req.Body)
default:
t.Errorf("MarkControlPlane(%s): request for unexpected HTTP verb: %v", tc.name, req.Method)
http.Error(w, "", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Write(jsonNode)
}))
defer s.Close()
cs, err := clientset.NewForConfig(&restclient.Config{Host: s.URL})
if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected error building clientset: %v", tc.name, err)
}
if err := MarkControlPlane(cs, hostname, tc.newTaints); err != nil {
t.Errorf("MarkControlPlane(%s) returned unexpected error: %v", tc.name, err)
}
if tc.expectedPatch != patchRequest {
t.Errorf("MarkControlPlane(%s) wanted patch %v, got %v", tc.name, tc.expectedPatch, patchRequest)
}
})
} }
} }