kubeadm: use t.Run in app/phases

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

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

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

View File

@ -58,6 +58,7 @@ func TestCreateServiceAccount(t *testing.T) {
}
for _, tc := range tests {
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) {
@ -70,7 +71,7 @@ func TestCreateServiceAccount(t *testing.T) {
if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
}
continue
return
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
@ -86,17 +87,18 @@ func TestCreateServiceAccount(t *testing.T) {
tc.name, action.GetVerb(), action.GetResource().Resource)
}
}
})
}
}
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,35 +136,35 @@ 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 {
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)
@ -183,16 +178,19 @@ func TestGetDNSIP(t *testing.T) {
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,6 +300,7 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
out, err := translateStubDomainOfKubeDNSToForwardCoreDNS(kubeDNSStubDomain, testCase.configMap)
if err != nil {
t.Errorf("unexpected error: %v", err)
@ -306,15 +308,18 @@ func TestTranslateStubDomainKubeDNSToCoreDNS(t *testing.T) {
if !strings.Contains(out, testCase.expectOne) && !strings.Contains(out, testCase.expectTwo) {
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,6 +360,7 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
out, err := translateUpstreamNameServerOfKubeDNSToUpstreamProxyCoreDNS(kubeDNSUpstreamNameservers, testCase.configMap)
if err != nil {
t.Errorf("unexpected error: %v", err)
@ -360,16 +368,19 @@ func TestTranslateUpstreamKubeDNSToCoreDNS(t *testing.T) {
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,6 +432,7 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
},
}
for _, testCase := range testCases {
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)
@ -426,15 +440,18 @@ func TestTranslateFederationKubeDNSToCoreDNS(t *testing.T) {
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,6 +475,7 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
},
}
for _, testCase := range testCases {
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 {
@ -465,5 +484,6 @@ func TestDeploymentsHaveSystemClusterCriticalPriorityClassName(t *testing.T) {
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,6 +62,7 @@ func TestCreateServiceAccount(t *testing.T) {
}
for _, tc := range tests {
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) {
@ -74,7 +75,7 @@ func TestCreateServiceAccount(t *testing.T) {
if err == nil {
t.Errorf("CreateServiceAccounts(%s) wanted err, got nil", tc.name)
}
continue
return
} else if !tc.expectErr && err != nil {
t.Errorf("CreateServiceAccounts(%s) returned unexpected err: %v", tc.name, err)
}
@ -90,17 +91,19 @@ func TestCreateServiceAccount(t *testing.T) {
tc.name, action.GetVerb(), action.GetResource().Resource)
}
}
})
}
}
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,7 +172,7 @@ func TestEnsureProxyAddon(t *testing.T) {
}
for _, tc := range testCases {
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
@ -207,7 +206,7 @@ func TestEnsureProxyAddon(t *testing.T) {
intControlPlane, err := configutil.DefaultedInitConfiguration(controlPlaneConfig)
if err != nil {
t.Errorf("test failed to convert external to internal version")
break
return
}
intControlPlane.ComponentConfigs.KubeProxy = &kubeproxyconfig.KubeProxyConfiguration{
BindAddress: "",
@ -224,7 +223,7 @@ func TestEnsureProxyAddon(t *testing.T) {
// 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
return
}
err = EnsureProxyAddon(&intControlPlane.ClusterConfiguration, &intControlPlane.LocalAPIEndpoint, client)
@ -256,15 +255,18 @@ func TestEnsureProxyAddon(t *testing.T) {
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,6 +276,7 @@ func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
},
}
for _, testCase := range testCases {
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 {
@ -282,5 +285,6 @@ func TestDaemonSetsHaveSystemNodeCriticalPriorityClassName(t *testing.T) {
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,6 +95,7 @@ func TestCreateBootstrapConfigMapIfNotExists(t *testing.T) {
}
for _, tc := range tests {
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) {
@ -108,6 +109,7 @@ func TestCreateBootstrapConfigMapIfNotExists(t *testing.T) {
} else if !tc.expectErr && err != nil {
t.Errorf("CreateBootstrapConfigMapIfNotExists(%s) returned unexpected error: %v", tc.name, err)
}
})
}
}
}

View File

@ -55,57 +55,67 @@ func TestGetStaticPodSpecs(t *testing.T) {
specs := GetStaticPodSpecs(cfg, &kubeadmapi.APIEndpoint{}, k8sVersion)
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[assertion.staticPodName]; ok {
if spec, ok := specs[tc.staticPodName]; ok {
// 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)
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)
}
} else {
t.Errorf("getStaticPodSpecs didn't create spec for %s ", assertion.staticPodName)
t.Errorf("getStaticPodSpecs didn't create spec for %s ", tc.staticPodName)
}
})
}
}
func TestCreateStaticPodFilesAndWrappers(t *testing.T) {
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)
@ -120,7 +130,7 @@ func TestCreateStaticPodFilesAndWrappers(t *testing.T) {
err := CreateStaticPodFiles(manifestPath, cfg, &kubeadmapi.APIEndpoint{}, test.components...)
if err != nil {
t.Errorf("Error executing createStaticPodFunction: %v", err)
continue
return
}
// Assert expected files are there
@ -129,6 +139,7 @@ func TestCreateStaticPodFilesAndWrappers(t *testing.T) {
for _, fileName := range test.components {
testutil.AssertFileExists(t, manifestPath, fileName+".yaml")
}
})
}
}
@ -626,12 +637,14 @@ func TestGetControllerManagerCommand(t *testing.T) {
}
for _, rt := range tests {
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 {
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,6 +794,7 @@ func TestGetControllerManagerCommandExternalCA(t *testing.T) {
}
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)
@ -806,6 +821,7 @@ func TestGetControllerManagerCommandExternalCA(t *testing.T) {
if !reflect.DeepEqual(actual, expected) {
errorDiffArguments(t, test.name, actual, expected)
}
})
}
}
@ -828,12 +844,14 @@ func TestGetSchedulerCommand(t *testing.T) {
}
for _, rt := range tests {
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
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,6 +233,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
}
for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
actualVol, actualVolMount := getEtcdCertVolumes(&kubeadmapi.ExternalEtcd{
CAFile: rt.ca,
CertFile: rt.cert,
@ -252,6 +253,7 @@ func TestGetEtcdCertVolumes(t *testing.T) {
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,6 +517,7 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
defer func() { caCertsExtraVolumePaths = []string{"/etc/pki", "/usr/share/ca-certificates"} }()
for _, rt := range tests {
t.Run(rt.name, func(t *testing.T) {
mounts := getHostPathVolumesForTheControlPlane(rt.cfg)
// Avoid unit test errors when the flexvolume is mounted
@ -537,6 +541,7 @@ func TestGetHostPathVolumesForTheControlPlane(t *testing.T) {
mounts.volumeMounts,
)
}
})
}
}
@ -609,6 +614,7 @@ func TestAddExtraHostPathMounts(t *testing.T) {
}
mounts.AddExtraHostPathMounts("component", hostPathMounts)
for _, hostMount := range hostPathMounts {
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)
@ -636,5 +642,6 @@ func TestAddExtraHostPathMounts(t *testing.T) {
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,6 +136,7 @@ func TestGetKubeConfigSpecs(t *testing.T) {
}
for _, assertion := range assertions {
t.Run(fmt.Sprintf("%d-%s", i, assertion.clientName), func(t *testing.T) {
// Executes getKubeConfigSpecs
specs, err := getKubeConfigSpecs(cfg)
if err != nil {
@ -148,7 +149,7 @@ func TestGetKubeConfigSpecs(t *testing.T) {
// 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
return
}
// Assert clientName
@ -177,6 +178,7 @@ func TestGetKubeConfigSpecs(t *testing.T) {
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,6 +248,7 @@ func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
}
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)
@ -263,22 +271,26 @@ func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
// 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,6 +311,7 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
}
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)
@ -317,20 +331,20 @@ func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
err := test.createKubeConfigFunction(tmpdir, cfg)
if test.expectedError && err == nil {
t.Errorf("createKubeConfigFunction didn't failed when expected to fail")
continue
return
}
if !test.expectedError && err != nil {
t.Errorf("createKubeConfigFunction failed")
continue
return
}
// 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 {
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")
}
})
}
}
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,19 +431,20 @@ func TestWriteKubeConfig(t *testing.T) {
}
for _, test := range tests {
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
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
return
}
// checks that CLI flags are properly propagated
@ -437,6 +459,7 @@ func TestWriteKubeConfig(t *testing.T) {
// checks that kubeconfig files have expected token
kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithToken(t, config, "myUser", "12345")
}
})
}
}
@ -475,6 +498,7 @@ func TestValidateKubeConfig(t *testing.T) {
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
@ -494,6 +518,7 @@ func TestValidateKubeConfig(t *testing.T) {
err,
)
}
})
}
}
@ -581,6 +606,7 @@ func TestValidateKubeconfigsForExternalCA(t *testing.T) {
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
tmpdir := testutil.SetupTempDir(t)
defer os.RemoveAll(tmpdir)
@ -600,6 +626,7 @@ func TestValidateKubeconfigsForExternalCA(t *testing.T) {
err,
)
}
})
}
}

View File

@ -107,6 +107,7 @@ func TestMarkControlPlane(t *testing.T) {
}
for _, tc := range tests {
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)
@ -170,6 +171,7 @@ func TestMarkControlPlane(t *testing.T) {
if tc.expectedPatch != patchRequest {
t.Errorf("MarkControlPlane(%s) wanted patch %v, got %v", tc.name, tc.expectedPatch, patchRequest)
}
})
}
}