From bae074ef3884a665bc034d7cb7a552f6d59da7fc Mon Sep 17 00:00:00 2001 From: Guoliang Wang Date: Sat, 12 May 2018 17:24:28 +0800 Subject: [PATCH] use subtest for table units (pkg/kubectl) --- pkg/kubectl/autoscale_test.go | 48 +- pkg/kubectl/clusterrolebinding_test.go | 30 +- .../cmd/config/create_authinfo_test.go | 82 ++-- pkg/kubectl/configmap_test.go | 55 ++- pkg/kubectl/deployment_test.go | 36 +- pkg/kubectl/env_file_test.go | 34 +- pkg/kubectl/explain/explain_test.go | 24 +- pkg/kubectl/explain/field_lookup_test.go | 36 +- pkg/kubectl/explain/typename_test.go | 26 +- pkg/kubectl/generate_test.go | 150 ++++-- .../resource/builder_test.go | 190 +++++--- .../genericclioptions/resource/helper_test.go | 330 +++++++------ .../resource/visitor_test.go | 195 +++++--- pkg/kubectl/namespace_test.go | 44 +- pkg/kubectl/pdb_test.go | 150 +++--- pkg/kubectl/plugins/env_test.go | 76 ++- pkg/kubectl/plugins/plugins_test.go | 22 +- pkg/kubectl/plugins/runner_test.go | 47 +- pkg/kubectl/priorityclass_test.go | 36 +- pkg/kubectl/proxy/proxy_server_test.go | 144 +++--- pkg/kubectl/quota_test.go | 42 +- pkg/kubectl/rolebinding_test.go | 57 ++- pkg/kubectl/rolling_updater_test.go | 451 +++++++++--------- pkg/kubectl/rollout_status_test.go | 181 +++---- pkg/kubectl/run_test.go | 235 +++++---- .../secret_for_docker_registry_test.go | 39 +- pkg/kubectl/secret_for_tls_test.go | 42 +- pkg/kubectl/secret_test.go | 54 ++- pkg/kubectl/service_test.go | 38 +- pkg/kubectl/serviceaccount_test.go | 30 +- pkg/kubectl/sorter_test.go | 34 +- pkg/kubectl/util/service_port_test.go | 76 +-- pkg/kubectl/util/util_test.go | 88 ++-- pkg/kubectl/validation/schema_test.go | 20 +- 34 files changed, 1841 insertions(+), 1301 deletions(-) diff --git a/pkg/kubectl/autoscale_test.go b/pkg/kubectl/autoscale_test.go index 918ee83547..fc851e3375 100644 --- a/pkg/kubectl/autoscale_test.go +++ b/pkg/kubectl/autoscale_test.go @@ -101,28 +101,30 @@ func TestHPAGenerate(t *testing.T) { }, } - for _, test := range tests { - generator := HorizontalPodAutoscalerGeneratorV1{ - Name: test.HPAName, - ScaleRefKind: test.scaleRefKind, - ScaleRefName: test.scaleRefName, - ScaleRefApiVersion: test.scaleRefApiVersion, - MinReplicas: test.minReplicas, - MaxReplicas: test.maxReplicas, - CPUPercent: test.CPUPercent, - } - obj, err := generator.StructuredGenerate() - if test.expectErr && err != nil { - continue - } - if !test.expectErr && err != nil { - t.Errorf("[%s] unexpected error: %v", test.name, err) - } - if test.expectErr && err == nil { - t.Errorf("[%s] expect error, got nil", test.name) - } - if !reflect.DeepEqual(obj.(*autoscalingv1.HorizontalPodAutoscaler), test.expected) { - t.Errorf("[%s] want:\n%#v\ngot:\n%#v", test.name, test.expected, obj.(*autoscalingv1.HorizontalPodAutoscaler)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + generator := HorizontalPodAutoscalerGeneratorV1{ + Name: tt.HPAName, + ScaleRefKind: tt.scaleRefKind, + ScaleRefName: tt.scaleRefName, + ScaleRefApiVersion: tt.scaleRefApiVersion, + MinReplicas: tt.minReplicas, + MaxReplicas: tt.maxReplicas, + CPUPercent: tt.CPUPercent, + } + obj, err := generator.StructuredGenerate() + if tt.expectErr && err != nil { + return + } + if !tt.expectErr && err != nil { + t.Errorf("[%s] unexpected error: %v", tt.name, err) + } + if tt.expectErr && err == nil { + t.Errorf("[%s] expect error, got nil", tt.name) + } + if !reflect.DeepEqual(obj.(*autoscalingv1.HorizontalPodAutoscaler), tt.expected) { + t.Errorf("[%s] want:\n%#v\ngot:\n%#v", tt.name, tt.expected, obj.(*autoscalingv1.HorizontalPodAutoscaler)) + } + }) } } diff --git a/pkg/kubectl/clusterrolebinding_test.go b/pkg/kubectl/clusterrolebinding_test.go index f1846a2678..1ab1af351a 100644 --- a/pkg/kubectl/clusterrolebinding_test.go +++ b/pkg/kubectl/clusterrolebinding_test.go @@ -211,19 +211,21 @@ func TestClusterRoleBindingGenerate(t *testing.T) { }, } generator := ClusterRoleBindingGeneratorV1{} - for i := range tests { - obj, err := generator.Generate(tests[i].params) - if !tests[i].expectErr && err != nil { - t.Errorf("[%d] unexpected error: %v", i, err) - } - if tests[i].expectErr && err != nil { - continue - } - if tests[i].expectErr && err == nil { - t.Errorf("[%s] expect error, got nil", tests[i].name) - } - if !reflect.DeepEqual(obj.(*rbacv1beta1.ClusterRoleBinding), tests[i].expected) { - t.Errorf("\n[%s] want:\n%#v\ngot:\n%#v", tests[i].name, tests[i].expected, obj.(*rbacv1beta1.ClusterRoleBinding)) - } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("[%d] unexpected error: %v", i, err) + } + if tt.expectErr && err != nil { + return + } + if tt.expectErr && err == nil { + t.Errorf("[%s] expect error, got nil", tt.name) + } + if !reflect.DeepEqual(obj.(*rbacv1beta1.ClusterRoleBinding), tt.expected) { + t.Errorf("\n[%s] want:\n%#v\ngot:\n%#v", tt.name, tt.expected, obj.(*rbacv1beta1.ClusterRoleBinding)) + } + }) } } diff --git a/pkg/kubectl/cmd/config/create_authinfo_test.go b/pkg/kubectl/cmd/config/create_authinfo_test.go index 2b7fd1edda..2de35e72c5 100644 --- a/pkg/kubectl/cmd/config/create_authinfo_test.go +++ b/pkg/kubectl/cmd/config/create_authinfo_test.go @@ -36,6 +36,7 @@ func stringFlagFor(s string) flag.StringFlag { func TestCreateAuthInfoOptions(t *testing.T) { tests := []struct { + name string flags []string wantParseErr bool wantCompleteErr bool @@ -44,6 +45,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { wantOptions *createAuthInfoOptions }{ { + name: "test1", flags: []string{ "me", }, @@ -52,6 +54,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { }, }, { + name: "test2", flags: []string{ "me", "--token=foo", @@ -62,6 +65,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { }, }, { + name: "test3", flags: []string{ "me", "--username=jane", @@ -74,6 +78,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { }, }, { + name: "test4", // Cannot provide both token and basic auth. flags: []string{ "me", @@ -84,6 +89,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { wantValidateErr: true, }, { + name: "test5", flags: []string{ "--auth-provider=oidc", "--auth-provider-arg=client-id=foo", @@ -101,6 +107,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { }, }, { + name: "test6", flags: []string{ "--auth-provider=oidc", "--auth-provider-arg=client-id-", @@ -118,6 +125,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { }, }, { + name: "test7", flags: []string{ "--auth-provider-arg=client-id-", // auth provider name not required "--auth-provider-arg=client-secret-", @@ -133,6 +141,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { }, }, { + name: "test8", flags: []string{ "--auth-provider=oidc", "--auth-provider-arg=client-id", // values must be of form 'key=value' or 'key-' @@ -141,6 +150,7 @@ func TestCreateAuthInfoOptions(t *testing.T) { wantCompleteErr: true, }, { + name: "test9", flags: []string{ // No name for authinfo provided. }, @@ -148,48 +158,50 @@ func TestCreateAuthInfoOptions(t *testing.T) { }, } - for i, test := range tests { - buff := new(bytes.Buffer) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + buff := new(bytes.Buffer) - opts := new(createAuthInfoOptions) - cmd := newCmdConfigSetAuthInfo(buff, opts) - if err := cmd.ParseFlags(test.flags); err != nil { - if !test.wantParseErr { - t.Errorf("case %d: parsing error for flags %q: %v: %s", i, test.flags, err, buff) + opts := new(createAuthInfoOptions) + cmd := newCmdConfigSetAuthInfo(buff, opts) + if err := cmd.ParseFlags(tt.flags); err != nil { + if !tt.wantParseErr { + t.Errorf("case %s: parsing error for flags %q: %v: %s", tt.name, tt.flags, err, buff) + } + return } - continue - } - if test.wantParseErr { - t.Errorf("case %d: expected parsing error for flags %q: %s", i, test.flags, buff) - continue - } - - if err := opts.complete(cmd, buff); err != nil { - if !test.wantCompleteErr { - t.Errorf("case %d: complete() error for flags %q: %s", i, test.flags, buff) + if tt.wantParseErr { + t.Errorf("case %s: expected parsing error for flags %q: %s", tt.name, tt.flags, buff) + return } - continue - } - if test.wantCompleteErr { - t.Errorf("case %d: complete() expected errors for flags %q: %s", i, test.flags, buff) - continue - } - if err := opts.validate(); err != nil { - if !test.wantValidateErr { - t.Errorf("case %d: flags %q: validate failed: %v", i, test.flags, err) + if err := opts.complete(cmd, buff); err != nil { + if !tt.wantCompleteErr { + t.Errorf("case %s: complete() error for flags %q: %s", tt.name, tt.flags, buff) + } + return + } + if tt.wantCompleteErr { + t.Errorf("case %s: complete() expected errors for flags %q: %s", tt.name, tt.flags, buff) + return } - continue - } - if test.wantValidateErr { - t.Errorf("case %d: flags %q: expected validate to fail", i, test.flags) - continue - } + if err := opts.validate(); err != nil { + if !tt.wantValidateErr { + t.Errorf("case %s: flags %q: validate failed: %v", tt.name, tt.flags, err) + } + return + } - if !reflect.DeepEqual(opts, test.wantOptions) { - t.Errorf("case %d: flags %q: mis-matched options,\nwanted=%#v\ngot= %#v", i, test.flags, test.wantOptions, opts) - } + if tt.wantValidateErr { + t.Errorf("case %s: flags %q: expected validate to fail", tt.name, tt.flags) + return + } + + if !reflect.DeepEqual(opts, tt.wantOptions) { + t.Errorf("case %s: flags %q: mis-matched options,\nwanted=%#v\ngot= %#v", tt.name, tt.flags, tt.wantOptions, opts) + } + }) } } diff --git a/pkg/kubectl/configmap_test.go b/pkg/kubectl/configmap_test.go index 594607cfce..820b5867c9 100644 --- a/pkg/kubectl/configmap_test.go +++ b/pkg/kubectl/configmap_test.go @@ -28,12 +28,14 @@ import ( func TestConfigMapGenerate(t *testing.T) { tests := []struct { + name string setup func(t *testing.T, params map[string]interface{}) func() params map[string]interface{} expected *v1.ConfigMap expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "name": "foo", }, @@ -47,6 +49,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test2", params: map[string]interface{}{ "name": "foo", "append-hash": true, @@ -61,6 +64,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test3", params: map[string]interface{}{ "name": "foo", "type": "my-type", @@ -75,6 +79,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test4", params: map[string]interface{}{ "name": "foo", "type": "my-type", @@ -90,6 +95,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test5", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1=value1", "key2=value2"}, @@ -107,6 +113,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test6", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1=value1", "key2=value2"}, @@ -125,6 +132,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test7", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1value1"}, @@ -132,6 +140,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: true, }, { + name: "test8", params: map[string]interface{}{ "name": "foo", "from-file": []string{"key1=/file=2"}, @@ -139,6 +148,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: true, }, { + name: "test9", params: map[string]interface{}{ "name": "foo", "from-file": []string{"key1==value"}, @@ -146,6 +156,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: true, }, { + name: "test10", setup: setupBinaryFile([]byte{0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64}), params: map[string]interface{}{ "name": "foo", @@ -161,6 +172,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test11", setup: setupBinaryFile([]byte{0xff, 0xfd}), params: map[string]interface{}{ "name": "foo", @@ -176,6 +188,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test12", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1==value1"}, @@ -192,6 +205,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test13", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1==value1"}, @@ -209,6 +223,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test14", setup: setupEnvFile("key1=value1", "#", "", "key2=value2"), params: map[string]interface{}{ "name": "valid_env", @@ -227,6 +242,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test15", setup: setupEnvFile("key1=value1", "#", "", "key2=value2"), params: map[string]interface{}{ "name": "valid_env", @@ -246,6 +262,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test16", setup: func() func(t *testing.T, params map[string]interface{}) func() { os.Setenv("g_key1", "1") os.Setenv("g_key2", "2") @@ -268,6 +285,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test17", setup: func() func(t *testing.T, params map[string]interface{}) func() { os.Setenv("g_key1", "1") os.Setenv("g_key2", "2") @@ -291,6 +309,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test18", params: map[string]interface{}{ "name": "too_many_args", "from-literal": []string{"key1=value1"}, @@ -298,7 +317,7 @@ func TestConfigMapGenerate(t *testing.T) { }, expectErr: true, }, - { + {name: "test19", setup: setupEnvFile("key#1=value1"), params: map[string]interface{}{ "name": "invalid_key", @@ -307,6 +326,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: true, }, { + name: "test20", setup: setupEnvFile(" key1= value1"), params: map[string]interface{}{ "name": "with_spaces", @@ -324,6 +344,7 @@ func TestConfigMapGenerate(t *testing.T) { expectErr: false, }, { + name: "test21", setup: setupEnvFile(" key1= value1"), params: map[string]interface{}{ "name": "with_spaces", @@ -343,22 +364,24 @@ func TestConfigMapGenerate(t *testing.T) { }, } generator := ConfigMapGeneratorV1{} - for i, test := range tests { - if test.setup != nil { - if teardown := test.setup(t, test.params); teardown != nil { - defer teardown() + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.setup != nil { + if teardown := tt.setup(t, tt.params); teardown != nil { + defer teardown() + } } - } - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("case %d, unexpected error: %v", i, err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.ConfigMap), test.expected) { - t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, test.expected, obj.(*v1.ConfigMap)) - } + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("case %d, unexpected error: %v", i, err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.ConfigMap), tt.expected) { + t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, tt.expected, obj.(*v1.ConfigMap)) + } + }) } } diff --git a/pkg/kubectl/deployment_test.go b/pkg/kubectl/deployment_test.go index 5388e6cd8d..58753ca287 100644 --- a/pkg/kubectl/deployment_test.go +++ b/pkg/kubectl/deployment_test.go @@ -82,22 +82,24 @@ func TestDeploymentBasicGenerate(t *testing.T) { expectErr: true, }, } - for _, test := range tests { - generator := &DeploymentBasicAppsGeneratorV1{ - BaseDeploymentGenerator{ - Name: test.deploymentName, - Images: test.images, - }, - } - obj, err := generator.StructuredGenerate() - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*appsv1.Deployment), test.expected) { - t.Errorf("test: %v\nexpected:\n%#v\nsaw:\n%#v", test.name, test.expected, obj.(*appsv1.Deployment)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + generator := &DeploymentBasicAppsGeneratorV1{ + BaseDeploymentGenerator{ + Name: tt.deploymentName, + Images: tt.images, + }, + } + obj, err := generator.StructuredGenerate() + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*appsv1.Deployment), tt.expected) { + t.Errorf("test: %v\nexpected:\n%#v\nsaw:\n%#v", tt.name, tt.expected, obj.(*appsv1.Deployment)) + } + }) } } diff --git a/pkg/kubectl/env_file_test.go b/pkg/kubectl/env_file_test.go index 10e37238de..9adf2749b4 100644 --- a/pkg/kubectl/env_file_test.go +++ b/pkg/kubectl/env_file_test.go @@ -48,24 +48,26 @@ func Test_processEnvFileLine(t *testing.T) { {"key is returned even with no value", []byte{' ', 'x', '='}, 0, "x", "", ""}, } - for _, c := range testCases { - key, value, err := proccessEnvFileLine(c.line, `filename`, c.currentLine) - t.Logf("Testing that %s.", c.name) - if c.expectedKey != key { - t.Errorf("\texpected key %q, received %q", c.expectedKey, key) - } - if c.expectedValue != value { - t.Errorf("\texpected value %q, received %q", c.expectedValue, value) - } - if len(c.expectedErr) == 0 { - if err != nil { - t.Errorf("\tunexpected err %v", err) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + key, value, err := proccessEnvFileLine(tt.line, `filename`, tt.currentLine) + t.Logf("Testing that %s.", tt.name) + if tt.expectedKey != key { + t.Errorf("\texpected key %q, received %q", tt.expectedKey, key) } - } else { - if !strings.Contains(err.Error(), c.expectedErr) { - t.Errorf("\terr %v doesn't match expected %q", err, c.expectedErr) + if tt.expectedValue != value { + t.Errorf("\texpected value %q, received %q", tt.expectedValue, value) } - } + if len(tt.expectedErr) == 0 { + if err != nil { + t.Errorf("\tunexpected err %v", err) + } + } else { + if !strings.Contains(err.Error(), tt.expectedErr) { + t.Errorf("\terr %v doesn't match expected %q", err, tt.expectedErr) + } + } + }) } } diff --git a/pkg/kubectl/explain/explain_test.go b/pkg/kubectl/explain/explain_test.go index 2c8c358884..b258674990 100644 --- a/pkg/kubectl/explain/explain_test.go +++ b/pkg/kubectl/explain/explain_test.go @@ -58,18 +58,20 @@ func TestSplitAndParseResourceRequest(t *testing.T) { } mapper := testrestmapper.TestOnlyStaticRESTMapper(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...) - for _, test := range tests { - gotInResource, gotFieldsPath, err := SplitAndParseResourceRequest(test.inresource, mapper) - if err != nil { - t.Errorf("unexpected error: %v", err) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotInResource, gotFieldsPath, err := SplitAndParseResourceRequest(tt.inresource, mapper) + if err != nil { + t.Errorf("unexpected error: %v", err) + } - if !reflect.DeepEqual(test.expectedInResource, gotInResource) && !test.expectedErr { - t.Errorf("%s: expected inresource: %s, got: %s", test.name, test.expectedInResource, gotInResource) - } + if !reflect.DeepEqual(tt.expectedInResource, gotInResource) && !tt.expectedErr { + t.Errorf("%s: expected inresource: %s, got: %s", tt.name, tt.expectedInResource, gotInResource) + } - if !reflect.DeepEqual(test.expectedFieldsPath, gotFieldsPath) && !test.expectedErr { - t.Errorf("%s: expected fieldsPath: %s, got: %s", test.name, test.expectedFieldsPath, gotFieldsPath) - } + if !reflect.DeepEqual(tt.expectedFieldsPath, gotFieldsPath) && !tt.expectedErr { + t.Errorf("%s: expected fieldsPath: %s, got: %s", tt.name, tt.expectedFieldsPath, gotFieldsPath) + } + }) } } diff --git a/pkg/kubectl/explain/field_lookup_test.go b/pkg/kubectl/explain/field_lookup_test.go index a2b99212b4..be23a7df0a 100644 --- a/pkg/kubectl/explain/field_lookup_test.go +++ b/pkg/kubectl/explain/field_lookup_test.go @@ -33,49 +33,57 @@ func TestFindField(t *testing.T) { } tests := []struct { + name string path []string err string expectedPath string }{ { + name: "test1", path: []string{}, expectedPath: "OneKind", }, { + name: "test2", path: []string{"field1"}, expectedPath: "OneKind.field1", }, { + name: "test3", path: []string{"field1", "array"}, expectedPath: "OtherKind.array", }, { + name: "test4", path: []string{"field1", "what?"}, err: `field "what?" does not exist`, }, { + name: "test5", path: []string{"field1", ""}, err: `field "" does not exist`, }, } - for _, test := range tests { - path, err := LookupSchemaForField(schema, test.path) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path, err := LookupSchemaForField(schema, tt.path) - gotErr := "" - if err != nil { - gotErr = err.Error() - } + gotErr := "" + if err != nil { + gotErr = err.Error() + } - gotPath := "" - if path != nil { - gotPath = path.GetPath().String() - } + gotPath := "" + if path != nil { + gotPath = path.GetPath().String() + } - if gotErr != test.err || gotPath != test.expectedPath { - t.Errorf("LookupSchemaForField(schema, %v) = (path: %q, err: %q), expected (path: %q, err: %q)", - test.path, gotPath, gotErr, test.expectedPath, test.err) - } + if gotErr != tt.err || gotPath != tt.expectedPath { + t.Errorf("LookupSchemaForField(schema, %v) = (path: %q, err: %q), expected (path: %q, err: %q)", + tt.path, gotPath, gotErr, tt.expectedPath, tt.err) + } + }) } } diff --git a/pkg/kubectl/explain/typename_test.go b/pkg/kubectl/explain/typename_test.go index aa3e5a2abe..72cd7a2983 100644 --- a/pkg/kubectl/explain/typename_test.go +++ b/pkg/kubectl/explain/typename_test.go @@ -36,45 +36,53 @@ func TestReferenceTypename(t *testing.T) { } tests := []struct { + name string path []string expected string }{ { // Kind is "Object" + name: "test1", path: []string{}, expected: "Object", }, { // Reference is equal to pointed type "Object" + name: "test2", path: []string{"field1"}, expected: "Object", }, { // Reference is equal to pointed type "string" + name: "test3", path: []string{"field1", "primitive"}, expected: "string", }, { // Array of object of reference to string + name: "test4", path: []string{"field2"}, expected: "[]map[string]string", }, { // Array of integer + name: "test5", path: []string{"field1", "array"}, expected: "[]integer", }, } - for _, test := range tests { - s, err := LookupSchemaForField(schema, test.path) - if err != nil { - t.Fatalf("Invalid test.path %v: %v", test.path, err) - } - got := GetTypeName(s) - if got != test.expected { - t.Errorf("Got %q, expected %q", got, test.expected) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s, err := LookupSchemaForField(schema, tt.path) + if err != nil { + t.Fatalf("Invalid tt.path %v: %v", tt.path, err) + } + got := GetTypeName(s) + if got != tt.expected { + t.Errorf("Got %q, expected %q", got, tt.expected) + } + }) } } diff --git a/pkg/kubectl/generate_test.go b/pkg/kubectl/generate_test.go index b94f806ea1..6bb174add1 100644 --- a/pkg/kubectl/generate_test.go +++ b/pkg/kubectl/generate_test.go @@ -29,38 +29,72 @@ type TestStruct struct { func TestIsZero(t *testing.T) { tests := []struct { + name string val interface{} expectZero bool }{ - {"", true}, - {nil, true}, - {0, true}, - {TestStruct{}, true}, - {"foo", false}, - {1, false}, - {TestStruct{val: 2}, false}, + { + name: "test1", + val: "", + expectZero: true, + }, + { + name: "test2", + val: nil, + expectZero: true, + }, + { + name: "test3", + val: 0, + expectZero: true, + }, + { + name: "test4", + val: TestStruct{}, + expectZero: true, + }, + { + name: "test5", + val: "foo", + expectZero: false, + }, + { + name: "test6", + val: 1, + expectZero: false, + }, + { + name: "test7", + val: TestStruct{val: 2}, + expectZero: false, + }, } - for _, test := range tests { - output := IsZero(test.val) - if output != test.expectZero { - t.Errorf("expected: %v, saw %v", test.expectZero, output) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + output := IsZero(tt.val) + if output != tt.expectZero { + t.Errorf("expected: %v, saw %v", tt.expectZero, output) + } + }) } } func TestValidateParams(t *testing.T) { tests := []struct { + name string paramSpec []GeneratorParam params map[string]interface{} valid bool }{ { + name: "test1", paramSpec: []GeneratorParam{}, params: map[string]interface{}{}, valid: true, }, { + name: "test2", paramSpec: []GeneratorParam{ {Name: "foo"}, }, @@ -68,6 +102,7 @@ func TestValidateParams(t *testing.T) { valid: true, }, { + name: "test3", paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, }, @@ -77,6 +112,7 @@ func TestValidateParams(t *testing.T) { valid: true, }, { + name: "test4", paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, }, @@ -87,6 +123,7 @@ func TestValidateParams(t *testing.T) { valid: true, }, { + name: "test5", paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, {Name: "baz", Required: true}, @@ -98,6 +135,7 @@ func TestValidateParams(t *testing.T) { valid: true, }, { + name: "test6", paramSpec: []GeneratorParam{ {Name: "foo", Required: true}, {Name: "baz", Required: true}, @@ -108,14 +146,16 @@ func TestValidateParams(t *testing.T) { valid: false, }, } - for _, test := range tests { - err := ValidateParams(test.paramSpec, test.params) - if test.valid && err != nil { - t.Errorf("unexpected error: %v", err) - } - if !test.valid && err == nil { - t.Errorf("unexpected non-error") - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ValidateParams(tt.paramSpec, tt.params) + if tt.valid && err != nil { + t.Errorf("unexpected error: %v", err) + } + if !tt.valid && err == nil { + t.Errorf("unexpected non-error") + } + }) } } @@ -209,26 +249,30 @@ func TestGetBool(t *testing.T) { expectError: true, }, } - for _, test := range testCases { - got, err := GetBool(test.parameters, test.key, test.defaultValue) - if err != nil && test.expectError == false { - t.Errorf("%s: unexpected error: %v", test.name, err) - } - if err == nil && test.expectError == true { - t.Errorf("%s: expect error, got nil", test.name) - } - if got != test.expected { - t.Errorf("%s: expect %v, got %v", test.name, test.expected, got) - } + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + got, err := GetBool(tt.parameters, tt.key, tt.defaultValue) + if err != nil && tt.expectError == false { + t.Errorf("%s: unexpected error: %v", tt.name, err) + } + if err == nil && tt.expectError == true { + t.Errorf("%s: expect error, got nil", tt.name) + } + if got != tt.expected { + t.Errorf("%s: expect %v, got %v", tt.name, tt.expected, got) + } + }) } } func TestMakeParseLabels(t *testing.T) { successCases := []struct { + name string labels map[string]string expected map[string]string }{ { + name: "test1", labels: map[string]string{ "foo": "false", }, @@ -237,6 +281,7 @@ func TestMakeParseLabels(t *testing.T) { }, }, { + name: "test2", labels: map[string]string{ "foo": "true", "bar": "123", @@ -247,15 +292,17 @@ func TestMakeParseLabels(t *testing.T) { }, }, } - for _, test := range successCases { - labelString := MakeLabels(test.labels) - got, err := ParseLabels(labelString) - if err != nil { - t.Errorf("unexpected error :%v", err) - } - if !reflect.DeepEqual(test.expected, got) { - t.Errorf("\nexpected:\n%v\ngot:\n%v", test.expected, got) - } + for _, tt := range successCases { + t.Run(tt.name, func(t *testing.T) { + labelString := MakeLabels(tt.labels) + got, err := ParseLabels(labelString) + if err != nil { + t.Errorf("unexpected error :%v", err) + } + if !reflect.DeepEqual(tt.expected, got) { + t.Errorf("\nexpected:\n%v\ngot:\n%v", tt.expected, got) + } + }) } errorCases := []struct { @@ -301,10 +348,12 @@ func TestMakeParseLabels(t *testing.T) { func TestMakeParseProtocols(t *testing.T) { successCases := []struct { + name string protocols map[string]string expected map[string]string }{ { + name: "test1", protocols: map[string]string{ "101": "TCP", }, @@ -313,6 +362,7 @@ func TestMakeParseProtocols(t *testing.T) { }, }, { + name: "test2", protocols: map[string]string{ "102": "UDP", "101": "TCP", @@ -323,15 +373,17 @@ func TestMakeParseProtocols(t *testing.T) { }, }, } - for _, test := range successCases { - protocolString := MakeProtocols(test.protocols) - got, err := ParseProtocols(protocolString) - if err != nil { - t.Errorf("unexpected error :%v", err) - } - if !reflect.DeepEqual(test.expected, got) { - t.Errorf("\nexpected:\n%v\ngot:\n%v", test.expected, got) - } + for _, tt := range successCases { + t.Run(tt.name, func(t *testing.T) { + protocolString := MakeProtocols(tt.protocols) + got, err := ParseProtocols(protocolString) + if err != nil { + t.Errorf("unexpected error :%v", err) + } + if !reflect.DeepEqual(tt.expected, got) { + t.Errorf("\nexpected:\n%v\ngot:\n%v", tt.expected, got) + } + }) } errorCases := []struct { diff --git a/pkg/kubectl/genericclioptions/resource/builder_test.go b/pkg/kubectl/genericclioptions/resource/builder_test.go index e6308a5668..9a30f7ea00 100644 --- a/pkg/kubectl/genericclioptions/resource/builder_test.go +++ b/pkg/kubectl/genericclioptions/resource/builder_test.go @@ -378,33 +378,35 @@ func TestPathBuilderWithMultiple(t *testing.T) { {"hardlink", &v1.Pod{}, true, fmt.Sprintf("%s/inode/hardlink/busybox-link.json", tmpDir), []string{"busybox0"}}, } - for _, test := range tests { - b := newDefaultBuilder(). - FilenameParam(false, &FilenameOptions{Recursive: test.recursive, Filenames: []string{test.directory}}). - NamespaceParam("test").DefaultNamespace() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + b := newDefaultBuilder(). + FilenameParam(false, &FilenameOptions{Recursive: tt.recursive, Filenames: []string{tt.directory}}). + NamespaceParam("test").DefaultNamespace() - testVisitor := &testVisitor{} - singleItemImplied := false + testVisitor := &testVisitor{} + singleItemImplied := false - err := b.Do().IntoSingleItemImplied(&singleItemImplied).Visit(testVisitor.Handle) - if err != nil { - t.Fatalf("unexpected response: %v %t %#v %s", err, singleItemImplied, testVisitor.Infos, test.name) - } + err := b.Do().IntoSingleItemImplied(&singleItemImplied).Visit(testVisitor.Handle) + if err != nil { + t.Fatalf("unexpected response: %v %t %#v %s", err, singleItemImplied, testVisitor.Infos, tt.name) + } - info := testVisitor.Infos + info := testVisitor.Infos - for i, v := range info { - switch test.object.(type) { - case *v1.Pod: - if _, ok := v.Object.(*v1.Pod); !ok || v.Name != test.expectedNames[i] || v.Namespace != "test" { - t.Errorf("unexpected info: %v", spew.Sdump(v.Object)) - } - case *v1.ReplicationController: - if _, ok := v.Object.(*v1.ReplicationController); !ok || v.Name != test.expectedNames[i] || v.Namespace != "test" { - t.Errorf("unexpected info: %v", spew.Sdump(v.Object)) + for i, v := range info { + switch tt.object.(type) { + case *v1.Pod: + if _, ok := v.Object.(*v1.Pod); !ok || v.Name != tt.expectedNames[i] || v.Namespace != "test" { + t.Errorf("unexpected info: %v", spew.Sdump(v.Object)) + } + case *v1.ReplicationController: + if _, ok := v.Object.(*v1.ReplicationController); !ok || v.Name != tt.expectedNames[i] || v.Namespace != "test" { + t.Errorf("unexpected info: %v", spew.Sdump(v.Object)) + } } } - } + }) } } @@ -437,18 +439,20 @@ func TestPathBuilderWithMultipleInvalid(t *testing.T) { {"loop", true, fmt.Sprintf("%s/inode/symlink/loop", tmpDir)}, } - for _, test := range tests { - b := newDefaultBuilder(). - FilenameParam(false, &FilenameOptions{Recursive: test.recursive, Filenames: []string{test.directory}}). - NamespaceParam("test").DefaultNamespace() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + b := newDefaultBuilder(). + FilenameParam(false, &FilenameOptions{Recursive: tt.recursive, Filenames: []string{tt.directory}}). + NamespaceParam("test").DefaultNamespace() - testVisitor := &testVisitor{} - singleItemImplied := false + testVisitor := &testVisitor{} + singleItemImplied := false - err := b.Do().IntoSingleItemImplied(&singleItemImplied).Visit(testVisitor.Handle) - if err == nil { - t.Fatalf("unexpected response: %v %t %#v %s", err, singleItemImplied, testVisitor.Infos, test.name) - } + err := b.Do().IntoSingleItemImplied(&singleItemImplied).Visit(testVisitor.Handle) + if err == nil { + t.Fatalf("unexpected response: %v %t %#v %s", err, singleItemImplied, testVisitor.Infos, tt.name) + } + }) } } @@ -928,43 +932,45 @@ func TestResourceTuple(t *testing.T) { errFn: expectErr, }, } - for k, testCase := range testCases { - for _, requireObject := range []bool{true, false} { - expectedRequests := map[string]string{} - if requireObject { - pods, _ := testData() - expectedRequests = map[string]string{ - "/namespaces/test/pods/foo": runtime.EncodeOrDie(corev1Codec, &pods.Items[0]), - "/namespaces/test/pods/bar": runtime.EncodeOrDie(corev1Codec, &pods.Items[0]), - "/nodes/foo": runtime.EncodeOrDie(corev1Codec, &v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}), + for k, tt := range testCases { + t.Run("using default namespace", func(t *testing.T) { + for _, requireObject := range []bool{true, false} { + expectedRequests := map[string]string{} + if requireObject { + pods, _ := testData() + expectedRequests = map[string]string{ + "/namespaces/test/pods/foo": runtime.EncodeOrDie(corev1Codec, &pods.Items[0]), + "/namespaces/test/pods/bar": runtime.EncodeOrDie(corev1Codec, &pods.Items[0]), + "/nodes/foo": runtime.EncodeOrDie(corev1Codec, &v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}), + } + } + b := newDefaultBuilderWith(fakeClientWith(k, t, expectedRequests)). + NamespaceParam("test").DefaultNamespace(). + ResourceTypeOrNameArgs(true, tt.args...).RequireObject(requireObject) + + r := b.Do() + + if !tt.errFn(r.Err()) { + t.Errorf("%s: unexpected error: %v", k, r.Err()) + } + if r.Err() != nil { + continue + } + switch { + case (r.singleItemImplied && len(tt.args) != 1), + (!r.singleItemImplied && len(tt.args) == 1): + t.Errorf("%s: result had unexpected singleItemImplied value", k) + } + info, err := r.Infos() + if err != nil { + // test error + continue + } + if len(info) != len(tt.args) { + t.Errorf("%s: unexpected number of infos returned: %#v", k, info) } } - b := newDefaultBuilderWith(fakeClientWith(k, t, expectedRequests)). - NamespaceParam("test").DefaultNamespace(). - ResourceTypeOrNameArgs(true, testCase.args...).RequireObject(requireObject) - - r := b.Do() - - if !testCase.errFn(r.Err()) { - t.Errorf("%s: unexpected error: %v", k, r.Err()) - } - if r.Err() != nil { - continue - } - switch { - case (r.singleItemImplied && len(testCase.args) != 1), - (!r.singleItemImplied && len(testCase.args) == 1): - t.Errorf("%s: result had unexpected singleItemImplied value", k) - } - info, err := r.Infos() - if err != nil { - // test error - continue - } - if len(info) != len(testCase.args) { - t.Errorf("%s: unexpected number of infos returned: %#v", k, info) - } - } + }) } } @@ -1296,120 +1302,146 @@ func TestReceiveMultipleErrors(t *testing.T) { func TestHasNames(t *testing.T) { basename := filepath.Base(os.Args[0]) tests := []struct { + name string args []string expectedHasName bool expectedError error }{ { + name: "test1", args: []string{""}, expectedHasName: false, expectedError: nil, }, { + name: "test2", args: []string{"rc"}, expectedHasName: false, expectedError: nil, }, { + name: "test3", args: []string{"rc,pod,svc"}, expectedHasName: false, expectedError: nil, }, { + name: "test4", args: []string{"rc/foo"}, expectedHasName: true, expectedError: nil, }, { + name: "test5", args: []string{"rc", "foo"}, expectedHasName: true, expectedError: nil, }, { + name: "test6", args: []string{"rc,pod,svc", "foo"}, expectedHasName: true, expectedError: nil, }, { + name: "test7", args: []string{"rc/foo", "rc/bar", "rc/zee"}, expectedHasName: true, expectedError: nil, }, { + name: "test8", args: []string{"rc/foo", "bar"}, expectedHasName: false, expectedError: fmt.Errorf("there is no need to specify a resource type as a separate argument when passing arguments in resource/name form (e.g. '" + basename + " get resource/' instead of '" + basename + " get resource resource/'"), }, } - for _, test := range tests { - hasNames, err := HasNames(test.args) - if !reflect.DeepEqual(test.expectedError, err) { - t.Errorf("expected HasName to error:\n%s\tgot:\n%s", test.expectedError, err) - } - if hasNames != test.expectedHasName { - t.Errorf("expected HasName to return %v for %s", test.expectedHasName, test.args) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + hasNames, err := HasNames(tt.args) + if !reflect.DeepEqual(tt.expectedError, err) { + t.Errorf("expected HasName to error:\n%s\tgot:\n%s", tt.expectedError, err) + } + if hasNames != tt.expectedHasName { + t.Errorf("expected HasName to return %v for %s", tt.expectedHasName, tt.args) + } + }) } } func TestMultipleTypesRequested(t *testing.T) { tests := []struct { + name string args []string expectedMultipleTypes bool }{ { + name: "test1", args: []string{""}, expectedMultipleTypes: false, }, { + name: "test2", args: []string{"all"}, expectedMultipleTypes: true, }, { + name: "test3", args: []string{"rc"}, expectedMultipleTypes: false, }, { + name: "test4", args: []string{"pod,all"}, expectedMultipleTypes: true, }, { + name: "test5", args: []string{"all,rc,pod"}, expectedMultipleTypes: true, }, { + name: "test6", args: []string{"rc,pod,svc"}, expectedMultipleTypes: true, }, { + name: "test7", args: []string{"rc/foo"}, expectedMultipleTypes: false, }, { + name: "test8", args: []string{"rc/foo", "rc/bar"}, expectedMultipleTypes: false, }, { + name: "test9", args: []string{"rc", "foo"}, expectedMultipleTypes: false, }, { + name: "test10", args: []string{"rc,pod,svc", "foo"}, expectedMultipleTypes: true, }, { + name: "test11", args: []string{"rc,secrets"}, expectedMultipleTypes: true, }, { + name: "test12", args: []string{"rc/foo", "rc/bar", "svc/svc"}, expectedMultipleTypes: true, }, } - for _, test := range tests { - hasMultipleTypes := MultipleTypesRequested(test.args) - if hasMultipleTypes != test.expectedMultipleTypes { - t.Errorf("expected MultipleTypesRequested to return %v for %s", test.expectedMultipleTypes, test.args) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + hasMultipleTypes := MultipleTypesRequested(tt.args) + if hasMultipleTypes != tt.expectedMultipleTypes { + t.Errorf("expected MultipleTypesRequested to return %v for %s", tt.expectedMultipleTypes, tt.args) + } + }) } } diff --git a/pkg/kubectl/genericclioptions/resource/helper_test.go b/pkg/kubectl/genericclioptions/resource/helper_test.go index e9cf7b1c96..67ce7f5fe2 100644 --- a/pkg/kubectl/genericclioptions/resource/helper_test.go +++ b/pkg/kubectl/genericclioptions/resource/helper_test.go @@ -69,16 +69,19 @@ func V1DeepEqualSafePodSpec() corev1.PodSpec { func TestHelperDelete(t *testing.T) { tests := []struct { + name string Err bool Req func(*http.Request) bool Resp *http.Response HttpErr error }{ { + name: "test1", HttpErr: errors.New("failure"), Err: true, }, { + name: "test2", Resp: &http.Response{ StatusCode: http.StatusNotFound, Header: header(), @@ -87,6 +90,7 @@ func TestHelperDelete(t *testing.T) { Err: true, }, { + name: "test3pkg/kubectl/genericclioptions/resource/helper_test.go", Resp: &http.Response{ StatusCode: http.StatusOK, Header: header(), @@ -114,26 +118,28 @@ func TestHelperDelete(t *testing.T) { }, }, } - for _, test := range tests { - client := &fake.RESTClient{ - NegotiatedSerializer: scheme.Codecs, - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: true, - } - err := modifier.Delete("bar", "foo") - if (err != nil) != test.Err { - t.Errorf("unexpected error: %t %v", test.Err, err) - } - if err != nil { - continue - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("unexpected request: %#v", client.Req) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := &fake.RESTClient{ + NegotiatedSerializer: scheme.Codecs, + Resp: tt.Resp, + Err: tt.HttpErr, + } + modifier := &Helper{ + RESTClient: client, + NamespaceScoped: true, + } + err := modifier.Delete("bar", "foo") + if (err != nil) != tt.Err { + t.Errorf("unexpected error: %t %v", tt.Err, err) + } + if err != nil { + return + } + if tt.Req != nil && !tt.Req(client.Req) { + t.Errorf("unexpected request: %#v", client.Req) + } + }) } } @@ -152,6 +158,7 @@ func TestHelperCreate(t *testing.T) { } tests := []struct { + name string Resp *http.Response HttpErr error Modify bool @@ -162,10 +169,12 @@ func TestHelperCreate(t *testing.T) { Req func(*http.Request) bool }{ { + name: "test1", HttpErr: errors.New("failure"), Err: true, }, { + name: "test1", Resp: &http.Response{ StatusCode: http.StatusNotFound, Header: header(), @@ -174,6 +183,7 @@ func TestHelperCreate(t *testing.T) { Err: true, }, { + name: "test1", Resp: &http.Response{ StatusCode: http.StatusOK, Header: header(), @@ -184,6 +194,7 @@ func TestHelperCreate(t *testing.T) { Req: expectPost, }, { + name: "test1", Modify: false, Object: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, ExpectObject: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, @@ -191,6 +202,7 @@ func TestHelperCreate(t *testing.T) { Req: expectPost, }, { + name: "test1", Modify: true, Object: &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "10"}, @@ -204,55 +216,59 @@ func TestHelperCreate(t *testing.T) { Req: expectPost, }, } - for i, test := range tests { - client := &fake.RESTClient{ - GroupVersion: corev1GV, - NegotiatedSerializer: scheme.Codecs, - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: true, - } - _, err := modifier.Create("bar", test.Modify, test.Object) - if (err != nil) != test.Err { - t.Errorf("%d: unexpected error: %t %v", i, test.Err, err) - } - if err != nil { - continue - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("%d: unexpected request: %#v", i, client.Req) - } - body, err := ioutil.ReadAll(client.Req.Body) - if err != nil { - t.Fatalf("%d: unexpected error: %#v", i, err) - } - t.Logf("got body: %s", string(body)) - expect := []byte{} - if test.ExpectObject != nil { - expect = []byte(runtime.EncodeOrDie(corev1Codec, test.ExpectObject)) - } - if !reflect.DeepEqual(expect, body) { - t.Errorf("%d: unexpected body: %s (expected %s)", i, string(body), string(expect)) - } - + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := &fake.RESTClient{ + GroupVersion: corev1GV, + NegotiatedSerializer: scheme.Codecs, + Resp: tt.Resp, + Err: tt.HttpErr, + } + modifier := &Helper{ + RESTClient: client, + NamespaceScoped: true, + } + _, err := modifier.Create("bar", tt.Modify, tt.Object) + if (err != nil) != tt.Err { + t.Errorf("%d: unexpected error: %t %v", i, tt.Err, err) + } + if err != nil { + return + } + if tt.Req != nil && !tt.Req(client.Req) { + t.Errorf("%d: unexpected request: %#v", i, client.Req) + } + body, err := ioutil.ReadAll(client.Req.Body) + if err != nil { + t.Fatalf("%d: unexpected error: %#v", i, err) + } + t.Logf("got body: %s", string(body)) + expect := []byte{} + if tt.ExpectObject != nil { + expect = []byte(runtime.EncodeOrDie(corev1Codec, tt.ExpectObject)) + } + if !reflect.DeepEqual(expect, body) { + t.Errorf("%d: unexpected body: %s (expected %s)", i, string(body), string(expect)) + } + }) } } func TestHelperGet(t *testing.T) { tests := []struct { + name string Err bool Req func(*http.Request) bool Resp *http.Response HttpErr error }{ { + name: "test1", HttpErr: errors.New("failure"), Err: true, }, { + name: "test1", Resp: &http.Response{ StatusCode: http.StatusNotFound, Header: header(), @@ -261,6 +277,7 @@ func TestHelperGet(t *testing.T) { Err: true, }, { + name: "test1", Resp: &http.Response{ StatusCode: http.StatusOK, Header: header(), @@ -284,46 +301,51 @@ func TestHelperGet(t *testing.T) { }, }, } - for i, test := range tests { - client := &fake.RESTClient{ - GroupVersion: corev1GV, - NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: true, - } - obj, err := modifier.Get("bar", "foo", false) + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := &fake.RESTClient{ + GroupVersion: corev1GV, + NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, + Resp: tt.Resp, + Err: tt.HttpErr, + } + modifier := &Helper{ + RESTClient: client, + NamespaceScoped: true, + } + obj, err := modifier.Get("bar", "foo", false) - if (err != nil) != test.Err { - t.Errorf("unexpected error: %d %t %v", i, test.Err, err) - } - if err != nil { - continue - } - if obj.(*corev1.Pod).Name != "foo" { - t.Errorf("unexpected object: %#v", obj) - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("unexpected request: %#v", client.Req) - } + if (err != nil) != tt.Err { + t.Errorf("unexpected error: %d %t %v", i, tt.Err, err) + } + if err != nil { + return + } + if obj.(*corev1.Pod).Name != "foo" { + t.Errorf("unexpected object: %#v", obj) + } + if tt.Req != nil && !tt.Req(client.Req) { + t.Errorf("unexpected request: %#v", client.Req) + } + }) } } func TestHelperList(t *testing.T) { tests := []struct { + name string Err bool Req func(*http.Request) bool Resp *http.Response HttpErr error }{ { + name: "test1", HttpErr: errors.New("failure"), Err: true, }, { + name: "test2", Resp: &http.Response{ StatusCode: http.StatusNotFound, Header: header(), @@ -332,6 +354,7 @@ func TestHelperList(t *testing.T) { Err: true, }, { + name: "test3", Resp: &http.Response{ StatusCode: http.StatusOK, Header: header(), @@ -359,30 +382,32 @@ func TestHelperList(t *testing.T) { }, }, } - for _, test := range tests { - client := &fake.RESTClient{ - GroupVersion: corev1GV, - NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: true, - } - obj, err := modifier.List("bar", corev1GV.String(), false, &metav1.ListOptions{LabelSelector: "foo=baz"}) - if (err != nil) != test.Err { - t.Errorf("unexpected error: %t %v", test.Err, err) - } - if err != nil { - continue - } - if obj.(*corev1.PodList).Items[0].Name != "foo" { - t.Errorf("unexpected object: %#v", obj) - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("unexpected request: %#v", client.Req) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := &fake.RESTClient{ + GroupVersion: corev1GV, + NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, + Resp: tt.Resp, + Err: tt.HttpErr, + } + modifier := &Helper{ + RESTClient: client, + NamespaceScoped: true, + } + obj, err := modifier.List("bar", corev1GV.String(), false, &metav1.ListOptions{LabelSelector: "foo=baz"}) + if (err != nil) != tt.Err { + t.Errorf("unexpected error: %t %v", tt.Err, err) + } + if err != nil { + return + } + if obj.(*corev1.PodList).Items[0].Name != "foo" { + t.Errorf("unexpected object: %#v", obj) + } + if tt.Req != nil && !tt.Req(client.Req) { + t.Errorf("unexpected request: %#v", client.Req) + } + }) } } @@ -436,19 +461,21 @@ func TestHelperListSelectorCombination(t *testing.T) { NamespaceScoped: true, } - for _, test := range tests { - _, err := modifier.List("bar", - corev1GV.String(), - false, - &metav1.ListOptions{LabelSelector: test.LabelSelector, FieldSelector: test.FieldSelector}) - if test.Err { - if err == nil { - t.Errorf("%q expected error: %q", test.Name, test.ErrMsg) + for _, tt := range tests { + t.Run(tt.Name, func(t *testing.T) { + _, err := modifier.List("bar", + corev1GV.String(), + false, + &metav1.ListOptions{LabelSelector: tt.LabelSelector, FieldSelector: tt.FieldSelector}) + if tt.Err { + if err == nil { + t.Errorf("%q expected error: %q", tt.Name, tt.ErrMsg) + } + if err != nil && err.Error() != tt.ErrMsg { + t.Errorf("%q expected error: %q", tt.Name, tt.ErrMsg) + } } - if err != nil && err.Error() != test.ErrMsg { - t.Errorf("%q expected error: %q", test.Name, test.ErrMsg) - } - } + }) } } @@ -466,6 +493,7 @@ func TestHelperReplace(t *testing.T) { } tests := []struct { + Name string Resp *http.Response HTTPClient *http.Client HttpErr error @@ -480,12 +508,14 @@ func TestHelperReplace(t *testing.T) { Req func(string, *http.Request) bool }{ { + Name: "test1", Namespace: "bar", NamespaceScoped: true, HttpErr: errors.New("failure"), Err: true, }, { + Name: "test2", Namespace: "bar", NamespaceScoped: true, Object: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}, @@ -497,6 +527,7 @@ func TestHelperReplace(t *testing.T) { Err: true, }, { + Name: "test3", Namespace: "bar", NamespaceScoped: true, Object: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}, @@ -511,6 +542,7 @@ func TestHelperReplace(t *testing.T) { }, // namespace scoped resource { + Name: "test4", Namespace: "bar", NamespaceScoped: true, Object: &corev1.Pod{ @@ -533,6 +565,7 @@ func TestHelperReplace(t *testing.T) { }, // cluster scoped resource { + Name: "test5", Object: &corev1.Node{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, }, @@ -550,6 +583,7 @@ func TestHelperReplace(t *testing.T) { Req: expectPut, }, { + Name: "test6", Namespace: "bar", NamespaceScoped: true, Object: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, @@ -559,38 +593,40 @@ func TestHelperReplace(t *testing.T) { Req: expectPut, }, } - for i, test := range tests { - client := &fake.RESTClient{ - GroupVersion: corev1GV, - NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, - Client: test.HTTPClient, - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: test.NamespaceScoped, - } - _, err := modifier.Replace(test.Namespace, "foo", test.Overwrite, test.Object) - if (err != nil) != test.Err { - t.Errorf("%d: unexpected error: %t %v", i, test.Err, err) - } - if err != nil { - continue - } - if test.Req != nil && !test.Req(test.ExpectPath, client.Req) { - t.Errorf("%d: unexpected request: %#v", i, client.Req) - } - body, err := ioutil.ReadAll(client.Req.Body) - if err != nil { - t.Fatalf("%d: unexpected error: %#v", i, err) - } - expect := []byte{} - if test.ExpectObject != nil { - expect = []byte(runtime.EncodeOrDie(corev1Codec, test.ExpectObject)) - } - if !reflect.DeepEqual(expect, body) { - t.Errorf("%d: unexpected body: %s", i, string(body)) - } + for i, tt := range tests { + t.Run(tt.Name, func(t *testing.T) { + client := &fake.RESTClient{ + GroupVersion: corev1GV, + NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, + Client: tt.HTTPClient, + Resp: tt.Resp, + Err: tt.HttpErr, + } + modifier := &Helper{ + RESTClient: client, + NamespaceScoped: tt.NamespaceScoped, + } + _, err := modifier.Replace(tt.Namespace, "foo", tt.Overwrite, tt.Object) + if (err != nil) != tt.Err { + t.Errorf("%d: unexpected error: %t %v", i, tt.Err, err) + } + if err != nil { + return + } + if tt.Req != nil && !tt.Req(tt.ExpectPath, client.Req) { + t.Errorf("%d: unexpected request: %#v", i, client.Req) + } + body, err := ioutil.ReadAll(client.Req.Body) + if err != nil { + t.Fatalf("%d: unexpected error: %#v", i, err) + } + expect := []byte{} + if tt.ExpectObject != nil { + expect = []byte(runtime.EncodeOrDie(corev1Codec, tt.ExpectObject)) + } + if !reflect.DeepEqual(expect, body) { + t.Errorf("%d: unexpected body: %s", i, string(body)) + } + }) } } diff --git a/pkg/kubectl/genericclioptions/resource/visitor_test.go b/pkg/kubectl/genericclioptions/resource/visitor_test.go index 50f7db7cad..62dce9b653 100644 --- a/pkg/kubectl/genericclioptions/resource/visitor_test.go +++ b/pkg/kubectl/genericclioptions/resource/visitor_test.go @@ -22,81 +22,144 @@ import ( "io" "io/ioutil" "testing" + "time" "github.com/stretchr/testify/assert" ) func TestVisitorHttpGet(t *testing.T) { - // Test retries on errors + type httpArgs struct { + duration time.Duration + u string + attempts int + } + i := 0 - expectedErr := fmt.Errorf("Failed to get http") - actualBytes, actualErr := readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) { - assert.Equal(t, "hello", url) - i++ - if i > 2 { - return 0, "", nil, expectedErr - } - return 0, "", nil, fmt.Errorf("Unexpected error") - }, 0, "hello", 3) - assert.Equal(t, expectedErr, actualErr) - assert.Nil(t, actualBytes) - assert.Equal(t, 3, i) + tests := []struct { + name string + httpRetries httpget + args httpArgs + expectedErr error + actualBytes io.ReadCloser + actualErr error + count int + isNotNil bool + }{ + { + name: "Test retries on errors", + httpRetries: func(url string) (int, string, io.ReadCloser, error) { + assert.Equal(t, "hello", url) + i++ + if i > 2 { + return 0, "", nil, fmt.Errorf("Failed to get http") + } + return 0, "", nil, fmt.Errorf("Unexpected error") - // Test that 500s are retried. - i = 0 - actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) { - assert.Equal(t, "hello", url) - i++ - return 501, "Status", nil, nil - }, 0, "hello", 3) - assert.Error(t, actualErr) - assert.Nil(t, actualBytes) - assert.Equal(t, 3, i) + }, + expectedErr: fmt.Errorf("Failed to get http"), + args: httpArgs{ + duration: 0, + u: "hello", + attempts: 3, + }, + count: 3, + }, + { + name: "Test that 500s are retried", + httpRetries: func(url string) (int, string, io.ReadCloser, error) { + assert.Equal(t, "hello", url) + i++ + return 501, "Status", nil, nil + }, + args: httpArgs{ + duration: 0, + u: "hello", + attempts: 3, + }, + count: 3, + }, + { + name: "Test that 300s are not retried", + httpRetries: func(url string) (int, string, io.ReadCloser, error) { + assert.Equal(t, "hello", url) + i++ + return 300, "Status", nil, nil - // Test that 300s are not retried - i = 0 - actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) { - assert.Equal(t, "hello", url) - i++ - return 300, "Status", nil, nil - }, 0, "hello", 3) - assert.Error(t, actualErr) - assert.Nil(t, actualBytes) - assert.Equal(t, 1, i) + }, + args: httpArgs{ + duration: 0, + u: "hello", + attempts: 3, + }, + count: 1, + }, + { + name: "Test attempt count is respected", + httpRetries: func(url string) (int, string, io.ReadCloser, error) { + assert.Equal(t, "hello", url) + i++ + return 501, "Status", nil, nil - // Test attempt count is respected - i = 0 - actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) { - assert.Equal(t, "hello", url) - i++ - return 501, "Status", nil, nil - }, 0, "hello", 1) - assert.Error(t, actualErr) - assert.Nil(t, actualBytes) - assert.Equal(t, 1, i) + }, + args: httpArgs{ + duration: 0, + u: "hello", + attempts: 1, + }, + count: 1, + }, + { + name: "Test attempts less than 1 results in an error", + httpRetries: func(url string) (int, string, io.ReadCloser, error) { + return 200, "Status", ioutil.NopCloser(new(bytes.Buffer)), nil - // Test attempts less than 1 results in an error - i = 0 - b := bytes.Buffer{} - actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) { - return 200, "Status", ioutil.NopCloser(&b), nil - }, 0, "hello", 0) - assert.Error(t, actualErr) - assert.Nil(t, actualBytes) - assert.Equal(t, 0, i) + }, + args: httpArgs{ + duration: 0, + u: "hello", + attempts: 0, + }, + count: 0, + }, + { + name: "Test Success", + httpRetries: func(url string) (int, string, io.ReadCloser, error) { + assert.Equal(t, "hello", url) + i++ + if i > 1 { + return 200, "Status", ioutil.NopCloser(new(bytes.Buffer)), nil + } + return 501, "Status", nil, nil - // Test Success - i = 0 - b = bytes.Buffer{} - actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) { - assert.Equal(t, "hello", url) - i++ - if i > 1 { - return 200, "Status", ioutil.NopCloser(&b), nil - } - return 501, "Status", nil, nil - }, 0, "hello", 3) - assert.Nil(t, actualErr) - assert.NotNil(t, actualBytes) - assert.Equal(t, 2, i) + }, + args: httpArgs{ + duration: 0, + u: "hello", + attempts: 3, + }, + count: 2, + isNotNil: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + i = 0 + actualBytes, actualErr := readHttpWithRetries(tt.httpRetries, tt.args.duration, tt.args.u, tt.args.attempts) + + if tt.isNotNil { + assert.Nil(t, actualErr) + assert.NotNil(t, actualBytes) + } else { + if tt.expectedErr != nil { + assert.Equal(t, tt.expectedErr, actualErr) + } else { + assert.Error(t, actualErr) + } + assert.Nil(t, actualBytes) + } + + assert.Equal(t, tt.count, i) + }) + } } diff --git a/pkg/kubectl/namespace_test.go b/pkg/kubectl/namespace_test.go index 23b214225a..db07fdc6d8 100644 --- a/pkg/kubectl/namespace_test.go +++ b/pkg/kubectl/namespace_test.go @@ -26,11 +26,13 @@ import ( func TestNamespaceGenerate(t *testing.T) { tests := []struct { + name string params map[string]interface{} expected *v1.Namespace expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "name": "foo", }, @@ -42,34 +44,40 @@ func TestNamespaceGenerate(t *testing.T) { expectErr: false, }, { + name: "test2", params: map[string]interface{}{}, expectErr: true, }, { + name: "test3", params: map[string]interface{}{ "name": 1, }, expectErr: true, }, { + name: "test4", params: map[string]interface{}{ "name": "", }, expectErr: true, }, { + name: "test5", params: map[string]interface{}{ "name": nil, }, expectErr: true, }, { + name: "test6", params: map[string]interface{}{ "name_wrong_key": "some_value", }, expectErr: true, }, { + name: "test7", params: map[string]interface{}{ "NAME": "some_value", }, @@ -77,22 +85,24 @@ func TestNamespaceGenerate(t *testing.T) { }, } generator := NamespaceGeneratorV1{} - for index, test := range tests { - obj, err := generator.Generate(test.params) - switch { - case test.expectErr && err != nil: - continue // loop, since there's no output to check - case test.expectErr && err == nil: - t.Errorf("%v: expected error and didn't get one", index) - continue // loop, no expected output object - case !test.expectErr && err != nil: - t.Errorf("%v: unexpected error %v", index, err) - continue // loop, no output object - case !test.expectErr && err == nil: - // do nothing and drop through - } - if !reflect.DeepEqual(obj.(*v1.Namespace), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.Namespace)) - } + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + switch { + case tt.expectErr && err != nil: + return // loop, since there's no output to check + case tt.expectErr && err == nil: + t.Errorf("%v: expected error and didn't get one", index) + return // loop, no expected output object + case !tt.expectErr && err != nil: + t.Errorf("%v: unexpected error %v", index, err) + return // loop, no output object + case !tt.expectErr && err == nil: + // do nothing and drop through + } + if !reflect.DeepEqual(obj.(*v1.Namespace), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.Namespace)) + } + }) } } diff --git a/pkg/kubectl/pdb_test.go b/pkg/kubectl/pdb_test.go index 35860dbdfd..96696710f4 100644 --- a/pkg/kubectl/pdb_test.go +++ b/pkg/kubectl/pdb_test.go @@ -36,12 +36,14 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { t.Errorf("unexpected error: %v", err) } - tests := map[string]struct { + tests := []struct { + name string params map[string]interface{} expectErrMsg string expectPDB *policy.PodDisruptionBudget }{ - "test-valid-use": { + { + name: "test-valid-use", params: map[string]interface{}{ "name": name, "min-available": minAvailable, @@ -57,14 +59,16 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { }, }, }, - "test-missing-name-param": { + { + name: "test-missing-name-param", params: map[string]interface{}{ "min-available": minAvailable, "selector": selector, }, expectErrMsg: "Parameter: name is required", }, - "test-blank-name-param": { + { + name: "test-blank-name-param", params: map[string]interface{}{ "name": "", "min-available": minAvailable, @@ -72,7 +76,8 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { }, expectErrMsg: "Parameter: name is required", }, - "test-invalid-name-param": { + { + name: "test-invalid-name-param", params: map[string]interface{}{ "name": 1, "min-available": minAvailable, @@ -80,14 +85,16 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { }, expectErrMsg: "expected string, found int for 'name'", }, - "test-missing-min-available-param": { + { + name: "test-missing-min-available-param", params: map[string]interface{}{ "name": name, "selector": selector, }, expectErrMsg: "expected string, found for 'min-available'", }, - "test-blank-min-available-param": { + { + name: "test-blank-min-available-param", params: map[string]interface{}{ "name": name, "min-available": "", @@ -103,7 +110,8 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { }, }, }, - "test-invalid-min-available-param": { + { + name: "test-invalid-min-available-param", params: map[string]interface{}{ "name": name, "min-available": 1, @@ -111,14 +119,16 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { }, expectErrMsg: "expected string, found int for 'min-available'", }, - "test-missing-selector-param": { + { + name: "test-missing-selector-param", params: map[string]interface{}{ "name": name, "min-available": minAvailable, }, expectErrMsg: "Parameter: selector is required", }, - "test-blank-selector-param": { + { + name: "test-blank-selector-param", params: map[string]interface{}{ "name": name, "min-available": minAvailable, @@ -126,7 +136,8 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { }, expectErrMsg: "Parameter: selector is required", }, - "test-invalid-selector-param": { + { + name: "test-invalid-selector-param", params: map[string]interface{}{ "name": name, "min-available": minAvailable, @@ -137,24 +148,26 @@ func TestPodDisruptionBudgetV1Generate(t *testing.T) { } generator := PodDisruptionBudgetV1Generator{} - for name, test := range tests { - obj, err := generator.Generate(test.params) - switch { - case test.expectErrMsg != "" && err != nil: - if err.Error() != test.expectErrMsg { - t.Errorf("test '%s': expect error '%s', but saw '%s'", name, test.expectErrMsg, err.Error()) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + switch { + case tt.expectErrMsg != "" && err != nil: + if err.Error() != tt.expectErrMsg { + t.Errorf("test '%s': expect error '%s', but saw '%s'", tt.name, tt.expectErrMsg, err.Error()) + } + return + case tt.expectErrMsg != "" && err == nil: + t.Errorf("test '%s': expected error '%s' and didn't get one", tt.name, tt.expectErrMsg) + return + case tt.expectErrMsg == "" && err != nil: + t.Errorf("test '%s': unexpected error %s", tt.name, err.Error()) + return } - continue - case test.expectErrMsg != "" && err == nil: - t.Errorf("test '%s': expected error '%s' and didn't get one", name, test.expectErrMsg) - continue - case test.expectErrMsg == "" && err != nil: - t.Errorf("test '%s': unexpected error %s", name, err.Error()) - continue - } - if !reflect.DeepEqual(obj.(*policy.PodDisruptionBudget), test.expectPDB) { - t.Errorf("test '%s': expected:\n%#v\nsaw:\n%#v", name, test.expectPDB, obj.(*policy.PodDisruptionBudget)) - } + if !reflect.DeepEqual(obj.(*policy.PodDisruptionBudget), tt.expectPDB) { + t.Errorf("test '%s': expected:\n%#v\nsaw:\n%#v", tt.name, tt.expectPDB, obj.(*policy.PodDisruptionBudget)) + } + }) } } @@ -170,12 +183,14 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { t.Errorf("unexpected error: %v", err) } - tests := map[string]struct { + tests := []struct { + name string params map[string]interface{} expectErrMsg string expectPDB *policy.PodDisruptionBudget }{ - "test-valid-min-available": { + { + name: "test-valid-min-available", params: map[string]interface{}{ "name": name, "min-available": minAvailable, @@ -192,7 +207,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, }, }, - "test-valid-max-available": { + { + name: "test-valid-max-available", params: map[string]interface{}{ "name": name, "min-available": "", @@ -209,7 +225,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, }, }, - "test-missing-name-param": { + { + name: "test-missing-name-param", params: map[string]interface{}{ "min-available": "", "max-unavailable": "", @@ -217,7 +234,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "Parameter: name is required", }, - "test-blank-name-param": { + { + name: "test-blank-name-param", params: map[string]interface{}{ "name": "", "min-available": "", @@ -226,7 +244,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "Parameter: name is required", }, - "test-invalid-name-param": { + { + name: "test-invalid-name-param", params: map[string]interface{}{ "name": 1, "min-available": "", @@ -235,7 +254,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "expected string, found int for 'name'", }, - "test-missing-min-available-param": { + { + name: "test-missing-min-available-param", params: map[string]interface{}{ "name": name, "max-unavailable": "", @@ -243,7 +263,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "expected string, found for 'min-available'", }, - "test-invalid-min-available-param": { + { + name: "test-invalid-min-available-param", params: map[string]interface{}{ "name": name, "min-available": 1, @@ -252,7 +273,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "expected string, found int for 'min-available'", }, - "test-missing-max-available-param": { + { + name: "test-missing-max-available-param", params: map[string]interface{}{ "name": name, "min-available": "", @@ -260,7 +282,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "expected string, found for 'max-unavailable'", }, - "test-invalid-max-available-param": { + { + name: "test-invalid-max-available-param", params: map[string]interface{}{ "name": name, "min-available": "", @@ -269,7 +292,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "expected string, found int for 'max-unavailable'", }, - "test-blank-min-available-max-unavailable-param": { + { + name: "test-blank-min-available-max-unavailable-param", params: map[string]interface{}{ "name": name, "min-available": "", @@ -278,7 +302,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "one of min-available or max-unavailable must be specified", }, - "test-min-available-max-unavailable-param": { + { + name: "test-min-available-max-unavailable-param", params: map[string]interface{}{ "name": name, "min-available": minAvailable, @@ -287,7 +312,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "min-available and max-unavailable cannot be both specified", }, - "test-missing-selector-param": { + { + name: "test-missing-selector-param", params: map[string]interface{}{ "name": name, "min-available": "", @@ -295,7 +321,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "Parameter: selector is required", }, - "test-blank-selector-param": { + { + name: "test-blank-selector-param", params: map[string]interface{}{ "name": name, "min-available": "", @@ -304,7 +331,8 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { }, expectErrMsg: "Parameter: selector is required", }, - "test-invalid-selector-param": { + { + name: "test-invalid-selector-param", params: map[string]interface{}{ "name": name, "min-available": "", @@ -316,23 +344,25 @@ func TestPodDisruptionBudgetV2Generate(t *testing.T) { } generator := PodDisruptionBudgetV2Generator{} - for name, test := range tests { - obj, err := generator.Generate(test.params) - switch { - case test.expectErrMsg != "" && err != nil: - if err.Error() != test.expectErrMsg { - t.Errorf("test '%s': expect error '%s', but saw '%s'", name, test.expectErrMsg, err.Error()) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + switch { + case tt.expectErrMsg != "" && err != nil: + if err.Error() != tt.expectErrMsg { + t.Errorf("test '%s': expect error '%s', but saw '%s'", tt.name, tt.expectErrMsg, err.Error()) + } + return + case tt.expectErrMsg != "" && err == nil: + t.Errorf("test '%s': expected error '%s' and didn't get one", tt.name, tt.expectErrMsg) + return + case tt.expectErrMsg == "" && err != nil: + t.Errorf("test '%s': unexpected error %s", tt.name, err.Error()) + return } - continue - case test.expectErrMsg != "" && err == nil: - t.Errorf("test '%s': expected error '%s' and didn't get one", name, test.expectErrMsg) - continue - case test.expectErrMsg == "" && err != nil: - t.Errorf("test '%s': unexpected error %s", name, err.Error()) - continue - } - if !reflect.DeepEqual(obj.(*policy.PodDisruptionBudget), test.expectPDB) { - t.Errorf("test '%s': expected:\n%#v\nsaw:\n%#v", name, test.expectPDB, obj.(*policy.PodDisruptionBudget)) - } + if !reflect.DeepEqual(obj.(*policy.PodDisruptionBudget), tt.expectPDB) { + t.Errorf("test '%s': expected:\n%#v\nsaw:\n%#v", tt.name, tt.expectPDB, obj.(*policy.PodDisruptionBudget)) + } + }) } } diff --git a/pkg/kubectl/plugins/env_test.go b/pkg/kubectl/plugins/env_test.go index 73a1440daf..780d239eea 100644 --- a/pkg/kubectl/plugins/env_test.go +++ b/pkg/kubectl/plugins/env_test.go @@ -25,35 +25,43 @@ import ( func TestEnv(t *testing.T) { tests := []struct { + name string env Env expected string }{ { + name: "test1", env: Env{"FOO", "BAR"}, expected: "FOO=BAR", }, { + name: "test2", env: Env{"FOO", "BAR="}, expected: "FOO=BAR=", }, { + name: "test3", env: Env{"FOO", ""}, expected: "FOO=", }, } - for _, test := range tests { - if s := test.env.String(); s != test.expected { - t.Errorf("%v: expected string %q, got %q", test.env, test.expected, s) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if s := tt.env.String(); s != tt.expected { + t.Errorf("%v: expected string %q, got %q", tt.env, tt.expected, s) + } + }) } } func TestEnvListToSlice(t *testing.T) { tests := []struct { + name string env EnvList expected []string }{ { + name: "test1", env: EnvList{ {"FOO", "BAR"}, {"ZEE", "YO"}, @@ -64,20 +72,24 @@ func TestEnvListToSlice(t *testing.T) { expected: []string{"FOO=BAR", "ZEE=YO", "ONE=1", "EQUALS===", "EMPTY="}, }, } - for _, test := range tests { - if s := test.env.Slice(); !reflect.DeepEqual(test.expected, s) { - t.Errorf("%v: expected %v, got %v", test.env, test.expected, s) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if s := tt.env.Slice(); !reflect.DeepEqual(tt.expected, s) { + t.Errorf("%v: expected %v, got %v", tt.env, tt.expected, s) + } + }) } } func TestAddToEnvList(t *testing.T) { tests := []struct { + name string add []string expected EnvList }{ { - add: []string{"FOO=BAR", "EMPTY=", "EQUALS===", "JUSTNAME"}, + name: "test1", + add: []string{"FOO=BAR", "EMPTY=", "EQUALS===", "JUSTNAME"}, expected: EnvList{ {"FOO", "BAR"}, {"EMPTY", ""}, @@ -86,11 +98,13 @@ func TestAddToEnvList(t *testing.T) { }, }, } - for _, test := range tests { - env := EnvList{}.Merge(test.add...) - if !reflect.DeepEqual(test.expected, env) { - t.Errorf("%v: expected %v, got %v", test.add, test.expected, env) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + env := EnvList{}.Merge(tt.add...) + if !reflect.DeepEqual(tt.expected, env) { + t.Errorf("%v: expected %v, got %v", tt.add, tt.expected, env) + } + }) } } @@ -102,37 +116,45 @@ func TestFlagToEnv(t *testing.T) { flags.Parse([]string{"--from-file=nondefault"}) tests := []struct { + name string flag *pflag.Flag prefix string expected Env }{ { + name: "test1", flag: flags.Lookup("test"), expected: Env{"TEST", "ok"}, }, { + name: "test2", flag: flags.Lookup("kube-master"), expected: Env{"KUBE_MASTER", "http://something"}, }, { + name: "test3", prefix: "KUBECTL_", flag: flags.Lookup("from-file"), expected: Env{"KUBECTL_FROM_FILE", "nondefault"}, }, } - for _, test := range tests { - if env := FlagToEnv(test.flag, test.prefix); !reflect.DeepEqual(test.expected, env) { - t.Errorf("%v: expected %v, got %v", test.flag.Name, test.expected, env) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if env := FlagToEnv(tt.flag, tt.prefix); !reflect.DeepEqual(tt.expected, env) { + t.Errorf("%v: expected %v, got %v", tt.flag.Name, tt.expected, env) + } + }) } } func TestPluginDescriptorEnvProvider(t *testing.T) { tests := []struct { + name string plugin *Plugin expected EnvList }{ { + name: "test1", plugin: &Plugin{ Description: Description{ Name: "test", @@ -149,14 +171,16 @@ func TestPluginDescriptorEnvProvider(t *testing.T) { }, }, } - for _, test := range tests { - provider := &PluginDescriptorEnvProvider{ - Plugin: test.plugin, - } - env, _ := provider.Env() - if !reflect.DeepEqual(test.expected, env) { - t.Errorf("%v: expected %v, got %v", test.plugin.Name, test.expected, env) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + provider := &PluginDescriptorEnvProvider{ + Plugin: tt.plugin, + } + env, _ := provider.Env() + if !reflect.DeepEqual(tt.expected, env) { + t.Errorf("%v: expected %v, got %v", tt.plugin.Name, tt.expected, env) + } + }) } } diff --git a/pkg/kubectl/plugins/plugins_test.go b/pkg/kubectl/plugins/plugins_test.go index b5a43573ee..9f707f54b1 100644 --- a/pkg/kubectl/plugins/plugins_test.go +++ b/pkg/kubectl/plugins/plugins_test.go @@ -20,10 +20,12 @@ import "testing" func TestPlugin(t *testing.T) { tests := []struct { + name string plugin *Plugin expectedErr error }{ { + name: "test1", plugin: &Plugin{ Description: Description{ Name: "test", @@ -33,6 +35,7 @@ func TestPlugin(t *testing.T) { }, }, { + name: "test2", plugin: &Plugin{ Description: Description{ Name: "test", @@ -42,10 +45,12 @@ func TestPlugin(t *testing.T) { expectedErr: ErrIncompletePlugin, }, { + name: "test3", plugin: &Plugin{}, expectedErr: ErrIncompletePlugin, }, { + name: "test4", plugin: &Plugin{ Description: Description{ Name: "test spaces", @@ -56,6 +61,7 @@ func TestPlugin(t *testing.T) { expectedErr: ErrInvalidPluginName, }, { + name: "test5", plugin: &Plugin{ Description: Description{ Name: "test", @@ -71,6 +77,7 @@ func TestPlugin(t *testing.T) { expectedErr: ErrIncompleteFlag, }, { + name: "test6", plugin: &Plugin{ Description: Description{ Name: "test", @@ -87,6 +94,7 @@ func TestPlugin(t *testing.T) { expectedErr: ErrInvalidFlagName, }, { + name: "test7", plugin: &Plugin{ Description: Description{ Name: "test", @@ -104,6 +112,7 @@ func TestPlugin(t *testing.T) { expectedErr: ErrInvalidFlagShorthand, }, { + name: "test8", plugin: &Plugin{ Description: Description{ Name: "test", @@ -121,6 +130,7 @@ func TestPlugin(t *testing.T) { expectedErr: ErrInvalidFlagShorthand, }, { + name: "test9", plugin: &Plugin{ Description: Description{ Name: "test", @@ -160,10 +170,12 @@ func TestPlugin(t *testing.T) { }, } - for _, test := range tests { - err := test.plugin.Validate() - if err != test.expectedErr { - t.Errorf("%s: expected error %v, got %v", test.plugin.Name, test.expectedErr, err) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.plugin.Validate() + if err != tt.expectedErr { + t.Errorf("%s: expected error %v, got %v", tt.plugin.Name, tt.expectedErr, err) + } + }) } } diff --git a/pkg/kubectl/plugins/runner_test.go b/pkg/kubectl/plugins/runner_test.go index ae37814876..f6d5f32254 100644 --- a/pkg/kubectl/plugins/runner_test.go +++ b/pkg/kubectl/plugins/runner_test.go @@ -50,33 +50,34 @@ func TestExecRunner(t *testing.T) { os.Setenv("KUBECTL_PLUGINS_TEST", "ok") defer os.Unsetenv("KUBECTL_PLUGINS_TEST") - for _, test := range tests { - streams, _, outBuf, _ := genericclioptions.NewTestIOStreams() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + streams, _, outBuf, _ := genericclioptions.NewTestIOStreams() - plugin := &Plugin{ - Description: Description{ - Name: test.name, - ShortDesc: "Test Runner Plugin", - Command: test.command, - }, - } + plugin := &Plugin{ + Description: Description{ + Name: tt.name, + ShortDesc: "Test Runner Plugin", + Command: tt.command, + }, + } - ctx := RunningContext{ - IOStreams: streams, - WorkingDir: ".", - EnvProvider: &EmptyEnvProvider{}, - } + ctx := RunningContext{ + IOStreams: streams, + WorkingDir: ".", + EnvProvider: &EmptyEnvProvider{}, + } - runner := &ExecPluginRunner{} - err := runner.Run(plugin, ctx) + runner := &ExecPluginRunner{} + err := runner.Run(plugin, ctx) - if outBuf.String() != test.expectedMsg { - t.Errorf("%s: unexpected output: %q", test.name, outBuf.String()) - } + if outBuf.String() != tt.expectedMsg { + t.Errorf("%s: unexpected output: %q", tt.name, outBuf.String()) + } - if err != nil && err.Error() != test.expectedErr { - t.Errorf("%s: unexpected err output: %v", test.name, err) - } + if err != nil && err.Error() != tt.expectedErr { + t.Errorf("%s: unexpected err output: %v", tt.name, err) + } + }) } - } diff --git a/pkg/kubectl/priorityclass_test.go b/pkg/kubectl/priorityclass_test.go index 2702ce33bb..1181732b49 100644 --- a/pkg/kubectl/priorityclass_test.go +++ b/pkg/kubectl/priorityclass_test.go @@ -25,12 +25,14 @@ import ( ) func TestPriorityClassV1Generator(t *testing.T) { - tests := map[string]struct { + tests := []struct { + name string params map[string]interface{} expected *scheduling.PriorityClass expectErr bool }{ - "test valid case": { + { + name: "test valid case", params: map[string]interface{}{ "name": "foo", "value": int32(1000), @@ -47,7 +49,8 @@ func TestPriorityClassV1Generator(t *testing.T) { }, expectErr: false, }, - "test valid case that as default priority": { + { + name: "test valid case that as default priority", params: map[string]interface{}{ "name": "foo", "value": int32(1000), @@ -64,7 +67,8 @@ func TestPriorityClassV1Generator(t *testing.T) { }, expectErr: false, }, - "test missing required param": { + { + name: "test missing required param", params: map[string]interface{}{ "name": "foo", "global-default": true, @@ -75,16 +79,18 @@ func TestPriorityClassV1Generator(t *testing.T) { } generator := PriorityClassV1Generator{} - for name, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("%s: unexpected error: %v", name, err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*scheduling.PriorityClass), test.expected) { - t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", name, test.expected, obj.(*scheduling.PriorityClass)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("%s: unexpected error: %v", tt.name, err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*scheduling.PriorityClass), tt.expected) { + t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", tt.name, tt.expected, obj.(*scheduling.PriorityClass)) + } + }) } } diff --git a/pkg/kubectl/proxy/proxy_server_test.go b/pkg/kubectl/proxy/proxy_server_test.go index 4a85501e2c..5f46af991c 100644 --- a/pkg/kubectl/proxy/proxy_server_test.go +++ b/pkg/kubectl/proxy/proxy_server_test.go @@ -33,6 +33,7 @@ import ( func TestAccept(t *testing.T) { tests := []struct { + name string acceptPaths string rejectPaths string acceptHosts string @@ -44,6 +45,7 @@ func TestAccept(t *testing.T) { }{ { + name: "test1", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -54,6 +56,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test2", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -64,6 +67,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test3", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -74,6 +78,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test4", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -84,6 +89,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test5", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -94,6 +100,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test7", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -104,6 +111,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test8", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -114,6 +122,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test9", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -124,6 +133,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test10", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -134,6 +144,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test11", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -144,6 +155,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test12", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -154,6 +166,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test13", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -164,6 +177,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test14", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -174,6 +188,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test15", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -184,6 +199,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test16", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -194,6 +210,7 @@ func TestAccept(t *testing.T) { expectAccept: true, }, { + name: "test17", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -204,6 +221,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test18", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -214,6 +232,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test19", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -224,6 +243,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test20", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -234,6 +254,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test21", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -244,6 +265,7 @@ func TestAccept(t *testing.T) { expectAccept: false, }, { + name: "test22", acceptPaths: DefaultPathAcceptRE, rejectPaths: DefaultPathRejectRE, acceptHosts: DefaultHostAcceptRE, @@ -254,52 +276,61 @@ func TestAccept(t *testing.T) { expectAccept: false, }, } - for _, test := range tests { - filter := &FilterServer{ - AcceptPaths: MakeRegexpArrayOrDie(test.acceptPaths), - RejectPaths: MakeRegexpArrayOrDie(test.rejectPaths), - AcceptHosts: MakeRegexpArrayOrDie(test.acceptHosts), - RejectMethods: MakeRegexpArrayOrDie(test.rejectMethods), - } - accept := filter.accept(test.method, test.path, test.host) - if accept != test.expectAccept { - t.Errorf("expected: %v, got %v for %#v", test.expectAccept, accept, test) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + filter := &FilterServer{ + AcceptPaths: MakeRegexpArrayOrDie(tt.acceptPaths), + RejectPaths: MakeRegexpArrayOrDie(tt.rejectPaths), + AcceptHosts: MakeRegexpArrayOrDie(tt.acceptHosts), + RejectMethods: MakeRegexpArrayOrDie(tt.rejectMethods), + } + accept := filter.accept(tt.method, tt.path, tt.host) + if accept != tt.expectAccept { + t.Errorf("expected: %v, got %v for %#v", tt.expectAccept, accept, tt) + } + }) } } func TestRegexpMatch(t *testing.T) { tests := []struct { + name string str string regexps string expectMatch bool }{ { + name: "test1", str: "foo", regexps: "bar,.*", expectMatch: true, }, { + name: "test2", str: "foo", regexps: "bar,fo.*", expectMatch: true, }, { + name: "test3", str: "bar", regexps: "bar,fo.*", expectMatch: true, }, { + name: "test4", str: "baz", regexps: "bar,fo.*", expectMatch: false, }, } - for _, test := range tests { - match := matchesRegexp(test.str, MakeRegexpArrayOrDie(test.regexps)) - if test.expectMatch != match { - t.Errorf("expected: %v, found: %v, for %s and %v", test.expectMatch, match, test.str, test.regexps) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + match := matchesRegexp(tt.str, MakeRegexpArrayOrDie(tt.regexps)) + if tt.expectMatch != match { + t.Errorf("expected: %v, found: %v, for %s and %v", tt.expectMatch, match, tt.str, tt.regexps) + } + }) } } @@ -363,29 +394,31 @@ func TestAPIRequests(t *testing.T) { target.Path = "/" proxy := newProxy(target) - tests := []struct{ method, body string }{ - {"GET", ""}, - {"DELETE", ""}, - {"POST", "test payload"}, - {"PUT", "test payload"}, + tests := []struct{ name, method, body string }{ + {"test1", "GET", ""}, + {"test2", "DELETE", ""}, + {"test3", "POST", "test payload"}, + {"test4", "PUT", "test payload"}, } const path = "/api/test?fields=ID%3Dfoo&labels=key%3Dvalue" for i, tt := range tests { - r, err := http.NewRequest(tt.method, path, strings.NewReader(tt.body)) - if err != nil { - t.Errorf("error creating request: %v", err) - continue - } - w := httptest.NewRecorder() - proxy.ServeHTTP(w, r) - if w.Code != http.StatusOK { - t.Errorf("%d: proxy.ServeHTTP w.Code = %d; want %d", i, w.Code, http.StatusOK) - } - want := strings.Join([]string{tt.method, path, tt.body}, " ") - if w.Body.String() != want { - t.Errorf("%d: response body = %q; want %q", i, w.Body.String(), want) - } + t.Run(tt.name, func(t *testing.T) { + r, err := http.NewRequest(tt.method, path, strings.NewReader(tt.body)) + if err != nil { + t.Errorf("error creating request: %v", err) + return + } + w := httptest.NewRecorder() + proxy.ServeHTTP(w, r) + if w.Code != http.StatusOK { + t.Errorf("%d: proxy.ServeHTTP w.Code = %d; want %d", i, w.Code, http.StatusOK) + } + want := strings.Join([]string{tt.method, path, tt.body}, " ") + if w.Body.String() != want { + t.Errorf("%d: response body = %q; want %q", i, w.Body.String(), want) + } + }) } } @@ -396,48 +429,49 @@ func TestPathHandling(t *testing.T) { defer ts.Close() table := []struct { + name string prefix string reqPath string expectPath string }{ - {"/api/", "/metrics", "404 page not found\n"}, - {"/api/", "/api/metrics", "/api/metrics"}, - {"/api/", "/api/v1/pods/", "/api/v1/pods/"}, - {"/", "/metrics", "/metrics"}, - {"/", "/api/v1/pods/", "/api/v1/pods/"}, - {"/custom/", "/metrics", "404 page not found\n"}, - {"/custom/", "/api/metrics", "404 page not found\n"}, - {"/custom/", "/api/v1/pods/", "404 page not found\n"}, - {"/custom/", "/custom/api/metrics", "/api/metrics"}, - {"/custom/", "/custom/api/v1/pods/", "/api/v1/pods/"}, + {"test1", "/api/", "/metrics", "404 page not found\n"}, + {"test2", "/api/", "/api/metrics", "/api/metrics"}, + {"test3", "/api/", "/api/v1/pods/", "/api/v1/pods/"}, + {"test4", "/", "/metrics", "/metrics"}, + {"test5", "/", "/api/v1/pods/", "/api/v1/pods/"}, + {"test6", "/custom/", "/metrics", "404 page not found\n"}, + {"test7", "/custom/", "/api/metrics", "404 page not found\n"}, + {"test8", "/custom/", "/api/v1/pods/", "404 page not found\n"}, + {"test9", "/custom/", "/custom/api/metrics", "/api/metrics"}, + {"test10", "/custom/", "/custom/api/v1/pods/", "/api/v1/pods/"}, } cc := &rest.Config{ Host: ts.URL, } - for _, item := range table { - func() { - p, err := NewServer("", item.prefix, "/not/used/for/this/test", nil, cc) + for _, tt := range table { + t.Run(tt.name, func(t *testing.T) { + p, err := NewServer("", tt.prefix, "/not/used/for/this/test", nil, cc) if err != nil { - t.Fatalf("%#v: %v", item, err) + t.Fatalf("%#v: %v", tt, err) } pts := httptest.NewServer(p.handler) defer pts.Close() - r, err := http.Get(pts.URL + item.reqPath) + r, err := http.Get(pts.URL + tt.reqPath) if err != nil { - t.Fatalf("%#v: %v", item, err) + t.Fatalf("%#v: %v", tt, err) } body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { - t.Fatalf("%#v: %v", item, err) + t.Fatalf("%#v: %v", tt, err) } - if e, a := item.expectPath, string(body); e != a { - t.Errorf("%#v: Wanted %q, got %q", item, e, a) + if e, a := tt.expectPath, string(body); e != a { + t.Errorf("%#v: Wanted %q, got %q", tt, e, a) } - }() + }) } } diff --git a/pkg/kubectl/quota_test.go b/pkg/kubectl/quota_test.go index 990a9379d7..46fe804962 100644 --- a/pkg/kubectl/quota_test.go +++ b/pkg/kubectl/quota_test.go @@ -31,12 +31,14 @@ func TestQuotaGenerate(t *testing.T) { t.Errorf("unexpected error: %v", err) } - tests := map[string]struct { + tests := []struct { + name string params map[string]interface{} expected *v1.ResourceQuota expectErr bool }{ - "test-valid-use": { + { + name: "test-valid-use", params: map[string]interface{}{ "name": "foo", "hard": hard, @@ -49,13 +51,15 @@ func TestQuotaGenerate(t *testing.T) { }, expectErr: false, }, - "test-missing-required-param": { + { + name: "test-missing-required-param", params: map[string]interface{}{ "name": "foo", }, expectErr: true, }, - "test-valid-scopes": { + { + name: "test-valid-scopes", params: map[string]interface{}{ "name": "foo", "hard": hard, @@ -75,7 +79,8 @@ func TestQuotaGenerate(t *testing.T) { }, expectErr: false, }, - "test-empty-scopes": { + { + name: "test-empty-scopes", params: map[string]interface{}{ "name": "foo", "hard": hard, @@ -89,7 +94,8 @@ func TestQuotaGenerate(t *testing.T) { }, expectErr: false, }, - "test-invalid-scopes": { + { + name: "test-invalid-scopes", params: map[string]interface{}{ "name": "foo", "hard": hard, @@ -100,16 +106,18 @@ func TestQuotaGenerate(t *testing.T) { } generator := ResourceQuotaGeneratorV1{} - for name, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("%s: unexpected error: %v", name, err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.ResourceQuota), test.expected) { - t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", name, test.expected, obj.(*v1.ResourceQuota)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("%s: unexpected error: %v", tt.name, err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.ResourceQuota), tt.expected) { + t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", tt.name, tt.expected, obj.(*v1.ResourceQuota)) + } + }) } } diff --git a/pkg/kubectl/rolebinding_test.go b/pkg/kubectl/rolebinding_test.go index 01504f2680..ccc2ba5c63 100644 --- a/pkg/kubectl/rolebinding_test.go +++ b/pkg/kubectl/rolebinding_test.go @@ -25,12 +25,14 @@ import ( ) func TestRoleBindingGenerate(t *testing.T) { - tests := map[string]struct { + tests := []struct { + name string params map[string]interface{} expectErrMsg string expectBinding *rbac.RoleBinding }{ - "test-missing-name": { + { + name: "test-missing-name", params: map[string]interface{}{ "role": "fake-role", "groups": []string{"fake-group"}, @@ -38,7 +40,8 @@ func TestRoleBindingGenerate(t *testing.T) { }, expectErrMsg: "Parameter: name is required", }, - "test-missing-role-and-clusterrole": { + { + name: "test-missing-role-and-clusterrole", params: map[string]interface{}{ "name": "fake-binding", "group": []string{"fake-group"}, @@ -46,7 +49,8 @@ func TestRoleBindingGenerate(t *testing.T) { }, expectErrMsg: "exactly one of clusterrole or role must be specified", }, - "test-both-role-and-clusterrole-provided": { + { + name: "test-both-role-and-clusterrole-provided", params: map[string]interface{}{ "name": "fake-binding", "role": "fake-role", @@ -56,7 +60,8 @@ func TestRoleBindingGenerate(t *testing.T) { }, expectErrMsg: "exactly one of clusterrole or role must be specified", }, - "test-invalid-parameter-type": { + { + name: "test-invalid-parameter-type", params: map[string]interface{}{ "name": "fake-binding", "role": []string{"fake-role"}, @@ -65,7 +70,8 @@ func TestRoleBindingGenerate(t *testing.T) { }, expectErrMsg: "expected string, saw [fake-role] for 'role'", }, - "test-invalid-serviceaccount": { + { + name: "test-invalid-serviceaccount", params: map[string]interface{}{ "name": "fake-binding", "role": "fake-role", @@ -74,7 +80,8 @@ func TestRoleBindingGenerate(t *testing.T) { }, expectErrMsg: "serviceaccount must be :", }, - "test-valid-case": { + { + name: "test-valid-case", params: map[string]interface{}{ "name": "fake-binding", "role": "fake-role", @@ -113,23 +120,25 @@ func TestRoleBindingGenerate(t *testing.T) { } generator := RoleBindingGeneratorV1{} - for name, test := range tests { - obj, err := generator.Generate(test.params) - switch { - case test.expectErrMsg != "" && err != nil: - if err.Error() != test.expectErrMsg { - t.Errorf("test '%s': expect error '%s', but saw '%s'", name, test.expectErrMsg, err.Error()) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + switch { + case tt.expectErrMsg != "" && err != nil: + if err.Error() != tt.expectErrMsg { + t.Errorf("test '%s': expect error '%s', but saw '%s'", tt.name, tt.expectErrMsg, err.Error()) + } + return + case tt.expectErrMsg != "" && err == nil: + t.Errorf("test '%s': expected error '%s' and didn't get one", tt.name, tt.expectErrMsg) + return + case tt.expectErrMsg == "" && err != nil: + t.Errorf("test '%s': unexpected error %s", tt.name, err.Error()) + return } - continue - case test.expectErrMsg != "" && err == nil: - t.Errorf("test '%s': expected error '%s' and didn't get one", name, test.expectErrMsg) - continue - case test.expectErrMsg == "" && err != nil: - t.Errorf("test '%s': unexpected error %s", name, err.Error()) - continue - } - if !reflect.DeepEqual(obj.(*rbac.RoleBinding), test.expectBinding) { - t.Errorf("test '%s': expected:\n%#v\nsaw:\n%#v", name, test.expectBinding, obj.(*rbac.RoleBinding)) - } + if !reflect.DeepEqual(obj.(*rbac.RoleBinding), tt.expectBinding) { + t.Errorf("test '%s': expected:\n%#v\nsaw:\n%#v", tt.name, tt.expectBinding, obj.(*rbac.RoleBinding)) + } + }) } } diff --git a/pkg/kubectl/rolling_updater_test.go b/pkg/kubectl/rolling_updater_test.go index 68c535bab6..92c3b90450 100644 --- a/pkg/kubectl/rolling_updater_test.go +++ b/pkg/kubectl/rolling_updater_test.go @@ -748,106 +748,108 @@ Scaling foo-v2 up to 2 }, } - for i, test := range tests { + for i, tt := range tests { // Extract expectations into some makeshift FIFOs so they can be returned // in the correct order from the right places. This lets scale downs be // expressed a single event even though the data is used from multiple // interface calls. - oldReady := []int{} - newReady := []int{} - upTo := []int{} - downTo := []int{} - for _, event := range test.expected { - switch e := event.(type) { - case down: - oldReady = append(oldReady, e.oldReady) - newReady = append(newReady, e.newReady) - if !e.noop { - downTo = append(downTo, e.to) + t.Run(tt.name, func(t *testing.T) { + oldReady := []int{} + newReady := []int{} + upTo := []int{} + downTo := []int{} + for _, event := range tt.expected { + switch e := event.(type) { + case down: + oldReady = append(oldReady, e.oldReady) + newReady = append(newReady, e.newReady) + if !e.noop { + downTo = append(downTo, e.to) + } + case up: + upTo = append(upTo, e.to) } - case up: - upTo = append(upTo, e.to) } - } - // Make a way to get the next item from our FIFOs. Returns -1 if the array - // is empty. - next := func(s *[]int) int { - slice := *s - v := -1 - if len(slice) > 0 { - v = slice[0] - if len(slice) > 1 { - *s = slice[1:] - } else { - *s = []int{} + // Make a way to get the next item from our FIFOs. Returns -1 if the array + // is empty. + next := func(s *[]int) int { + slice := *s + v := -1 + if len(slice) > 0 { + v = slice[0] + if len(slice) > 1 { + *s = slice[1:] + } else { + *s = []int{} + } } + return v } - return v - } - t.Logf("running test %d (%s) (up: %v, down: %v, oldReady: %v, newReady: %v)", i, test.name, upTo, downTo, oldReady, newReady) - updater := &RollingUpdater{ - ns: "default", - scaleAndWait: func(rc *api.ReplicationController, retry *RetryParams, wait *RetryParams) (*api.ReplicationController, error) { - // Return a scale up or scale down expectation depending on the rc, - // and throw errors if there is no expectation expressed for this - // call. - expected := -1 - switch { - case rc == test.newRc: - t.Logf("scaling up %s to %d", rc.Name, rc.Spec.Replicas) - expected = next(&upTo) - case rc == test.oldRc: - t.Logf("scaling down %s to %d", rc.Name, rc.Spec.Replicas) - expected = next(&downTo) - } - if expected == -1 { - t.Fatalf("unexpected scale of %s to %d", rc.Name, rc.Spec.Replicas) - } else if e, a := expected, int(rc.Spec.Replicas); e != a { - t.Fatalf("expected scale of %s to %d, got %d", rc.Name, e, a) - } - // Simulate the scale. - rc.Status.Replicas = rc.Spec.Replicas - return rc, nil - }, - getOrCreateTargetController: func(controller *api.ReplicationController, sourceId string) (*api.ReplicationController, bool, error) { - // Simulate a create vs. update of an existing controller. - return test.newRc, test.newRcExists, nil - }, - cleanup: func(oldRc, newRc *api.ReplicationController, config *RollingUpdaterConfig) error { - return nil - }, - } - // Set up a mock readiness check which handles the test assertions. - updater.getReadyPods = func(oldRc, newRc *api.ReplicationController, minReadySecondsDeadline int32) (int32, int32, error) { - // Return simulated readiness, and throw an error if this call has no - // expectations defined. - oldReady := next(&oldReady) - newReady := next(&newReady) - if oldReady == -1 || newReady == -1 { - t.Fatalf("unexpected getReadyPods call for:\noldRc: %#v\nnewRc: %#v", oldRc, newRc) + t.Logf("running test %d (%s) (up: %v, down: %v, oldReady: %v, newReady: %v)", i, tt.name, upTo, downTo, oldReady, newReady) + updater := &RollingUpdater{ + ns: "default", + scaleAndWait: func(rc *api.ReplicationController, retry *RetryParams, wait *RetryParams) (*api.ReplicationController, error) { + // Return a scale up or scale down expectation depending on the rc, + // and throw errors if there is no expectation expressed for this + // call. + expected := -1 + switch { + case rc == tt.newRc: + t.Logf("scaling up %s to %d", rc.Name, rc.Spec.Replicas) + expected = next(&upTo) + case rc == tt.oldRc: + t.Logf("scaling down %s to %d", rc.Name, rc.Spec.Replicas) + expected = next(&downTo) + } + if expected == -1 { + t.Fatalf("unexpected scale of %s to %d", rc.Name, rc.Spec.Replicas) + } else if e, a := expected, int(rc.Spec.Replicas); e != a { + t.Fatalf("expected scale of %s to %d, got %d", rc.Name, e, a) + } + // Simulate the scale. + rc.Status.Replicas = rc.Spec.Replicas + return rc, nil + }, + getOrCreateTargetController: func(controller *api.ReplicationController, sourceId string) (*api.ReplicationController, bool, error) { + // Simulate a create vs. update of an existing controller. + return tt.newRc, tt.newRcExists, nil + }, + cleanup: func(oldRc, newRc *api.ReplicationController, config *RollingUpdaterConfig) error { + return nil + }, } - return int32(oldReady), int32(newReady), nil - } - var buffer bytes.Buffer - config := &RollingUpdaterConfig{ - Out: &buffer, - OldRc: test.oldRc, - NewRc: test.newRc, - UpdatePeriod: 0, - Interval: time.Millisecond, - Timeout: time.Millisecond, - CleanupPolicy: DeleteRollingUpdateCleanupPolicy, - MaxUnavailable: test.maxUnavail, - MaxSurge: test.maxSurge, - } - err := updater.Update(config) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if buffer.String() != test.output { - t.Errorf("Bad output. expected:\n%s\ngot:\n%s", test.output, buffer.String()) - } + // Set up a mock readiness check which handles the test assertions. + updater.getReadyPods = func(oldRc, newRc *api.ReplicationController, minReadySecondsDeadline int32) (int32, int32, error) { + // Return simulated readiness, and throw an error if this call has no + // expectations defined. + oldReady := next(&oldReady) + newReady := next(&newReady) + if oldReady == -1 || newReady == -1 { + t.Fatalf("unexpected getReadyPods call for:\noldRc: %#v\nnewRc: %#v", oldRc, newRc) + } + return int32(oldReady), int32(newReady), nil + } + var buffer bytes.Buffer + config := &RollingUpdaterConfig{ + Out: &buffer, + OldRc: tt.oldRc, + NewRc: tt.newRc, + UpdatePeriod: 0, + Interval: time.Millisecond, + Timeout: time.Millisecond, + CleanupPolicy: DeleteRollingUpdateCleanupPolicy, + MaxUnavailable: tt.maxUnavail, + MaxSurge: tt.maxSurge, + } + err := updater.Update(config) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if buffer.String() != tt.output { + t.Errorf("Bad output. expected:\n%s\ngot:\n%s", tt.output, buffer.String()) + } + }) } } @@ -942,14 +944,15 @@ func TestUpdate_assignOriginalAnnotation(t *testing.T) { func TestRollingUpdater_multipleContainersInPod(t *testing.T) { tests := []struct { - oldRc *api.ReplicationController - newRc *api.ReplicationController - + name string + oldRc *api.ReplicationController + newRc *api.ReplicationController container string image string deploymentKey string }{ { + name: "test1", oldRc: &api.ReplicationController{ ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceDefault, @@ -1015,6 +1018,7 @@ func TestRollingUpdater_multipleContainersInPod(t *testing.T) { deploymentKey: "dk", }, { + name: "test2", oldRc: &api.ReplicationController{ ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceDefault, @@ -1073,35 +1077,37 @@ func TestRollingUpdater_multipleContainersInPod(t *testing.T) { }, } - for _, test := range tests { - fake := fake.NewSimpleClientset(test.oldRc) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fake := fake.NewSimpleClientset(tt.oldRc) - codec := testapi.Default.Codec() + codec := testapi.Default.Codec() - deploymentHash, err := util.HashObject(test.newRc, codec) - if err != nil { - t.Errorf("unexpected error: %v", err) - } + deploymentHash, err := util.HashObject(tt.newRc, codec) + if err != nil { + t.Errorf("unexpected error: %v", err) + } - test.newRc.Spec.Selector[test.deploymentKey] = deploymentHash - test.newRc.Spec.Template.Labels[test.deploymentKey] = deploymentHash - test.newRc.Name = fmt.Sprintf("%s-%s", test.newRc.Name, deploymentHash) + tt.newRc.Spec.Selector[tt.deploymentKey] = deploymentHash + tt.newRc.Spec.Template.Labels[tt.deploymentKey] = deploymentHash + tt.newRc.Name = fmt.Sprintf("%s-%s", tt.newRc.Name, deploymentHash) - config := &NewControllerConfig{ - Namespace: metav1.NamespaceDefault, - OldName: test.oldRc.ObjectMeta.Name, - NewName: test.newRc.ObjectMeta.Name, - Image: test.image, - Container: test.container, - DeploymentKey: test.deploymentKey, - } - updatedRc, err := CreateNewControllerFromCurrentController(fake.Core(), codec, config) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !reflect.DeepEqual(updatedRc, test.newRc) { - t.Errorf("expected:\n%#v\ngot:\n%#v\n", test.newRc, updatedRc) - } + config := &NewControllerConfig{ + Namespace: metav1.NamespaceDefault, + OldName: tt.oldRc.ObjectMeta.Name, + NewName: tt.newRc.ObjectMeta.Name, + Image: tt.image, + Container: tt.container, + DeploymentKey: tt.deploymentKey, + } + updatedRc, err := CreateNewControllerFromCurrentController(fake.Core(), codec, config) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if !reflect.DeepEqual(updatedRc, tt.newRc) { + t.Errorf("expected:\n%#v\ngot:\n%#v\n", tt.newRc, updatedRc) + } + }) } } @@ -1163,36 +1169,38 @@ func TestRollingUpdater_cleanupWithClients(t *testing.T) { //}, } - for _, test := range tests { - objs := []runtime.Object{rc} - objs = append(objs, test.responses...) - fake := fake.NewSimpleClientset(objs...) - updater := &RollingUpdater{ - ns: "default", - rcClient: fake.Core(), - podClient: fake.Core(), - } - config := &RollingUpdaterConfig{ - Out: ioutil.Discard, - OldRc: rc, - NewRc: rcExisting, - UpdatePeriod: 0, - Interval: time.Millisecond, - Timeout: time.Millisecond, - CleanupPolicy: test.policy, - } - err := updater.cleanupWithClients(rc, rcExisting, config) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(fake.Actions()) != len(test.expected) { - t.Fatalf("%s: unexpected actions: %v, expected %v", test.name, fake.Actions(), test.expected) - } - for j, action := range fake.Actions() { - if e, a := test.expected[j], action.GetVerb(); e != a { - t.Errorf("%s: unexpected action: expected %s, got %s", test.name, e, a) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + objs := []runtime.Object{rc} + objs = append(objs, tt.responses...) + fake := fake.NewSimpleClientset(objs...) + updater := &RollingUpdater{ + ns: "default", + rcClient: fake.Core(), + podClient: fake.Core(), } - } + config := &RollingUpdaterConfig{ + Out: ioutil.Discard, + OldRc: rc, + NewRc: rcExisting, + UpdatePeriod: 0, + Interval: time.Millisecond, + Timeout: time.Millisecond, + CleanupPolicy: tt.policy, + } + err := updater.cleanupWithClients(rc, rcExisting, config) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if len(fake.Actions()) != len(tt.expected) { + t.Fatalf("%s: unexpected actions: %v, expected %v", tt.name, fake.Actions(), tt.expected) + } + for j, action := range fake.Actions() { + if e, a := tt.expected[j], action.GetVerb(); e != a { + t.Errorf("%s: unexpected action: expected %s, got %s", tt.name, e, a) + } + } + }) } } @@ -1303,18 +1311,20 @@ func TestFindSourceController(t *testing.T) { expectedController: &ctrl3, }, } - for _, test := range tests { - fakeClient := fake.NewSimpleClientset(test.list) - ctrl, err := FindSourceController(fakeClient.Core(), "default", test.name) - if test.expectError && err == nil { - t.Errorf("unexpected non-error") - } - if !test.expectError && err != nil { - t.Errorf("unexpected error") - } - if !reflect.DeepEqual(ctrl, test.expectedController) { - t.Errorf("expected:\n%v\ngot:\n%v\n", test.expectedController, ctrl) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fakeClient := fake.NewSimpleClientset(tt.list) + ctrl, err := FindSourceController(fakeClient.Core(), "default", tt.name) + if tt.expectError && err == nil { + t.Errorf("unexpected non-error") + } + if !tt.expectError && err != nil { + t.Errorf("unexpected error") + } + if !reflect.DeepEqual(ctrl, tt.expectedController) { + t.Errorf("expected:\n%v\ngot:\n%v\n", tt.expectedController, ctrl) + } + }) } } @@ -1410,19 +1420,21 @@ func TestUpdateExistingReplicationController(t *testing.T) { }, }, } - for _, test := range tests { - buffer := &bytes.Buffer{} - fakeClient := fake.NewSimpleClientset(test.expectedRc) - rc, err := UpdateExistingReplicationController(fakeClient.Core(), fakeClient.Core(), test.rc, "default", test.name, test.deploymentKey, test.deploymentValue, buffer) - if !reflect.DeepEqual(rc, test.expectedRc) { - t.Errorf("expected:\n%#v\ngot:\n%#v\n", test.expectedRc, rc) - } - if test.expectErr && err == nil { - t.Errorf("unexpected non-error") - } - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + buffer := &bytes.Buffer{} + fakeClient := fake.NewSimpleClientset(tt.expectedRc) + rc, err := UpdateExistingReplicationController(fakeClient.Core(), fakeClient.Core(), tt.rc, "default", tt.name, tt.deploymentKey, tt.deploymentValue, buffer) + if !reflect.DeepEqual(rc, tt.expectedRc) { + t.Errorf("expected:\n%#v\ngot:\n%#v\n", tt.expectedRc, rc) + } + if tt.expectErr && err == nil { + t.Errorf("unexpected non-error") + } + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + }) } } @@ -1646,6 +1658,7 @@ func TestRollingUpdater_readyPods(t *testing.T) { } tests := []struct { + name string oldRc *api.ReplicationController newRc *api.ReplicationController // expectated old/new ready counts @@ -1665,6 +1678,7 @@ func TestRollingUpdater_readyPods(t *testing.T) { nowFn func() metav1.Time }{ { + name: "test1", oldRc: oldRc(4, 4), newRc: newRc(4, 4), oldReady: 4, @@ -1683,6 +1697,7 @@ func TestRollingUpdater_readyPods(t *testing.T) { }, }, { + name: "test2", oldRc: oldRc(4, 4), newRc: newRc(4, 4), oldReady: 0, @@ -1695,6 +1710,7 @@ func TestRollingUpdater_readyPods(t *testing.T) { }, }, { + name: "test3", oldRc: oldRc(4, 4), newRc: newRc(4, 4), oldReady: 1, @@ -1707,6 +1723,7 @@ func TestRollingUpdater_readyPods(t *testing.T) { }, }, { + name: "test4", oldRc: oldRc(4, 4), newRc: newRc(4, 4), oldReady: 0, @@ -1721,6 +1738,7 @@ func TestRollingUpdater_readyPods(t *testing.T) { nowFn: func() metav1.Time { return now }, }, { + name: "test5", oldRc: oldRc(4, 4), newRc: newRc(4, 4), oldReady: 1, @@ -1736,6 +1754,7 @@ func TestRollingUpdater_readyPods(t *testing.T) { podReadyTimeFn: func() metav1.Time { return now }, }, { + name: "test6", oldRc: oldRc(4, 4), newRc: newRc(4, 4), oldReady: 2, @@ -1749,51 +1768,53 @@ func TestRollingUpdater_readyPods(t *testing.T) { }, } - for i, test := range tests { - t.Logf("evaluating test %d", i) - if test.nowFn == nil { - test.nowFn = func() metav1.Time { return now } - } - if test.podReadyTimeFn == nil { - test.podReadyTimeFn = test.nowFn - } - // Populate the fake client with pods associated with their owners. - pods := []runtime.Object{} - for _, ready := range test.oldPods { - pod := mkpod(test.oldRc, ready, test.podReadyTimeFn()) - if test.oldPodDeletions > 0 { - now := metav1.Now() - pod.DeletionTimestamp = &now - test.oldPodDeletions-- + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Logf("evaluating test %d", i) + if tt.nowFn == nil { + tt.nowFn = func() metav1.Time { return now } } - pods = append(pods, pod) - } - for _, ready := range test.newPods { - pod := mkpod(test.newRc, ready, test.podReadyTimeFn()) - if test.newPodDeletions > 0 { - now := metav1.Now() - pod.DeletionTimestamp = &now - test.newPodDeletions-- + if tt.podReadyTimeFn == nil { + tt.podReadyTimeFn = tt.nowFn } - pods = append(pods, pod) - } - client := fake.NewSimpleClientset(pods...) + // Populate the fake client with pods associated with their owners. + pods := []runtime.Object{} + for _, ready := range tt.oldPods { + pod := mkpod(tt.oldRc, ready, tt.podReadyTimeFn()) + if tt.oldPodDeletions > 0 { + now := metav1.Now() + pod.DeletionTimestamp = &now + tt.oldPodDeletions-- + } + pods = append(pods, pod) + } + for _, ready := range tt.newPods { + pod := mkpod(tt.newRc, ready, tt.podReadyTimeFn()) + if tt.newPodDeletions > 0 { + now := metav1.Now() + pod.DeletionTimestamp = &now + tt.newPodDeletions-- + } + pods = append(pods, pod) + } + client := fake.NewSimpleClientset(pods...) - updater := &RollingUpdater{ - ns: "default", - rcClient: client.Core(), - podClient: client.Core(), - nowFn: test.nowFn, - } - oldReady, newReady, err := updater.readyPods(test.oldRc, test.newRc, test.minReadySeconds) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := test.oldReady, oldReady; e != a { - t.Errorf("expected old ready %d, got %d", e, a) - } - if e, a := test.newReady, newReady; e != a { - t.Errorf("expected new ready %d, got %d", e, a) - } + updater := &RollingUpdater{ + ns: "default", + rcClient: client.Core(), + podClient: client.Core(), + nowFn: tt.nowFn, + } + oldReady, newReady, err := updater.readyPods(tt.oldRc, tt.newRc, tt.minReadySeconds) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if e, a := tt.oldReady, oldReady; e != a { + t.Errorf("expected old ready %d, got %d", e, a) + } + if e, a := tt.newReady, newReady; e != a { + t.Errorf("expected new ready %d, got %d", e, a) + } + }) } } diff --git a/pkg/kubectl/rollout_status_test.go b/pkg/kubectl/rollout_status_test.go index 729709a7af..c77dd89335 100644 --- a/pkg/kubectl/rollout_status_test.go +++ b/pkg/kubectl/rollout_status_test.go @@ -28,6 +28,7 @@ import ( func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { + name string generation int64 specReplicas int32 status apps.DeploymentStatus @@ -35,6 +36,7 @@ func TestDeploymentStatusViewerStatus(t *testing.T) { done bool }{ { + name: "test1", generation: 0, specReplicas: 1, status: apps.DeploymentStatus{ @@ -49,6 +51,7 @@ func TestDeploymentStatusViewerStatus(t *testing.T) { done: false, }, { + name: "test2", generation: 1, specReplicas: 1, status: apps.DeploymentStatus{ @@ -63,6 +66,7 @@ func TestDeploymentStatusViewerStatus(t *testing.T) { done: false, }, { + name: "test3", generation: 1, specReplicas: 2, status: apps.DeploymentStatus{ @@ -77,6 +81,7 @@ func TestDeploymentStatusViewerStatus(t *testing.T) { done: false, }, { + name: "test4", generation: 1, specReplicas: 2, status: apps.DeploymentStatus{ @@ -91,6 +96,7 @@ func TestDeploymentStatusViewerStatus(t *testing.T) { done: true, }, { + name: "test5", generation: 2, specReplicas: 2, status: apps.DeploymentStatus{ @@ -107,46 +113,50 @@ func TestDeploymentStatusViewerStatus(t *testing.T) { } for _, test := range tests { - d := &apps.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "bar", - Name: "foo", - UID: "8764ae47-9092-11e4-8393-42010af018ff", - Generation: test.generation, - }, - Spec: apps.DeploymentSpec{ - Replicas: &test.specReplicas, - }, - Status: test.status, - } - client := fake.NewSimpleClientset(d).Apps() - dsv := &DeploymentStatusViewer{c: client} - msg, done, err := dsv.Status("bar", "foo", 0) - if err != nil { - t.Fatalf("DeploymentStatusViewer.Status(): %v", err) - } - if done != test.done || msg != test.msg { - t.Errorf("DeploymentStatusViewer.Status() for deployment with generation %d, %d replicas specified, and status %+v returned %q, %t, want %q, %t", - test.generation, - test.specReplicas, - test.status, - msg, - done, - test.msg, - test.done, - ) - } + t.Run(test.name, func(t *testing.T) { + d := &apps.Deployment{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "bar", + Name: "foo", + UID: "8764ae47-9092-11e4-8393-42010af018ff", + Generation: test.generation, + }, + Spec: apps.DeploymentSpec{ + Replicas: &test.specReplicas, + }, + Status: test.status, + } + client := fake.NewSimpleClientset(d).Apps() + dsv := &DeploymentStatusViewer{c: client} + msg, done, err := dsv.Status("bar", "foo", 0) + if err != nil { + t.Fatalf("DeploymentStatusViewer.Status(): %v", err) + } + if done != test.done || msg != test.msg { + t.Errorf("DeploymentStatusViewer.Status() for deployment with generation %d, %d replicas specified, and status %+v returned %q, %t, want %q, %t", + test.generation, + test.specReplicas, + test.status, + msg, + done, + test.msg, + test.done, + ) + } + }) } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { + name string generation int64 status apps.DaemonSetStatus msg string done bool }{ { + name: "test1", generation: 0, status: apps.DaemonSetStatus{ ObservedGeneration: 1, @@ -159,6 +169,7 @@ func TestDaemonSetStatusViewerStatus(t *testing.T) { done: false, }, { + name: "test2", generation: 1, status: apps.DaemonSetStatus{ ObservedGeneration: 1, @@ -171,6 +182,7 @@ func TestDaemonSetStatusViewerStatus(t *testing.T) { done: false, }, { + name: "test3", generation: 1, status: apps.DaemonSetStatus{ ObservedGeneration: 1, @@ -183,6 +195,7 @@ func TestDaemonSetStatusViewerStatus(t *testing.T) { done: true, }, { + name: "test4", generation: 2, status: apps.DaemonSetStatus{ ObservedGeneration: 1, @@ -196,40 +209,40 @@ func TestDaemonSetStatusViewerStatus(t *testing.T) { }, } - for i := range tests { - test := tests[i] - t.Logf("testing scenario %d", i) - d := &apps.DaemonSet{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "bar", - Name: "foo", - UID: "8764ae47-9092-11e4-8393-42010af018ff", - Generation: test.generation, - }, - Spec: apps.DaemonSetSpec{ - UpdateStrategy: apps.DaemonSetUpdateStrategy{ - Type: apps.RollingUpdateDaemonSetStrategyType, + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + d := &apps.DaemonSet{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "bar", + Name: "foo", + UID: "8764ae47-9092-11e4-8393-42010af018ff", + Generation: test.generation, }, - }, - Status: test.status, - } - client := fake.NewSimpleClientset(d).Apps() - dsv := &DaemonSetStatusViewer{c: client} - msg, done, err := dsv.Status("bar", "foo", 0) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if done != test.done || msg != test.msg { - t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", - test.generation, - d.Status.DesiredNumberScheduled, - test.status, - msg, - done, - test.msg, - test.done, - ) - } + Spec: apps.DaemonSetSpec{ + UpdateStrategy: apps.DaemonSetUpdateStrategy{ + Type: apps.RollingUpdateDaemonSetStrategyType, + }, + }, + Status: test.status, + } + client := fake.NewSimpleClientset(d).Apps() + dsv := &DaemonSetStatusViewer{c: client} + msg, done, err := dsv.Status("bar", "foo", 0) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if done != test.done || msg != test.msg { + t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", + test.generation, + d.Status.DesiredNumberScheduled, + test.status, + msg, + done, + test.msg, + test.done, + ) + } + }) } } @@ -350,27 +363,29 @@ func TestStatefulSetStatusViewerStatus(t *testing.T) { err: false, }, } - for i := range tests { - test := tests[i] - s := newStatefulSet(3) - s.Status = test.status - s.Spec.UpdateStrategy = test.strategy - s.Generation = test.generation - client := fake.NewSimpleClientset(s).AppsV1() - dsv := &StatefulSetStatusViewer{c: client} - msg, done, err := dsv.Status(s.Namespace, s.Name, 0) - if test.err && err == nil { - t.Fatalf("%s: expected error", test.name) - } - if !test.err && err != nil { - t.Fatalf("%s: %s", test.name, err) - } - if done && !test.done { - t.Errorf("%s: want done %v got %v", test.name, done, test.done) - } - if msg != test.msg { - t.Errorf("%s: want message %s got %s", test.name, test.msg, msg) - } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + s := newStatefulSet(3) + s.Status = test.status + s.Spec.UpdateStrategy = test.strategy + s.Generation = test.generation + client := fake.NewSimpleClientset(s).AppsV1() + dsv := &StatefulSetStatusViewer{c: client} + msg, done, err := dsv.Status(s.Namespace, s.Name, 0) + if test.err && err == nil { + t.Fatalf("%s: expected error", test.name) + } + if !test.err && err != nil { + t.Fatalf("%s: %s", test.name, err) + } + if done && !test.done { + t.Errorf("%s: want done %v got %v", test.name, done, test.done) + } + if msg != test.msg { + t.Errorf("%s: want message %s got %s", test.name, test.msg, msg) + } + }) } } diff --git a/pkg/kubectl/run_test.go b/pkg/kubectl/run_test.go index f2f217e486..84aad5b3e0 100644 --- a/pkg/kubectl/run_test.go +++ b/pkg/kubectl/run_test.go @@ -33,11 +33,13 @@ import ( func TestGenerate(t *testing.T) { one := int32(1) tests := []struct { + name string params map[string]interface{} expected *v1.ReplicationController expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -72,6 +74,7 @@ func TestGenerate(t *testing.T) { }, { + name: "test2", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -115,6 +118,7 @@ func TestGenerate(t *testing.T) { }, { + name: "test3", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -150,6 +154,7 @@ func TestGenerate(t *testing.T) { }, }, { + name: "test3", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -184,6 +189,7 @@ func TestGenerate(t *testing.T) { }, }, { + name: "test4", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -220,6 +226,7 @@ func TestGenerate(t *testing.T) { }, }, { + name: "test5", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -260,6 +267,7 @@ func TestGenerate(t *testing.T) { }, }, { + name: "test6", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -270,6 +278,7 @@ func TestGenerate(t *testing.T) { expectErr: true, }, { + name: "test7", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -301,6 +310,7 @@ func TestGenerate(t *testing.T) { }, }, { + name: "test8", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -311,6 +321,7 @@ func TestGenerate(t *testing.T) { expectErr: true, }, { + name: "test9", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -322,6 +333,7 @@ func TestGenerate(t *testing.T) { expectErr: true, }, { + name: "test10", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -333,6 +345,7 @@ func TestGenerate(t *testing.T) { expectErr: true, }, { + name: "test11", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -344,6 +357,7 @@ func TestGenerate(t *testing.T) { expectErr: true, }, { + name: "test12", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -388,29 +402,33 @@ func TestGenerate(t *testing.T) { }, } generator := BasicReplicationController{} - for i, test := range tests { - obj, err := generator.Generate(test.params) - t.Logf("%d: %#v", i, obj) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.ReplicationController).Spec.Template, test.expected.Spec.Template) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected.Spec.Template, obj.(*v1.ReplicationController).Spec.Template) - } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + t.Logf("%d: %#v", i, obj) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + return + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.ReplicationController).Spec.Template, tt.expected.Spec.Template) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected.Spec.Template, obj.(*v1.ReplicationController).Spec.Template) + } + }) } } func TestGeneratePod(t *testing.T) { tests := []struct { + name string params map[string]interface{} expected *v1.Pod expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -435,6 +453,7 @@ func TestGeneratePod(t *testing.T) { }, }, { + name: "test2", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -445,6 +464,7 @@ func TestGeneratePod(t *testing.T) { expectErr: true, }, { + name: "test3", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -480,6 +500,7 @@ func TestGeneratePod(t *testing.T) { }, }, { + name: "test4", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -509,6 +530,7 @@ func TestGeneratePod(t *testing.T) { }, }, { + name: "test5", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -540,6 +562,7 @@ func TestGeneratePod(t *testing.T) { }, }, { + name: "test6", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -549,6 +572,7 @@ func TestGeneratePod(t *testing.T) { expectErr: true, }, { + name: "test7", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -574,6 +598,7 @@ func TestGeneratePod(t *testing.T) { }, }, { + name: "test8", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -602,6 +627,7 @@ func TestGeneratePod(t *testing.T) { }, }, { + name: "test9", params: map[string]interface{}{ "name": "foo", "image": "someimage", @@ -632,28 +658,32 @@ func TestGeneratePod(t *testing.T) { }, } generator := BasicPod{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.Pod), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.Pod)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.Pod), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.Pod)) + } + }) } } func TestGenerateDeployment(t *testing.T) { three := int32(3) tests := []struct { + name string params map[string]interface{} expected *extensionsv1beta1.Deployment expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "labels": "foo=bar,baz=blah", "name": "foo", @@ -725,28 +755,32 @@ func TestGenerateDeployment(t *testing.T) { } generator := DeploymentV1Beta1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*extensionsv1beta1.Deployment), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*extensionsv1beta1.Deployment)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*extensionsv1beta1.Deployment), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*extensionsv1beta1.Deployment)) + } + }) } } func TestGenerateAppsDeployment(t *testing.T) { three := int32(3) tests := []struct { + name string params map[string]interface{} expected *appsv1beta1.Deployment expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "labels": "foo=bar,baz=blah", "name": "foo", @@ -818,27 +852,31 @@ func TestGenerateAppsDeployment(t *testing.T) { } generator := DeploymentAppsV1Beta1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*appsv1beta1.Deployment), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*appsv1beta1.Deployment)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*appsv1beta1.Deployment), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*appsv1beta1.Deployment)) + } + }) } } func TestGenerateJob(t *testing.T) { tests := []struct { + name string params map[string]interface{} expected *batchv1.Job expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "labels": "foo=bar,baz=blah", "name": "foo", @@ -909,27 +947,31 @@ func TestGenerateJob(t *testing.T) { } generator := JobV1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*batchv1.Job), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*batchv1.Job)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*batchv1.Job), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*batchv1.Job)) + } + }) } } func TestGenerateCronJobAlpha(t *testing.T) { tests := []struct { + name string params map[string]interface{} expected *batchv2alpha1.CronJob expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "labels": "foo=bar,baz=blah", "name": "foo", @@ -1007,27 +1049,31 @@ func TestGenerateCronJobAlpha(t *testing.T) { } generator := CronJobV2Alpha1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*batchv2alpha1.CronJob), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*batchv2alpha1.CronJob)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*batchv2alpha1.CronJob), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*batchv2alpha1.CronJob)) + } + }) } } func TestGenerateCronJobBeta(t *testing.T) { tests := []struct { + name string params map[string]interface{} expected *batchv1beta1.CronJob expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "labels": "foo=bar,baz=blah", "name": "foo", @@ -1105,28 +1151,32 @@ func TestGenerateCronJobBeta(t *testing.T) { } generator := CronJobV1Beta1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*batchv1beta1.CronJob), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*batchv1beta1.CronJob)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*batchv1beta1.CronJob), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*batchv1beta1.CronJob)) + } + }) } } func TestParseEnv(t *testing.T) { tests := []struct { + name string envArray []string expected []v1.EnvVar expectErr bool test string }{ { + name: "test1", envArray: []string{ "THIS_ENV=isOK", "this.dotted.env=isOKToo", @@ -1155,6 +1205,7 @@ func TestParseEnv(t *testing.T) { test: "test case 1", }, { + name: "test2", envArray: []string{ "WITH_OUT_EQUALS", }, @@ -1163,6 +1214,7 @@ func TestParseEnv(t *testing.T) { test: "test case 2", }, { + name: "test3", envArray: []string{ "WITH_OUT_VALUES=", }, @@ -1176,6 +1228,7 @@ func TestParseEnv(t *testing.T) { test: "test case 3", }, { + name: "test4", envArray: []string{ "=WITH_OUT_NAME", }, @@ -1185,16 +1238,18 @@ func TestParseEnv(t *testing.T) { }, } - for _, test := range tests { - envs, err := parseEnvs(test.envArray) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v (%s)", err, test.test) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(envs, test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v (%s)", test.expected, envs, test.test) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + envs, err := parseEnvs(tt.envArray) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v (%s)", err, tt.test) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(envs, tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v (%s)", tt.expected, envs, tt.test) + } + }) } } diff --git a/pkg/kubectl/secret_for_docker_registry_test.go b/pkg/kubectl/secret_for_docker_registry_test.go index 844acc3bcc..dec0729ae9 100644 --- a/pkg/kubectl/secret_for_docker_registry_test.go +++ b/pkg/kubectl/secret_for_docker_registry_test.go @@ -35,12 +35,14 @@ func TestSecretForDockerRegistryGenerate(t *testing.T) { t.Errorf("unexpected error: %v", err) } - tests := map[string]struct { + tests := []struct { + name string params map[string]interface{} expected *v1.Secret expectErr bool }{ - "test-valid-use": { + { + name: "test-valid-use", params: map[string]interface{}{ "name": "foo", "docker-server": server, @@ -59,7 +61,8 @@ func TestSecretForDockerRegistryGenerate(t *testing.T) { }, expectErr: false, }, - "test-valid-use-append-hash": { + { + name: "test-valid-use-append-hash", params: map[string]interface{}{ "name": "foo", "docker-server": server, @@ -79,7 +82,8 @@ func TestSecretForDockerRegistryGenerate(t *testing.T) { }, expectErr: false, }, - "test-valid-use-no-email": { + { + name: "test-valid-use-no-email", params: map[string]interface{}{ "name": "foo", "docker-server": server, @@ -97,7 +101,8 @@ func TestSecretForDockerRegistryGenerate(t *testing.T) { }, expectErr: false, }, - "test-missing-required-param": { + { + name: "test-missing-required-param", params: map[string]interface{}{ "name": "foo", "docker-server": server, @@ -109,16 +114,18 @@ func TestSecretForDockerRegistryGenerate(t *testing.T) { } generator := SecretForDockerRegistryGeneratorV1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.Secret), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.Secret)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.Secret), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.Secret)) + } + }) } } diff --git a/pkg/kubectl/secret_for_tls_test.go b/pkg/kubectl/secret_for_tls_test.go index 9f296a8884..487ff14583 100644 --- a/pkg/kubectl/secret_for_tls_test.go +++ b/pkg/kubectl/secret_for_tls_test.go @@ -122,12 +122,14 @@ func TestSecretForTLSGenerate(t *testing.T) { defer tearDown(mismatchCertTmpDir) mismatchKeyPath, mismatchCertPath := writeKeyPair(mismatchCertTmpDir, mismatchRSAKeyPEM, rsaCertPEM, t) - tests := map[string]struct { + tests := []struct { + name string params map[string]interface{} expected *v1.Secret expectErr bool }{ - "test-valid-tls-secret": { + { + name: "test-valid-tls-secret", params: map[string]interface{}{ "name": "foo", "key": validKeyPath, @@ -145,7 +147,8 @@ func TestSecretForTLSGenerate(t *testing.T) { }, expectErr: false, }, - "test-valid-tls-secret-append-hash": { + { + name: "test-valid-tls-secret-append-hash", params: map[string]interface{}{ "name": "foo", "key": validKeyPath, @@ -164,7 +167,8 @@ func TestSecretForTLSGenerate(t *testing.T) { }, expectErr: false, }, - "test-invalid-key-pair": { + { + name: "test-invalid-key-pair", params: map[string]interface{}{ "name": "foo", "key": invalidKeyPath, @@ -182,7 +186,8 @@ func TestSecretForTLSGenerate(t *testing.T) { }, expectErr: true, }, - "test-mismatched-key-pair": { + { + name: "test-mismatched-key-pair", params: map[string]interface{}{ "name": "foo", "key": mismatchKeyPath, @@ -200,7 +205,8 @@ func TestSecretForTLSGenerate(t *testing.T) { }, expectErr: true, }, - "test-missing-required-param": { + { + name: "test-missing-required-param", params: map[string]interface{}{ "name": "foo", "key": "/tmp/foo.key", @@ -210,16 +216,18 @@ func TestSecretForTLSGenerate(t *testing.T) { } generator := SecretForTLSGeneratorV1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.Secret), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.Secret)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.Secret), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.Secret)) + } + }) } } diff --git a/pkg/kubectl/secret_test.go b/pkg/kubectl/secret_test.go index 43dd411a20..8ad27ea427 100644 --- a/pkg/kubectl/secret_test.go +++ b/pkg/kubectl/secret_test.go @@ -27,12 +27,14 @@ import ( func TestSecretGenerate(t *testing.T) { tests := []struct { + name string setup func(t *testing.T, params map[string]interface{}) func() params map[string]interface{} expected *v1.Secret expectErr bool }{ { + name: "test1", params: map[string]interface{}{ "name": "foo", }, @@ -47,6 +49,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test2", params: map[string]interface{}{ "name": "foo", "append-hash": true, @@ -62,6 +65,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test3", params: map[string]interface{}{ "name": "foo", "type": "my-type", @@ -78,6 +82,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test4", params: map[string]interface{}{ "name": "foo", "type": "my-type", @@ -95,6 +100,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test5", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1=value1", "key2=value2"}, @@ -113,6 +119,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test6", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1=value1", "key2=value2"}, @@ -132,6 +139,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test7", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1value1"}, @@ -139,6 +147,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: true, }, { + name: "test8", params: map[string]interface{}{ "name": "foo", "from-file": []string{"key1=/file=2"}, @@ -146,6 +155,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: true, }, { + name: "test9", params: map[string]interface{}{ "name": "foo", "from-file": []string{"key1==value"}, @@ -153,6 +163,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: true, }, { + name: "test10", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1==value1"}, @@ -170,6 +181,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test11", params: map[string]interface{}{ "name": "foo", "from-literal": []string{"key1==value1"}, @@ -188,6 +200,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test12", setup: setupEnvFile("key1=value1", "#", "", "key2=value2"), params: map[string]interface{}{ "name": "valid_env", @@ -207,6 +220,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test13", setup: setupEnvFile("key1=value1", "#", "", "key2=value2"), params: map[string]interface{}{ "name": "valid_env", @@ -227,6 +241,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test14", setup: func() func(t *testing.T, params map[string]interface{}) func() { os.Setenv("g_key1", "1") os.Setenv("g_key2", "2") @@ -250,6 +265,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test15", setup: func() func(t *testing.T, params map[string]interface{}) func() { os.Setenv("g_key1", "1") os.Setenv("g_key2", "2") @@ -274,6 +290,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test16", params: map[string]interface{}{ "name": "too_many_args", "from-literal": []string{"key1=value1"}, @@ -282,6 +299,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: true, }, { + name: "test17", setup: setupEnvFile("key#1=value1"), params: map[string]interface{}{ "name": "invalid_key", @@ -290,6 +308,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: true, }, { + name: "test18", setup: setupEnvFile(" key1= value1"), params: map[string]interface{}{ "name": "with_spaces", @@ -308,6 +327,7 @@ func TestSecretGenerate(t *testing.T) { expectErr: false, }, { + name: "test19", setup: setupEnvFile(" key1= value1"), params: map[string]interface{}{ "name": "with_spaces", @@ -328,22 +348,24 @@ func TestSecretGenerate(t *testing.T) { }, } generator := SecretGeneratorV1{} - for i, test := range tests { - if test.setup != nil { - if teardown := test.setup(t, test.params); teardown != nil { - defer teardown() + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.setup != nil { + if teardown := tt.setup(t, tt.params); teardown != nil { + defer teardown() + } } - } - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("case %d, unexpected error: %v", i, err) - continue - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.Secret), test.expected) { - t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, test.expected, obj.(*v1.Secret)) - } + obj, err := generator.Generate(tt.params) + if !tt.expectErr && err != nil { + t.Errorf("case %d, unexpected error: %v", i, err) + return + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.Secret), tt.expected) { + t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, tt.expected, obj.(*v1.Secret)) + } + }) } } diff --git a/pkg/kubectl/service_test.go b/pkg/kubectl/service_test.go index 0120c3557b..ceaba9b463 100644 --- a/pkg/kubectl/service_test.go +++ b/pkg/kubectl/service_test.go @@ -27,11 +27,13 @@ import ( func TestGenerateService(t *testing.T) { tests := []struct { + name string generator Generator params map[string]interface{} expected v1.Service }{ { + name: "test1", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -60,7 +62,7 @@ func TestGenerateService(t *testing.T) { }, }, { - + name: "test2", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -89,6 +91,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test3", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -122,6 +125,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test4", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -152,6 +156,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test5", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -184,6 +189,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test6", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -214,6 +220,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test7", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -245,6 +252,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test8", generator: ServiceGeneratorV1{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -274,6 +282,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test9", generator: ServiceGeneratorV1{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -305,6 +314,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test10", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -335,6 +345,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test11", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -365,6 +376,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test12", generator: ServiceGeneratorV1{}, params: map[string]interface{}{ "selector": "foo=bar", @@ -399,6 +411,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test13", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar", @@ -433,6 +446,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test14", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar", @@ -466,6 +480,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test15", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar", @@ -499,6 +514,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test16", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar", @@ -538,6 +554,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test17", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar,baz=blah", @@ -561,6 +578,7 @@ func TestGenerateService(t *testing.T) { }, }, { + name: "test18", generator: ServiceGeneratorV2{}, params: map[string]interface{}{ "selector": "foo=bar", @@ -581,13 +599,15 @@ func TestGenerateService(t *testing.T) { }, }, } - for _, test := range tests { - obj, err := test.generator.Generate(test.params) - if !reflect.DeepEqual(obj, &test.expected) { - t.Errorf("expected:\n%#v\ngot\n%#v\n", &test.expected, obj) - } - if err != nil { - t.Errorf("unexpected error: %v", err) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj, err := tt.generator.Generate(tt.params) + if !reflect.DeepEqual(obj, &tt.expected) { + t.Errorf("expected:\n%#v\ngot\n%#v\n", &tt.expected, obj) + } + if err != nil { + t.Errorf("unexpected error: %v", err) + } + }) } } diff --git a/pkg/kubectl/serviceaccount_test.go b/pkg/kubectl/serviceaccount_test.go index ec232f4a6d..d2e45ec05e 100644 --- a/pkg/kubectl/serviceaccount_test.go +++ b/pkg/kubectl/serviceaccount_test.go @@ -43,19 +43,21 @@ func TestServiceAccountGenerate(t *testing.T) { expectErr: true, }, } - for _, test := range tests { - generator := ServiceAccountGeneratorV1{ - Name: test.name, - } - obj, err := generator.StructuredGenerate() - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*v1.ServiceAccount), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.ServiceAccount)) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + generator := ServiceAccountGeneratorV1{ + Name: tt.name, + } + obj, err := generator.StructuredGenerate() + if !tt.expectErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + if tt.expectErr && err != nil { + return + } + if !reflect.DeepEqual(obj.(*v1.ServiceAccount), tt.expected) { + t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.ServiceAccount)) + } + }) } } diff --git a/pkg/kubectl/sorter_test.go b/pkg/kubectl/sorter_test.go index 7c2e5ee0a0..667dee7980 100644 --- a/pkg/kubectl/sorter_test.go +++ b/pkg/kubectl/sorter_test.go @@ -389,24 +389,26 @@ func TestSortingPrinter(t *testing.T) { expectedErr: "couldn't find any field with path \"{.invalid}\" in the list of objects", }, } - for _, test := range tests { - sort := &SortingPrinter{SortField: test.field, Decoder: legacyscheme.Codecs.UniversalDecoder()} - err := sort.sortObj(test.obj) - if err != nil { - if len(test.expectedErr) > 0 { - if strings.Contains(err.Error(), test.expectedErr) { - continue + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sort := &SortingPrinter{SortField: tt.field, Decoder: legacyscheme.Codecs.UniversalDecoder()} + err := sort.sortObj(tt.obj) + if err != nil { + if len(tt.expectedErr) > 0 { + if strings.Contains(err.Error(), tt.expectedErr) { + return + } + t.Fatalf("%s: expected error containing: %q, got: \"%v\"", tt.name, tt.expectedErr, err) } - t.Fatalf("%s: expected error containing: %q, got: \"%v\"", test.name, test.expectedErr, err) + t.Fatalf("%s: unexpected error: %v", tt.name, err) } - t.Fatalf("%s: unexpected error: %v", test.name, err) - } - if len(test.expectedErr) > 0 { - t.Fatalf("%s: expected error containing: %q, got none", test.name, test.expectedErr) - } - if !reflect.DeepEqual(test.obj, test.sort) { - t.Errorf("[%s]\nexpected:\n%v\nsaw:\n%v", test.name, test.sort, test.obj) - } + if len(tt.expectedErr) > 0 { + t.Fatalf("%s: expected error containing: %q, got none", tt.name, tt.expectedErr) + } + if !reflect.DeepEqual(tt.obj, tt.sort) { + t.Errorf("[%s]\nexpected:\n%v\nsaw:\n%v", tt.name, tt.sort, tt.obj) + } + }) } } diff --git a/pkg/kubectl/util/service_port_test.go b/pkg/kubectl/util/service_port_test.go index 914c7d3b07..6a4bb2adb5 100644 --- a/pkg/kubectl/util/service_port_test.go +++ b/pkg/kubectl/util/service_port_test.go @@ -24,7 +24,7 @@ import ( ) func TestLookupContainerPortNumberByName(t *testing.T) { - cases := []struct { + tests := []struct { name string pod api.Pod portname string @@ -74,30 +74,32 @@ func TestLookupContainerPortNumberByName(t *testing.T) { }, } - for _, tc := range cases { - portnum, err := LookupContainerPortNumberByName(tc.pod, tc.portname) - if err != nil { - if tc.err { - continue + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + portnum, err := LookupContainerPortNumberByName(tt.pod, tt.portname) + if err != nil { + if tt.err { + return + } + + t.Errorf("%v: unexpected error: %v", tt.name, err) + return } - t.Errorf("%v: unexpected error: %v", tc.name, err) - continue - } + if tt.err { + t.Errorf("%v: unexpected success", tt.name) + return + } - if tc.err { - t.Errorf("%v: unexpected success", tc.name) - continue - } - - if portnum != tc.portnum { - t.Errorf("%v: expected port number %v; got %v", tc.name, tc.portnum, portnum) - } + if portnum != tt.portnum { + t.Errorf("%v: expected port number %v; got %v", tt.name, tt.portnum, portnum) + } + }) } } func TestLookupContainerPortNumberByServicePort(t *testing.T) { - cases := []struct { + tests := []struct { name string svc api.Service pod api.Pod @@ -311,27 +313,29 @@ func TestLookupContainerPortNumberByServicePort(t *testing.T) { }, } - for _, tc := range cases { - containerPort, err := LookupContainerPortNumberByServicePort(tc.svc, tc.pod, tc.port) - if err != nil { - if tc.err { - if containerPort != tc.containerPort { - t.Errorf("%v: expected port %v; got %v", tc.name, tc.containerPort, containerPort) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + containerPort, err := LookupContainerPortNumberByServicePort(tt.svc, tt.pod, tt.port) + if err != nil { + if tt.err { + if containerPort != tt.containerPort { + t.Errorf("%v: expected port %v; got %v", tt.name, tt.containerPort, containerPort) + } + return } - continue + + t.Errorf("%v: unexpected error: %v", tt.name, err) + return } - t.Errorf("%v: unexpected error: %v", tc.name, err) - continue - } + if tt.err { + t.Errorf("%v: unexpected success", tt.name) + return + } - if tc.err { - t.Errorf("%v: unexpected success", tc.name) - continue - } - - if containerPort != tc.containerPort { - t.Errorf("%v: expected port %v; got %v", tc.name, tc.containerPort, containerPort) - } + if containerPort != tt.containerPort { + t.Errorf("%v: expected port %v; got %v", tt.name, tt.containerPort, containerPort) + } + }) } } diff --git a/pkg/kubectl/util/util_test.go b/pkg/kubectl/util/util_test.go index d1fefed38f..4a4e647a0e 100644 --- a/pkg/kubectl/util/util_test.go +++ b/pkg/kubectl/util/util_test.go @@ -19,7 +19,7 @@ package util import "testing" func TestParseFileSource(t *testing.T) { - cases := []struct { + tests := []struct { name string input string key string @@ -88,35 +88,37 @@ func TestParseFileSource(t *testing.T) { }, } - for _, tc := range cases { - key, filepath, err := ParseFileSource(tc.input) - if err != nil { - if tc.err { - continue + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key, filepath, err := ParseFileSource(tt.input) + if err != nil { + if tt.err { + return + } + + t.Errorf("%v: unexpected error: %v", tt.name, err) + return } - t.Errorf("%v: unexpected error: %v", tc.name, err) - continue - } + if tt.err { + t.Errorf("%v: unexpected success", tt.name) + return + } - if tc.err { - t.Errorf("%v: unexpected success", tc.name) - continue - } + if e, a := tt.key, key; e != a { + t.Errorf("%v: expected key %v; got %v", tt.name, e, a) + return + } - if e, a := tc.key, key; e != a { - t.Errorf("%v: expected key %v; got %v", tc.name, e, a) - continue - } - - if e, a := tc.filepath, filepath; e != a { - t.Errorf("%v: expected filepath %v; got %v", tc.name, e, a) - } + if e, a := tt.filepath, filepath; e != a { + t.Errorf("%v: expected filepath %v; got %v", tt.name, e, a) + } + }) } } func TestParseLiteralSource(t *testing.T) { - cases := []struct { + tests := []struct { name string input string key string @@ -170,29 +172,31 @@ func TestParseLiteralSource(t *testing.T) { }, } - for _, tc := range cases { - key, value, err := ParseLiteralSource(tc.input) - if err != nil { - if tc.err { - continue + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key, value, err := ParseLiteralSource(tt.input) + if err != nil { + if tt.err { + return + } + + t.Errorf("%v: unexpected error: %v", tt.name, err) + return } - t.Errorf("%v: unexpected error: %v", tc.name, err) - continue - } + if tt.err { + t.Errorf("%v: unexpected success", tt.name) + return + } - if tc.err { - t.Errorf("%v: unexpected success", tc.name) - continue - } + if e, a := tt.key, key; e != a { + t.Errorf("%v: expected key %v; got %v", tt.name, e, a) + return + } - if e, a := tc.key, key; e != a { - t.Errorf("%v: expected key %v; got %v", tc.name, e, a) - continue - } - - if e, a := tc.value, value; e != a { - t.Errorf("%v: expected value %v; got %v", tc.name, e, a) - } + if e, a := tt.value, value; e != a { + t.Errorf("%v: expected value %v; got %v", tt.name, e, a) + } + }) } } diff --git a/pkg/kubectl/validation/schema_test.go b/pkg/kubectl/validation/schema_test.go index c43eb785dc..c0ac764631 100644 --- a/pkg/kubectl/validation/schema_test.go +++ b/pkg/kubectl/validation/schema_test.go @@ -126,14 +126,16 @@ func TestConjunctiveSchema(t *testing.T) { }, } - for _, test := range tests { - schema := ConjunctiveSchema(test.schemas) - err := schema.ValidateBytes([]byte{}) - if err != nil && test.shouldPass { - t.Errorf("Unexpected error: %v in %s", err, test.name) - } - if err == nil && !test.shouldPass { - t.Errorf("Unexpected non-error: %s", test.name) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + schema := ConjunctiveSchema(tt.schemas) + err := schema.ValidateBytes([]byte{}) + if err != nil && tt.shouldPass { + t.Errorf("Unexpected error: %v in %s", err, tt.name) + } + if err == nil && !tt.shouldPass { + t.Errorf("Unexpected non-error: %s", tt.name) + } + }) } }