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 {
client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil {
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)
t.Run(tc.name, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil {
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, tc.createErr
})
}
continue
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
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)
err := CreateServiceAccount(client)
if tc.expectErr {
if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
}
return
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
}
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) {
var tests = []struct {
name string
manifest string
data interface{}
expected bool
}{
{
name: "KubeDNSDeployment manifest",
manifest: KubeDNSDeployment,
data: struct{ DeploymentName, KubeDNSImage, DNSMasqImage, SidecarImage, DNSBindAddr, DNSProbeAddr, DNSDomain, ControlPlaneTaintKey string }{
DeploymentName: "foo",
@ -108,32 +110,25 @@ func TestCompileManifests(t *testing.T) {
DNSDomain: "foo",
ControlPlaneTaintKey: "foo",
},
expected: true,
},
{
name: "KubeDNSService manifest",
manifest: KubeDNSService,
data: struct{ DNSIP string }{
DNSIP: "foo",
},
expected: true,
},
{
name: "CoreDNSDeployment manifest",
manifest: CoreDNSDeployment,
data: struct{ DeploymentName, Image, ControlPlaneTaintKey string }{
DeploymentName: "foo",
Image: "foo",
ControlPlaneTaintKey: "foo",
},
expected: true,
},
{
manifest: KubeDNSService,
data: struct{ DNSIP string }{
DNSIP: "foo",
},
expected: true,
},
{
name: "CoreDNSConfigMap manifest",
manifest: CoreDNSConfigMap,
data: struct{ DNSDomain, Federation, UpstreamNameserver, StubDomain string }{
DNSDomain: "foo",
@ -141,58 +136,61 @@ func TestCompileManifests(t *testing.T) {
UpstreamNameserver: "foo",
StubDomain: "foo",
},
expected: true,
},
}
for _, rt := range tests {
_, actual := kubeadmutil.ParseTemplate(rt.manifest, rt.data)
if (actual == nil) != rt.expected {
t.Errorf(
"failed CompileManifests:\n\texpected: %t\n\t actual: %t",
rt.expected,
(actual == nil),
)
}
t.Run(rt.name, func(t *testing.T) {
_, err := kubeadmutil.ParseTemplate(rt.manifest, rt.data)
if err != nil {
t.Errorf("unexpected ParseTemplate failure: %+v", err)
}
})
}
}
func TestGetDNSIP(t *testing.T) {
var tests = []struct {
svcSubnet, expectedDNSIP string
name, svcSubnet, expectedDNSIP string
}{
{
name: "subnet mask 12",
svcSubnet: "10.96.0.0/12",
expectedDNSIP: "10.96.0.10",
},
{
name: "subnet mask 26",
svcSubnet: "10.87.116.64/26",
expectedDNSIP: "10.87.116.74",
},
}
for _, rt := range tests {
dnsIP, err := kubeadmconstants.GetDNSIP(rt.svcSubnet)
if err != nil {
t.Fatalf("couldn't get dnsIP : %v", err)
}
t.Run(rt.name, func(t *testing.T) {
dnsIP, err := kubeadmconstants.GetDNSIP(rt.svcSubnet)
if err != nil {
t.Fatalf("couldn't get dnsIP : %v", err)
}
actualDNSIP := dnsIP.String()
if actualDNSIP != rt.expectedDNSIP {
t.Errorf(
"failed GetDNSIP\n\texpected: %s\n\t actual: %s",
rt.expectedDNSIP,
actualDNSIP,
)
}
actualDNSIP := dnsIP.String()
if actualDNSIP != rt.expectedDNSIP {
t.Errorf(
"failed GetDNSIP\n\texpected: %s\n\t actual: %s",
rt.expectedDNSIP,
actualDNSIP,
)
}
})
}
}
func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
testCases := []struct {
name string
configMap *v1.ConfigMap
expectOne string
expectTwo string
}{
{
name: "valid call 1",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns",
@ -234,6 +232,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
}`,
},
{
name: "empty call",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kubedns",
@ -244,6 +243,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
expectOne: "",
},
{
name: "valid call 2",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns",
@ -285,6 +285,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
}`,
},
{
name: "missing stubDomains",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns",
@ -299,22 +300,26 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
},
}
for _, testCase := range testCases {
out, err := translateStubDomainOfKubeDNSToForwardCoreDNS(kubeDNSStubDomain, testCase.configMap)
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)
}
t.Run(testCase.name, func(t *testing.T) {
out, err := translateStubDomainOfKubeDNSToForwardCoreDNS(kubeDNSStubDomain, testCase.configMap)
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)
}
})
}
}
func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
testCases := []struct {
name string
configMap *v1.ConfigMap
expect string
}{
{
name: "expect resolv.conf",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns",
@ -325,6 +330,7 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
expect: "/etc/resolv.conf",
},
{
name: "expect list of Name Server IP addresses",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kubedns",
@ -339,6 +345,7 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
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{
ObjectMeta: metav1.ObjectMeta{
Name: "kubedns",
@ -353,23 +360,27 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
},
}
for _, testCase := range testCases {
out, err := translateUpstreamNameServerOfKubeDNSToUpstreamProxyCoreDNS(kubeDNSUpstreamNameservers, testCase.configMap)
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)
}
t.Run(testCase.name, func(t *testing.T) {
out, err := translateUpstreamNameServerOfKubeDNSToUpstreamProxyCoreDNS(kubeDNSUpstreamNameservers, testCase.configMap)
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)
}
})
}
}
func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
testCases := []struct {
name string
configMap *v1.ConfigMap
expectOne string
expectTwo string
}{
{
name: "valid call",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns",
@ -394,6 +405,7 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
}`,
},
{
name: "empty data",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kubedns",
@ -404,6 +416,7 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
expectOne: "",
},
{
name: "missing federations data",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-dns",
@ -419,22 +432,26 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
},
}
for _, testCase := range testCases {
out, err := translateFederationsofKubeDNSToCoreDNS(kubeDNSFederation, "cluster.local", testCase.configMap)
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)
}
t.Run(testCase.name, func(t *testing.T) {
out, err := translateFederationsofKubeDNSToCoreDNS(kubeDNSFederation, "cluster.local", testCase.configMap)
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)
}
})
}
}
func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
testCases := []struct {
name string
manifest string
data interface{}
}{
{
name: "KubeDNSDeployment",
manifest: KubeDNSDeployment,
data: struct{ DeploymentName, KubeDNSImage, DNSMasqImage, SidecarImage, DNSBindAddr, DNSProbeAddr, DNSDomain, ControlPlaneTaintKey string }{
DeploymentName: "foo",
@ -448,6 +465,7 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
},
},
{
name: "CoreDNSDeployment",
manifest: CoreDNSDeployment,
data: struct{ DeploymentName, Image, ControlPlaneTaintKey string }{
DeploymentName: "foo",
@ -457,13 +475,15 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
},
}
for _, testCase := range testCases {
deploymentBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
deployment := &apps.Deployment{}
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)
}
t.Run(testCase.name, func(t *testing.T) {
deploymentBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
deployment := &apps.Deployment{}
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)
}
})
}
}

View File

@ -62,45 +62,48 @@ func TestCreateServiceAccount(t *testing.T) {
}
for _, tc := range tests {
client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil {
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)
t.Run(tc.name, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil {
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, tc.createErr
})
}
continue
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
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)
err := CreateServiceAccount(client)
if tc.expectErr {
if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
}
return
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
}
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) {
var tests = []struct {
name string
manifest string
data interface{}
expected bool
}{
{
name: "KubeProxyConfigMap19",
manifest: KubeProxyConfigMap19,
data: struct {
ControlPlaneEndpoint, ProxyConfig, ProxyConfigMap, ProxyConfigMapKey string
@ -110,28 +113,24 @@ func TestCompileManifests(t *testing.T) {
ProxyConfigMap: "bar",
ProxyConfigMapKey: "baz",
},
expected: true,
},
{
name: "KubeProxyDaemonSet19",
manifest: KubeProxyDaemonSet19,
data: struct{ Image, ProxyConfigMap, ProxyConfigMapKey string }{
Image: "foo",
ProxyConfigMap: "bar",
ProxyConfigMapKey: "baz",
},
expected: true,
},
}
for _, rt := range tests {
_, actual := kubeadmutil.ParseTemplate(rt.manifest, rt.data)
if (actual == nil) != rt.expected {
t.Errorf(
"failed to compile %s manifest:\n\texpected: %t\n\t actual: %t",
rt.manifest,
rt.expected,
(actual == nil),
)
}
t.Run(rt.name, func(t *testing.T) {
_, err := kubeadmutil.ParseTemplate(rt.manifest, rt.data)
if err != nil {
t.Errorf("unexpected ParseTemplate faiure: %+v", err)
}
})
}
}
@ -173,98 +172,101 @@ func TestEnsureProxyAddon(t *testing.T) {
}
for _, tc := range testCases {
// Create a fake client and set up default test configuration
client := clientsetfake.NewSimpleClientset()
// TODO: Consider using a YAML file instead for this that makes it possible to specify YAML documents for the ComponentConfigs
controlPlaneConfig := &kubeadmapiv1beta1.InitConfiguration{
LocalAPIEndpoint: kubeadmapiv1beta1.APIEndpoint{
AdvertiseAddress: "1.2.3.4",
BindPort: 1234,
},
ClusterConfiguration: kubeadmapiv1beta1.ClusterConfiguration{
Networking: kubeadmapiv1beta1.Networking{
PodSubnet: "5.6.7.8/24",
t.Run(tc.name, func(t *testing.T) {
// Create a fake client and set up default test configuration
client := clientsetfake.NewSimpleClientset()
// TODO: Consider using a YAML file instead for this that makes it possible to specify YAML documents for the ComponentConfigs
controlPlaneConfig := &kubeadmapiv1beta1.InitConfiguration{
LocalAPIEndpoint: kubeadmapiv1beta1.APIEndpoint{
AdvertiseAddress: "1.2.3.4",
BindPort: 1234,
},
ImageRepository: "someRepo",
KubernetesVersion: constants.MinimumControlPlaneVersion.String(),
},
}
ClusterConfiguration: kubeadmapiv1beta1.ClusterConfiguration{
Networking: kubeadmapiv1beta1.Networking{
PodSubnet: "5.6.7.8/24",
},
ImageRepository: "someRepo",
KubernetesVersion: constants.MinimumControlPlaneVersion.String(),
},
}
// Simulate an error if necessary
switch tc.simError {
case ServiceAccountError:
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, apierrors.NewUnauthorized("")
})
case InvalidControlPlaneEndpoint:
controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1.2.3"
case IPv6SetBindAddress:
controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1:2::3:4"
controlPlaneConfig.Networking.PodSubnet = "2001:101::/96"
}
// Simulate an error if necessary
switch tc.simError {
case ServiceAccountError:
client.PrependReactor("create", "serviceaccounts", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, apierrors.NewUnauthorized("")
})
case InvalidControlPlaneEndpoint:
controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1.2.3"
case IPv6SetBindAddress:
controlPlaneConfig.LocalAPIEndpoint.AdvertiseAddress = "1:2::3:4"
controlPlaneConfig.Networking.PodSubnet = "2001:101::/96"
}
intControlPlane, err := configutil.DefaultedInitConfiguration(controlPlaneConfig)
if err != nil {
t.Errorf("test failed to convert external to internal version")
break
}
intControlPlane.ComponentConfigs.KubeProxy = &kubeproxyconfig.KubeProxyConfiguration{
BindAddress: "",
HealthzBindAddress: "0.0.0.0:10256",
MetricsBindAddress: "127.0.0.1:10249",
Conntrack: kubeproxyconfig.KubeProxyConntrackConfiguration{
Max: pointer.Int32Ptr(2),
MaxPerCore: pointer.Int32Ptr(1),
Min: pointer.Int32Ptr(1),
TCPEstablishedTimeout: &metav1.Duration{Duration: 5 * time.Second},
TCPCloseWaitTimeout: &metav1.Duration{Duration: 5 * time.Second},
},
}
// Run dynamic defaulting again as we changed the internal cfg
if err := configutil.SetInitDynamicDefaults(intControlPlane); err != nil {
t.Errorf("test failed to set dynamic defaults: %v", err)
break
}
err = EnsureProxyAddon(&intControlPlane.ClusterConfiguration, &intControlPlane.LocalAPIEndpoint, client)
intControlPlane, err := configutil.DefaultedInitConfiguration(controlPlaneConfig)
if err != nil {
t.Errorf("test failed to convert external to internal version")
return
}
intControlPlane.ComponentConfigs.KubeProxy = &kubeproxyconfig.KubeProxyConfiguration{
BindAddress: "",
HealthzBindAddress: "0.0.0.0:10256",
MetricsBindAddress: "127.0.0.1:10249",
Conntrack: kubeproxyconfig.KubeProxyConntrackConfiguration{
Max: pointer.Int32Ptr(2),
MaxPerCore: pointer.Int32Ptr(1),
Min: pointer.Int32Ptr(1),
TCPEstablishedTimeout: &metav1.Duration{Duration: 5 * time.Second},
TCPCloseWaitTimeout: &metav1.Duration{Duration: 5 * time.Second},
},
}
// Run dynamic defaulting again as we changed the internal cfg
if err := configutil.SetInitDynamicDefaults(intControlPlane); err != nil {
t.Errorf("test failed to set dynamic defaults: %v", err)
return
}
err = EnsureProxyAddon(&intControlPlane.ClusterConfiguration, &intControlPlane.LocalAPIEndpoint, client)
// Compare actual to expected errors
actErr := "No error"
if err != nil {
actErr = err.Error()
}
expErr := "No error"
if tc.expErrString != "" {
expErr = tc.expErrString
}
if !strings.Contains(actErr, expErr) {
t.Errorf(
"%s test failed, expected: %s, got: %s",
tc.name,
expErr,
actErr)
}
if intControlPlane.ComponentConfigs.KubeProxy.BindAddress != tc.expBindAddr {
t.Errorf("%s test failed, expected: %s, got: %s",
tc.name,
tc.expBindAddr,
intControlPlane.ComponentConfigs.KubeProxy.BindAddress)
}
if intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR != tc.expClusterCIDR {
t.Errorf("%s test failed, expected: %s, got: %s",
tc.name,
tc.expClusterCIDR,
intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR)
}
// Compare actual to expected errors
actErr := "No error"
if err != nil {
actErr = err.Error()
}
expErr := "No error"
if tc.expErrString != "" {
expErr = tc.expErrString
}
if !strings.Contains(actErr, expErr) {
t.Errorf(
"%s test failed, expected: %s, got: %s",
tc.name,
expErr,
actErr)
}
if intControlPlane.ComponentConfigs.KubeProxy.BindAddress != tc.expBindAddr {
t.Errorf("%s test failed, expected: %s, got: %s",
tc.name,
tc.expBindAddr,
intControlPlane.ComponentConfigs.KubeProxy.BindAddress)
}
if intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR != tc.expClusterCIDR {
t.Errorf("%s test failed, expected: %s, got: %s",
tc.name,
tc.expClusterCIDR,
intControlPlane.ComponentConfigs.KubeProxy.ClusterCIDR)
}
})
}
}
func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
testCases := []struct {
name string
manifest string
data interface{}
}{
{
name: "KubeProxyDaemonSet19",
manifest: KubeProxyDaemonSet19,
data: struct{ Image, ProxyConfigMap, ProxyConfigMapKey string }{
Image: "foo",
@ -274,13 +276,15 @@ func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
},
}
for _, testCase := range testCases {
daemonSetBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
daemonSet := &apps.DaemonSet{}
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)
}
t.Run(testCase.name, func(t *testing.T) {
daemonSetBytes, _ := kubeadmutil.ParseTemplate(testCase.manifest, testCase.data)
daemonSet := &apps.DaemonSet{}
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)
}
})
}
}

View File

@ -95,19 +95,21 @@ func TestCreateBootstrapConfigMapIfNotExists(t *testing.T) {
}
for _, tc := range tests {
client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil {
client.PrependReactor("create", "configmaps", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, tc.createErr
})
}
t.Run(tc.name, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset()
if tc.createErr != nil {
client.PrependReactor("create", "configmaps", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, tc.createErr
})
}
err := CreateBootstrapConfigMapIfNotExists(client, file.Name())
if tc.expectErr && err == nil {
t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) wanted error, got nil", tc.name)
} else if !tc.expectErr && err != nil {
t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) returned unexpected error: %v", tc.name, err)
}
err := CreateBootstrapConfigMapIfNotExists(client, file.Name())
if tc.expectErr && err == nil {
t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) wanted error, got nil", tc.name)
} else if !tc.expectErr && err != nil {
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)
var assertions = []struct {
var tests = []struct {
name string
staticPodName string
}{
{
name: "KubeAPIServer",
staticPodName: kubeadmconstants.KubeAPIServer,
},
{
name: "KubeControllerManager",
staticPodName: kubeadmconstants.KubeControllerManager,
},
{
name: "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
if spec, ok := specs[assertion.staticPodName]; ok {
// Assert each specs refers to the right pod
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
if spec.Spec.Containers[0].Name != assertion.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 ", tc.staticPodName)
}
} else {
t.Errorf("getStaticPodSpecs didn't create spec for %s ", assertion.staticPodName)
}
})
}
}
func TestCreateStaticPodFilesAndWrappers(t *testing.T) {
var tests = []struct {
name string
components []string
}{
{
name: "KubeAPIServer KubeAPIServer KubeScheduler",
components: []string{kubeadmconstants.KubeAPIServer, kubeadmconstants.KubeControllerManager, kubeadmconstants.KubeScheduler},
},
{
name: "KubeAPIServer",
components: []string{kubeadmconstants.KubeAPIServer},
},
{
name: "KubeControllerManager",
components: []string{kubeadmconstants.KubeControllerManager},
},
{
name: "KubeScheduler",
components: []string{kubeadmconstants.KubeScheduler},
},
}
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
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
// Creates a Cluster Configuration
cfg := &kubeadmapi.ClusterConfiguration{
KubernetesVersion: "v1.9.0",
}
// Creates a Cluster Configuration
cfg := &kubeadmapi.ClusterConfiguration{
KubernetesVersion: "v1.9.0",
}
// Execute createStaticPodFunction
manifestPath := filepath.Join(tmpdir, kubeadmconstants.ManifestsSubDirName)
err := CreateStaticPodFiles(manifestPath, cfg, &kubeadmapi.APIEndpoint{}, test.components...)
if err != nil {
t.Errorf("Error executing createStaticPodFunction: %v", err)
return
}
// Execute createStaticPodFunction
manifestPath := filepath.Join(tmpdir, kubeadmconstants.ManifestsSubDirName)
err := CreateStaticPodFiles(manifestPath, cfg, &kubeadmapi.APIEndpoint{}, test.components...)
if err != nil {
t.Errorf("Error executing createStaticPodFunction: %v", err)
continue
}
// Assert expected files are there
testutil.AssertFilesCount(t, manifestPath, len(test.components))
// Assert expected files are there
testutil.AssertFilesCount(t, manifestPath, len(test.components))
for _, fileName := range 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 {
actual := getControllerManagerCommand(rt.cfg, version.MustParseSemantic(rt.cfg.KubernetesVersion))
sort.Strings(actual)
sort.Strings(rt.expected)
if !reflect.DeepEqual(actual, rt.expected) {
errorDiffArguments(t, rt.name, actual, rt.expected)
}
t.Run(rt.name, func(t *testing.T) {
actual := getControllerManagerCommand(rt.cfg, version.MustParseSemantic(rt.cfg.KubernetesVersion))
sort.Strings(actual)
sort.Strings(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 {
actualPrefix := calcNodeCidrSize(test.podSubnet)
if actualPrefix != test.expectedPrefix {
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)
}
t.Run(test.name, func(t *testing.T) {
actualPrefix := calcNodeCidrSize(test.podSubnet)
if actualPrefix != test.expectedPrefix {
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) {
tests := []struct {
name string
cfg *kubeadmapi.InitConfiguration
@ -780,32 +794,34 @@ func TestGetControllerManagerCommandExternalCA(t *testing.T) {
}
for _, test := range tests {
// Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
test.cfg.CertificatesDir = tmpdir
t.Run(test.name, func(t *testing.T) {
// Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
test.cfg.CertificatesDir = tmpdir
if err := certs.CreatePKIAssets(test.cfg); err != nil {
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 := certs.CreatePKIAssets(test.cfg); err != nil {
t.Errorf("failed creating pki assets: %v", 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))
expected := test.expectedArgFunc(tmpdir)
sort.Strings(actual)
sort.Strings(expected)
if !reflect.DeepEqual(actual, expected) {
errorDiffArguments(t, test.name, actual, expected)
}
// 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))
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 {
actual := getSchedulerCommand(rt.cfg)
sort.Strings(actual)
sort.Strings(rt.expected)
if !reflect.DeepEqual(actual, rt.expected) {
errorDiffArguments(t, rt.name, actual, rt.expected)
}
t.Run(rt.name, func(t *testing.T) {
actual := getSchedulerCommand(rt.cfg)
sort.Strings(actual)
sort.Strings(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 {
t.Run(rt.name, func(t *testing.T) {
actual := getAuthzModes(strings.Join(rt.authMode, ","))
if actual != rt.expected {

View File

@ -32,12 +32,12 @@ func TestGetEtcdCertVolumes(t *testing.T) {
hostPathDirectoryOrCreate := v1.HostPathDirectoryOrCreate
k8sCertifcatesDir := "/etc/kubernetes/pki"
var tests = []struct {
ca, cert, key string
vol []v1.Volume
volMount []v1.VolumeMount
name, ca, cert, key string
vol []v1.Volume
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",
cert: "/etc/ssl/certs/my-etcd.crt",
key: "/etc/ssl/certs/my-etcd.key",
@ -45,7 +45,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
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",
cert: "/etc/ssl/certs/etcd/my-etcd.crt",
key: "/etc/ssl/certs/etcd/my-etcd.key",
@ -53,7 +53,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
volMount: []v1.VolumeMount{},
},
{
// Should ignore files in /etc/pki
name: "Should ignore files in /etc/pki",
ca: "/etc/pki/my-etcd-ca.crt",
cert: "/etc/pki/my-etcd.crt",
key: "/etc/pki/my-etcd.key",
@ -61,7 +61,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
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",
cert: k8sCertifcatesDir + "/my-etcd.crt",
key: k8sCertifcatesDir + "/my-etcd.key",
@ -69,7 +69,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
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",
cert: "/var/lib/certs/etcd/my-etcd.crt",
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",
cert: "/var/lib/certs/etcd/my-etcd.crt",
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",
cert: "/var/lib/certs/etcd/my-etcd.crt",
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",
cert: "/etc/certs/etcd/serving/my-etcd.crt",
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",
cert: "/etc/certs/etcd/my-etcd.crt",
key: "/etc/certs/etcd/my-etcd.key",
@ -233,25 +233,27 @@ func TestGetEtcdCertVolumes(t *testing.T) {
}
for _, rt := range tests {
actualVol, actualVolMount := getEtcdCertVolumes(&kubeadmapi.ExternalEtcd{
CAFile: rt.ca,
CertFile: rt.cert,
KeyFile: rt.key,
}, k8sCertifcatesDir)
if !reflect.DeepEqual(actualVol, rt.vol) {
t.Errorf(
"failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v",
rt.vol,
actualVol,
)
}
if !reflect.DeepEqual(actualVolMount, rt.volMount) {
t.Errorf(
"failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v",
rt.volMount,
actualVolMount,
)
}
t.Run(rt.name, func(t *testing.T) {
actualVol, actualVolMount := getEtcdCertVolumes(&kubeadmapi.ExternalEtcd{
CAFile: rt.ca,
CertFile: rt.cert,
KeyFile: rt.key,
}, k8sCertifcatesDir)
if !reflect.DeepEqual(actualVol, rt.vol) {
t.Errorf(
"failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v",
rt.vol,
actualVol,
)
}
if !reflect.DeepEqual(actualVolMount, rt.volMount) {
t.Errorf(
"failed getEtcdCertVolumes:\n\texpected: %v\n\t actual: %v",
rt.volMount,
actualVolMount,
)
}
})
}
}
@ -472,12 +474,13 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
ReadOnly: true,
}
var tests = []struct {
name string
cfg *kubeadmapi.ClusterConfiguration
vol map[string]map[string]v1.Volume
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{
CertificatesDir: testCertsDir,
Etcd: kubeadmapi.Etcd{},
@ -486,7 +489,7 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
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{
CertificatesDir: testCertsDir,
Etcd: kubeadmapi.Etcd{
@ -514,29 +517,31 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
defer func() { caCertsExtraVolumePaths = []string{"/etc/pki", "/usr/share/ca-certificates"} }()
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
if _, ok := mounts.volumes[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok {
delete(mounts.volumes[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName)
}
if _, ok := mounts.volumeMounts[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok {
delete(mounts.volumeMounts[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName)
}
if !reflect.DeepEqual(mounts.volumes, rt.vol) {
t.Errorf(
"failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v",
rt.vol,
mounts.volumes,
)
}
if !reflect.DeepEqual(mounts.volumeMounts, rt.volMount) {
t.Errorf(
"failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v",
rt.volMount,
mounts.volumeMounts,
)
}
// Avoid unit test errors when the flexvolume is mounted
if _, ok := mounts.volumes[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok {
delete(mounts.volumes[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName)
}
if _, ok := mounts.volumeMounts[kubeadmconstants.KubeControllerManager][flexvolumeDirVolumeName]; ok {
delete(mounts.volumeMounts[kubeadmconstants.KubeControllerManager], flexvolumeDirVolumeName)
}
if !reflect.DeepEqual(mounts.volumes, rt.vol) {
t.Errorf(
"failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v",
rt.vol,
mounts.volumes,
)
}
if !reflect.DeepEqual(mounts.volumeMounts, rt.volMount) {
t.Errorf(
"failed getHostPathVolumesForTheControlPlane:\n\texpected: %v\n\t actual: %v",
rt.volMount,
mounts.volumeMounts,
)
}
})
}
}
@ -609,32 +614,34 @@ func TestAddExtraHostPathMounts(t *testing.T) {
}
mounts.AddExtraHostPathMounts("component", hostPathMounts)
for _, hostMount := range hostPathMounts {
volumeName := hostMount.Name
if _, ok := mounts.volumes["component"][volumeName]; !ok {
t.Errorf("Expected to find volume %q", volumeName)
}
vol := mounts.volumes["component"][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 _, 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)
}
volMount, _ := mounts.volumeMounts["component"][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.ReadOnly != hostMount.ReadOnly {
t.Errorf("Expected volume readOnly setting %t", hostMount.ReadOnly)
}
t.Run(hostMount.Name, func(t *testing.T) {
volumeName := hostMount.Name
if _, ok := mounts.volumes["component"][volumeName]; !ok {
t.Errorf("Expected to find volume %q", volumeName)
}
vol := mounts.volumes["component"][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 _, 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)
}
volMount, _ := mounts.volumeMounts["component"][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.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 {
kubeConfigFile string
clientName string
@ -136,47 +136,49 @@ func TestGetKubeConfigSpecs(t *testing.T) {
}
for _, assertion := range assertions {
// Executes getKubeConfigSpecs
specs, err := getKubeConfigSpecs(cfg)
if err != nil {
t.Fatal("getKubeConfigSpecs failed!")
}
t.Run(fmt.Sprintf("%d-%s", i, assertion.clientName), func(t *testing.T) {
// Executes getKubeConfigSpecs
specs, err := getKubeConfigSpecs(cfg)
if err != nil {
t.Fatal("getKubeConfigSpecs failed!")
}
var spec *kubeConfigSpec
var ok bool
var spec *kubeConfigSpec
var ok bool
// assert the spec for the kubeConfigFile exists
if spec, ok = specs[assertion.kubeConfigFile]; !ok {
t.Errorf("getKubeConfigSpecs didn't create spec for %s ", assertion.kubeConfigFile)
continue
}
// assert the spec for the kubeConfigFile exists
if spec, ok = specs[assertion.kubeConfigFile]; !ok {
t.Errorf("getKubeConfigSpecs didn't create spec for %s ", assertion.kubeConfigFile)
return
}
// Assert clientName
if spec.ClientName != assertion.clientName {
t.Errorf("getKubeConfigSpecs for %s clientName is %s, expected %s", assertion.kubeConfigFile, spec.ClientName, assertion.clientName)
}
// Assert clientName
if spec.ClientName != assertion.clientName {
t.Errorf("getKubeConfigSpecs for %s clientName is %s, expected %s", assertion.kubeConfigFile, spec.ClientName, assertion.clientName)
}
// Assert 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)
}
// Assert 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)
}
// Asserts InitConfiguration values injected into spec
controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
if err != nil {
t.Error(err)
}
if spec.APIServer != controlPlaneEndpoint {
t.Errorf("getKubeConfigSpecs didn't injected cfg.APIServer endpoint into spec for %s", assertion.kubeConfigFile)
}
// Asserts InitConfiguration values injected into spec
controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
if err != nil {
t.Error(err)
}
if spec.APIServer != controlPlaneEndpoint {
t.Errorf("getKubeConfigSpecs didn't injected cfg.APIServer endpoint into spec for %s", assertion.kubeConfigFile)
}
// Asserts CA certs and CA keys loaded into specs
if spec.CACert == nil {
t.Errorf("getKubeConfigSpecs didn't loaded CACert into spec for %s!", assertion.kubeConfigFile)
}
if spec.ClientCertAuth == nil || spec.ClientCertAuth.CAKey == nil {
t.Errorf("getKubeConfigSpecs didn't loaded CAKey into spec for %s!", assertion.kubeConfigFile)
}
// Asserts CA certs and CA keys loaded into specs
if spec.CACert == nil {
t.Errorf("getKubeConfigSpecs didn't loaded CACert into spec for %s!", assertion.kubeConfigFile)
}
if spec.ClientCertAuth == nil || spec.ClientCertAuth.CAKey == nil {
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")
var tests = []struct {
name string
existingKubeConfig *clientcmdapi.Config
kubeConfig *clientcmdapi.Config
expectedError bool
}{
{ // if there is no existing KubeConfig, creates the kubeconfig
name: "KubeConfig doesn't exist",
kubeConfig: config,
},
{ // 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,
kubeConfig: config,
},
{ // 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,
kubeConfig: configWithAnotherClusterCa,
expectedError: true,
},
{ // 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,
kubeConfig: configWithAnotherClusterAddress,
expectedError: true,
@ -241,44 +248,49 @@ func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
}
for _, test := range tests {
// Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
t.Run(test.name, func(t *testing.T) {
// Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
// Writes the existing kubeconfig file to disk
if test.existingKubeConfig != nil {
if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil {
// Writes the existing kubeconfig file to disk
if test.existingKubeConfig != 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")
}
}
// 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")
}
// Assert that the created file is there
testutil.AssertFileExists(t, tmpdir, "test.conf")
// Assert that the created file is there
testutil.AssertFileExists(t, tmpdir, "test.conf")
})
}
}
func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
var tests = []struct {
name string
createKubeConfigFunction func(outDir string, cfg *kubeadmapi.InitConfiguration) error
expectedFiles []string
expectedError bool
}{
{ // Test createKubeConfigFiles fails for unknown kubeconfig is requested
name: "createKubeConfigFiles",
createKubeConfigFunction: func(outDir string, cfg *kubeadmapi.InitConfiguration) error {
return createKubeConfigFiles(outDir, cfg, "unknown.conf")
},
expectedError: true,
},
{ // Test CreateInitKubeConfigFiles (wrapper to createKubeConfigFile)
name: "CreateInitKubeConfigFiles",
createKubeConfigFunction: CreateInitKubeConfigFiles,
expectedFiles: []string{
kubeadmconstants.AdminKubeConfigFileName,
@ -288,6 +300,7 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
},
},
{ // Test CreateJoinControlPlaneKubeConfigFiles (wrapper to createKubeConfigFile)
name: "CreateJoinControlPlaneKubeConfigFiles",
createKubeConfigFunction: CreateJoinControlPlaneKubeConfigFiles,
expectedFiles: []string{
kubeadmconstants.AdminKubeConfigFileName,
@ -298,39 +311,40 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
}
for _, test := range tests {
// Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
t.Run(test.name, func(t *testing.T) {
// Create temp folder for the test case
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
// Adds a pki folder with a ca certs to the temp folder
pkidir := testutil.SetupPkiDirWithCertificateAuthorithy(t, tmpdir)
// Adds a pki folder with a ca certs to the temp folder
pkidir := testutil.SetupPkiDirWithCertificateAuthorithy(t, tmpdir)
// Creates an InitConfiguration pointing to the pkidir folder
cfg := &kubeadmapi.InitConfiguration{
LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
ClusterConfiguration: kubeadmapi.ClusterConfiguration{
CertificatesDir: pkidir,
},
}
// Creates an InitConfiguration pointing to the pkidir folder
cfg := &kubeadmapi.InitConfiguration{
LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
ClusterConfiguration: kubeadmapi.ClusterConfiguration{
CertificatesDir: pkidir,
},
}
// Execs the createKubeConfigFunction
err := test.createKubeConfigFunction(tmpdir, cfg)
if test.expectedError && err == nil {
t.Errorf("createKubeConfigFunction didn't failed when expected to fail")
continue
}
if !test.expectedError && err != nil {
t.Errorf("createKubeConfigFunction failed")
continue
}
// Execs the createKubeConfigFunction
err := test.createKubeConfigFunction(tmpdir, cfg)
if test.expectedError && err == nil {
t.Errorf("createKubeConfigFunction didn't failed when expected to fail")
return
}
if !test.expectedError && err != nil {
t.Errorf("createKubeConfigFunction failed")
return
}
// Assert expected files are there
testutil.AssertFileExists(t, tmpdir, test.expectedFiles...)
// Assert expected files are there
testutil.AssertFileExists(t, tmpdir, test.expectedFiles...)
})
}
}
func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) {
// Temporary folders for the test case (without a CA)
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
@ -343,14 +357,17 @@ func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) {
}
var tests = []struct {
name string
writeKubeConfigFunction func(out io.Writer) error
}{
{ // Test WriteKubeConfigWithClientCert
{
name: "WriteKubeConfigWithClientCert",
writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"})
},
},
{ // Test WriteKubeConfigWithToken
{
name: "WriteKubeConfigWithToken",
writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithToken(out, cfg, "myUser", "12345")
},
@ -358,17 +375,18 @@ func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) {
}
for _, test := range tests {
buf := new(bytes.Buffer)
t.Run(test.name, func(t *testing.T) {
buf := new(bytes.Buffer)
// executes writeKubeConfigFunction
if err := test.writeKubeConfigFunction(buf); err == nil {
t.Error("writeKubeConfigFunction didnt failed when expected")
}
// executes writeKubeConfigFunction
if err := test.writeKubeConfigFunction(buf); err == nil {
t.Error("writeKubeConfigFunction didnt failed when expected")
}
})
}
}
func TestWriteKubeConfig(t *testing.T) {
// Temporary folders for the test case
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
@ -391,17 +409,20 @@ func TestWriteKubeConfig(t *testing.T) {
}
var tests = []struct {
name string
writeKubeConfigFunction func(out io.Writer) error
withClientCert bool
withToken bool
}{
{ // Test WriteKubeConfigWithClientCert
{
name: "WriteKubeConfigWithClientCert",
writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"})
},
withClientCert: true,
},
{ // Test WriteKubeConfigWithToken
{
name: "WriteKubeConfigWithToken",
writeKubeConfigFunction: func(out io.Writer) error {
return WriteKubeConfigWithToken(out, cfg, "myUser", "12345")
},
@ -410,33 +431,35 @@ func TestWriteKubeConfig(t *testing.T) {
}
for _, test := range tests {
buf := new(bytes.Buffer)
t.Run(test.name, func(t *testing.T) {
buf := new(bytes.Buffer)
// executes writeKubeConfigFunction
if err := test.writeKubeConfigFunction(buf); err != nil {
t.Error("writeKubeConfigFunction failed")
continue
}
// executes writeKubeConfigFunction
if err := test.writeKubeConfigFunction(buf); err != nil {
t.Error("writeKubeConfigFunction failed")
return
}
// reads kubeconfig written to stdout
config, err := clientcmd.Load(buf.Bytes())
if err != nil {
t.Errorf("Couldn't read kubeconfig file from buffer: %v", err)
continue
}
// reads kubeconfig written to stdout
config, err := clientcmd.Load(buf.Bytes())
if err != nil {
t.Errorf("Couldn't read kubeconfig file from buffer: %v", err)
return
}
// checks that CLI flags are properly propagated
kubeconfigtestutil.AssertKubeConfigCurrentCluster(t, config, "https://1.2.3.4:1234", caCert)
// checks that CLI flags are properly propagated
kubeconfigtestutil.AssertKubeConfigCurrentCluster(t, config, "https://1.2.3.4:1234", caCert)
if test.withClientCert {
// checks that kubeconfig files have expected client cert
kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithClientCert(t, config, caCert, "myUser")
}
if test.withClientCert {
// checks that kubeconfig files have expected client cert
kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithClientCert(t, config, caCert, "myUser")
}
if test.withToken {
// checks that kubeconfig files have expected token
kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithToken(t, config, "myUser", "12345")
}
if test.withToken {
// checks that kubeconfig files have expected token
kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithToken(t, config, "myUser", "12345")
}
})
}
}
@ -475,25 +498,27 @@ func TestValidateKubeConfig(t *testing.T) {
}
for name, test := range tests {
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
t.Run(name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
if test.existingKubeConfig != nil {
if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed")
if test.existingKubeConfig != nil {
if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed")
}
}
}
err := validateKubeConfig(tmpdir, "test.conf", test.kubeConfig)
if (err != nil) != test.expectedError {
t.Fatalf(dedent.Dedent(
"validateKubeConfig failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
name,
test.expectedError,
(err != nil),
err,
)
}
err := validateKubeConfig(tmpdir, "test.conf", test.kubeConfig)
if (err != nil) != test.expectedError {
t.Fatalf(dedent.Dedent(
"validateKubeConfig failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
name,
test.expectedError,
(err != nil),
err,
)
}
})
}
}
@ -581,25 +606,27 @@ func TestValidateKubeconfigsForExternalCA(t *testing.T) {
}
for name, test := range tests {
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
t.Run(name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
for name, config := range test.filesToWrite {
if err := createKubeConfigFileIfNotExists(tmpdir, name, config); err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed: %v", err)
for name, config := range test.filesToWrite {
if err := createKubeConfigFileIfNotExists(tmpdir, name, config); err != nil {
t.Errorf("createKubeConfigFileIfNotExists failed: %v", err)
}
}
}
err := ValidateKubeconfigsForExternalCA(tmpdir, test.initConfig)
if (err != nil) != test.expectedError {
t.Fatalf(dedent.Dedent(
"ValidateKubeconfigsForExternalCA failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
name,
test.expectedError,
(err != nil),
err,
)
}
err := ValidateKubeconfigsForExternalCA(tmpdir, test.initConfig)
if (err != nil) != test.expectedError {
t.Fatalf(dedent.Dedent(
"ValidateKubeconfigsForExternalCA failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
name,
test.expectedError,
(err != nil),
err,
)
}
})
}
}

View File

@ -107,69 +107,71 @@ func TestMarkControlPlane(t *testing.T) {
}
for _, tc := range tests {
hostname, err := node.GetHostname("")
if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected error: %v", tc.name, err)
}
controlPlaneNode := &v1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: hostname,
Labels: map[string]string{
v1.LabelHostname: hostname,
t.Run(tc.name, func(t *testing.T) {
hostname, err := node.GetHostname("")
if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected error: %v", tc.name, err)
}
controlPlaneNode := &v1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: 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 {
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
if tc.existingLabel != "" {
controlPlaneNode.ObjectMeta.Labels[tc.existingLabel] = ""
}
w.WriteHeader(http.StatusOK)
w.Write(jsonNode)
}))
defer s.Close()
if tc.existingTaints != nil {
controlPlaneNode.Spec.Taints = tc.existingTaints
}
cs, err := clientset.NewForConfig(&restclient.Config{Host: s.URL})
if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected error building clientset: %v", tc.name, err)
}
jsonNode, err := json.Marshal(controlPlaneNode)
if err != nil {
t.Fatalf("MarkControlPlane(%s): unexpected encoding error: %v", tc.name, err)
}
if err := MarkControlPlane(cs, hostname, tc.newTaints); err != nil {
t.Errorf("MarkControlPlane(%s) returned unexpected 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 tc.expectedPatch != patchRequest {
t.Errorf("MarkControlPlane(%s) wanted patch %v, got %v", tc.name, tc.expectedPatch, patchRequest)
}
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 {
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)
}
})
}
}