Merge pull request #63747 from wgliang/master.test.kubectl

Automatic merge from submit-queue. If you want to cherry-pick this change to another branch, please follow the instructions <a href="https://github.com/kubernetes/community/blob/master/contributors/devel/cherry-picks.md">here</a>.

use subtest for table units (pkg/kubectl)

**What this PR does / why we need it**:
Go 1.7 added the subtest feature which can make table-driven tests much easier to run and debug. Many table-driven tests in pkg/kubectl are not using this feature.

/kind cleanup
/area kubectl

Further reading: [Using Subtests and Sub-benchmarks](https://blog.golang.org/subtests)


**Which issue(s) this PR fixes** *(optional, in `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close the issue(s) when PR gets merged)*:
Fixes #

**Special notes for your reviewer**:

**Release note**:

```release-note
NONE
```
pull/8/head
Kubernetes Submit Queue 2018-06-20 12:39:21 -07:00 committed by GitHub
commit debc5387fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 1841 additions and 1301 deletions

View File

@ -101,28 +101,30 @@ func TestHPAGenerate(t *testing.T) {
},
}
for _, test := range tests {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
generator := HorizontalPodAutoscalerGeneratorV1{
Name: test.HPAName,
ScaleRefKind: test.scaleRefKind,
ScaleRefName: test.scaleRefName,
ScaleRefApiVersion: test.scaleRefApiVersion,
MinReplicas: test.minReplicas,
MaxReplicas: test.maxReplicas,
CPUPercent: test.CPUPercent,
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !test.expectErr && err != nil {
t.Errorf("[%s] unexpected error: %v", test.name, err)
if !tt.expectErr && err != nil {
t.Errorf("[%s] unexpected error: %v", tt.name, err)
}
if test.expectErr && err == nil {
t.Errorf("[%s] expect error, got nil", test.name)
if tt.expectErr && err == nil {
t.Errorf("[%s] expect error, got nil", tt.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))
if !reflect.DeepEqual(obj.(*autoscalingv1.HorizontalPodAutoscaler), tt.expected) {
t.Errorf("[%s] want:\n%#v\ngot:\n%#v", tt.name, tt.expected, obj.(*autoscalingv1.HorizontalPodAutoscaler))
}
})
}
}

View File

@ -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 {
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 tests[i].expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if tests[i].expectErr && err == nil {
t.Errorf("[%s] expect error, got nil", tests[i].name)
if tt.expectErr && err == nil {
t.Errorf("[%s] expect error, got nil", tt.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))
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))
}
})
}
}

View File

@ -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 {
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)
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)
}
continue
return
}
if test.wantParseErr {
t.Errorf("case %d: expected parsing error for flags %q: %s", i, test.flags, buff)
continue
if tt.wantParseErr {
t.Errorf("case %s: expected parsing error for flags %q: %s", tt.name, tt.flags, buff)
return
}
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.wantCompleteErr {
t.Errorf("case %s: complete() error for flags %q: %s", tt.name, tt.flags, buff)
}
continue
return
}
if test.wantCompleteErr {
t.Errorf("case %d: complete() expected errors for flags %q: %s", i, test.flags, buff)
continue
if tt.wantCompleteErr {
t.Errorf("case %s: complete() expected errors for flags %q: %s", tt.name, tt.flags, buff)
return
}
if err := opts.validate(); err != nil {
if !test.wantValidateErr {
t.Errorf("case %d: flags %q: validate failed: %v", i, test.flags, err)
if !tt.wantValidateErr {
t.Errorf("case %s: flags %q: validate failed: %v", tt.name, tt.flags, err)
}
continue
return
}
if test.wantValidateErr {
t.Errorf("case %d: flags %q: expected validate to fail", i, test.flags)
continue
if tt.wantValidateErr {
t.Errorf("case %s: flags %q: expected validate to fail", tt.name, tt.flags)
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 !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)
}
})
}
}

View File

@ -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 {
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 {
obj, err := generator.Generate(tt.params)
if !tt.expectErr && err != nil {
t.Errorf("case %d, unexpected error: %v", i, err)
}
if test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*v1.ConfigMap), test.expected) {
t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, test.expected, obj.(*v1.ConfigMap))
if !reflect.DeepEqual(obj.(*v1.ConfigMap), tt.expected) {
t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, tt.expected, obj.(*v1.ConfigMap))
}
})
}
}

View File

@ -82,22 +82,24 @@ func TestDeploymentBasicGenerate(t *testing.T) {
expectErr: true,
},
}
for _, test := range tests {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
generator := &DeploymentBasicAppsGeneratorV1{
BaseDeploymentGenerator{
Name: test.deploymentName,
Images: test.images,
Name: tt.deploymentName,
Images: tt.images,
},
}
obj, err := generator.StructuredGenerate()
if !test.expectErr && err != nil {
if !tt.expectErr && err != nil {
t.Errorf("unexpected error: %v", err)
}
if test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
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))
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))
}
})
}
}

View File

@ -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)
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)
}
if c.expectedValue != value {
t.Errorf("\texpected value %q, received %q", c.expectedValue, value)
if tt.expectedValue != value {
t.Errorf("\texpected value %q, received %q", tt.expectedValue, value)
}
if len(c.expectedErr) == 0 {
if len(tt.expectedErr) == 0 {
if err != nil {
t.Errorf("\tunexpected err %v", err)
}
} else {
if !strings.Contains(err.Error(), c.expectedErr) {
t.Errorf("\terr %v doesn't match expected %q", err, c.expectedErr)
if !strings.Contains(err.Error(), tt.expectedErr) {
t.Errorf("\terr %v doesn't match expected %q", err, tt.expectedErr)
}
}
})
}
}

View File

@ -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)
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)
}
})
}
}

View File

@ -33,35 +33,42 @@ 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 {
@ -73,9 +80,10 @@ func TestFindField(t *testing.T) {
gotPath = path.GetPath().String()
}
if gotErr != test.err || gotPath != test.expectedPath {
if gotErr != tt.err || gotPath != tt.expectedPath {
t.Errorf("LookupSchemaForField(schema, %v) = (path: %q, err: %q), expected (path: %q, err: %q)",
test.path, gotPath, gotErr, test.expectedPath, test.err)
tt.path, gotPath, gotErr, tt.expectedPath, tt.err)
}
})
}
}

View File

@ -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)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := LookupSchemaForField(schema, tt.path)
if err != nil {
t.Fatalf("Invalid test.path %v: %v", test.path, err)
t.Fatalf("Invalid tt.path %v: %v", tt.path, err)
}
got := GetTypeName(s)
if got != test.expected {
t.Errorf("Got %q, expected %q", got, test.expected)
if got != tt.expected {
t.Errorf("Got %q, expected %q", got, tt.expected)
}
})
}
}

View File

@ -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 {
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 !test.valid && err == nil {
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)
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 && test.expectError == true {
t.Errorf("%s: expect error, got nil", test.name)
if err == nil && tt.expectError == true {
t.Errorf("%s: expect error, got nil", tt.name)
}
if got != test.expected {
t.Errorf("%s: expect %v, got %v", test.name, test.expected, got)
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)
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(test.expected, got) {
t.Errorf("\nexpected:\n%v\ngot:\n%v", test.expected, got)
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)
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(test.expected, got) {
t.Errorf("\nexpected:\n%v\ngot:\n%v", test.expected, got)
if !reflect.DeepEqual(tt.expected, got) {
t.Errorf("\nexpected:\n%v\ngot:\n%v", tt.expected, got)
}
})
}
errorCases := []struct {

View File

@ -378,9 +378,10 @@ func TestPathBuilderWithMultiple(t *testing.T) {
{"hardlink", &v1.Pod{}, true, fmt.Sprintf("%s/inode/hardlink/busybox-link.json", tmpDir), []string{"busybox0"}},
}
for _, test := range tests {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := newDefaultBuilder().
FilenameParam(false, &FilenameOptions{Recursive: test.recursive, Filenames: []string{test.directory}}).
FilenameParam(false, &FilenameOptions{Recursive: tt.recursive, Filenames: []string{tt.directory}}).
NamespaceParam("test").DefaultNamespace()
testVisitor := &testVisitor{}
@ -388,23 +389,24 @@ func TestPathBuilderWithMultiple(t *testing.T) {
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)
t.Fatalf("unexpected response: %v %t %#v %s", err, singleItemImplied, testVisitor.Infos, tt.name)
}
info := testVisitor.Infos
for i, v := range info {
switch test.object.(type) {
switch tt.object.(type) {
case *v1.Pod:
if _, ok := v.Object.(*v1.Pod); !ok || v.Name != test.expectedNames[i] || v.Namespace != "test" {
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 != test.expectedNames[i] || v.Namespace != "test" {
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,9 +439,10 @@ func TestPathBuilderWithMultipleInvalid(t *testing.T) {
{"loop", true, fmt.Sprintf("%s/inode/symlink/loop", tmpDir)},
}
for _, test := range tests {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := newDefaultBuilder().
FilenameParam(false, &FilenameOptions{Recursive: test.recursive, Filenames: []string{test.directory}}).
FilenameParam(false, &FilenameOptions{Recursive: tt.recursive, Filenames: []string{tt.directory}}).
NamespaceParam("test").DefaultNamespace()
testVisitor := &testVisitor{}
@ -447,8 +450,9 @@ func TestPathBuilderWithMultipleInvalid(t *testing.T) {
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)
t.Fatalf("unexpected response: %v %t %#v %s", err, singleItemImplied, testVisitor.Infos, tt.name)
}
})
}
}
@ -956,7 +960,8 @@ func TestResourceTuple(t *testing.T) {
errFn: expectErr,
},
}
for k, testCase := range testCases {
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 {
@ -969,19 +974,19 @@ func TestResourceTuple(t *testing.T) {
}
b := newDefaultBuilderWith(fakeClientWith(k, t, expectedRequests)).
NamespaceParam("test").DefaultNamespace().
ResourceTypeOrNameArgs(true, testCase.args...).RequireObject(requireObject)
ResourceTypeOrNameArgs(true, tt.args...).RequireObject(requireObject)
r := b.Do()
if !testCase.errFn(r.Err()) {
if !tt.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):
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()
@ -989,10 +994,11 @@ func TestResourceTuple(t *testing.T) {
// test error
continue
}
if len(info) != len(testCase.args) {
if len(info) != len(tt.args) {
t.Errorf("%s: unexpected number of infos returned: %#v", k, info)
}
}
})
}
}
@ -1324,120 +1330,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/<resource_name>' instead of '" + basename + " get resource resource/<resource_name>'"),
},
}
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)
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 != test.expectedHasName {
t.Errorf("expected HasName to return %v for %s", test.expectedHasName, test.args)
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)
}
})
}
}

View File

@ -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 {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &fake.RESTClient{
NegotiatedSerializer: scheme.Codecs,
Resp: test.Resp,
Err: test.HttpErr,
Resp: tt.Resp,
Err: tt.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) != tt.Err {
t.Errorf("unexpected error: %t %v", tt.Err, err)
}
if err != nil {
continue
return
}
if test.Req != nil && !test.Req(client.Req) {
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,25 +216,26 @@ func TestHelperCreate(t *testing.T) {
Req: expectPost,
},
}
for i, test := range tests {
for i, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &fake.RESTClient{
GroupVersion: corev1GV,
NegotiatedSerializer: scheme.Codecs,
Resp: test.Resp,
Err: test.HttpErr,
Resp: tt.Resp,
Err: tt.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)
_, 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 {
continue
return
}
if test.Req != nil && !test.Req(client.Req) {
if tt.Req != nil && !tt.Req(client.Req) {
t.Errorf("%d: unexpected request: %#v", i, client.Req)
}
body, err := ioutil.ReadAll(client.Req.Body)
@ -231,28 +244,31 @@ func TestHelperCreate(t *testing.T) {
}
t.Logf("got body: %s", string(body))
expect := []byte{}
if test.ExpectObject != nil {
expect = []byte(runtime.EncodeOrDie(corev1Codec, test.ExpectObject))
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,12 +301,13 @@ func TestHelperGet(t *testing.T) {
},
},
}
for i, test := range tests {
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: test.Resp,
Err: test.HttpErr,
Resp: tt.Resp,
Err: tt.HttpErr,
}
modifier := &Helper{
RESTClient: client,
@ -297,33 +315,37 @@ func TestHelperGet(t *testing.T) {
}
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) != tt.Err {
t.Errorf("unexpected error: %d %t %v", i, tt.Err, err)
}
if err != nil {
continue
return
}
if obj.(*corev1.Pod).Name != "foo" {
t.Errorf("unexpected object: %#v", obj)
}
if test.Req != nil && !test.Req(client.Req) {
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 {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &fake.RESTClient{
GroupVersion: corev1GV,
NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs},
Resp: test.Resp,
Err: test.HttpErr,
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) != test.Err {
t.Errorf("unexpected error: %t %v", test.Err, err)
if (err != nil) != tt.Err {
t.Errorf("unexpected error: %t %v", tt.Err, err)
}
if err != nil {
continue
return
}
if obj.(*corev1.PodList).Items[0].Name != "foo" {
t.Errorf("unexpected object: %#v", obj)
}
if test.Req != nil && !test.Req(client.Req) {
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 {
for _, tt := range tests {
t.Run(tt.Name, func(t *testing.T) {
_, err := modifier.List("bar",
corev1GV.String(),
false,
&metav1.ListOptions{LabelSelector: test.LabelSelector, FieldSelector: test.FieldSelector})
if test.Err {
&metav1.ListOptions{LabelSelector: tt.LabelSelector, FieldSelector: tt.FieldSelector})
if tt.Err {
if err == nil {
t.Errorf("%q expected error: %q", test.Name, test.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)
if err != nil && err.Error() != tt.ErrMsg {
t.Errorf("%q expected error: %q", tt.Name, tt.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,26 +593,27 @@ func TestHelperReplace(t *testing.T) {
Req: expectPut,
},
}
for i, test := range tests {
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: test.HTTPClient,
Resp: test.Resp,
Err: test.HttpErr,
Client: tt.HTTPClient,
Resp: tt.Resp,
Err: tt.HttpErr,
}
modifier := &Helper{
RESTClient: client,
NamespaceScoped: test.NamespaceScoped,
NamespaceScoped: tt.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)
_, 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 {
continue
return
}
if test.Req != nil && !test.Req(test.ExpectPath, client.Req) {
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)
@ -586,11 +621,12 @@ func TestHelperReplace(t *testing.T) {
t.Fatalf("%d: unexpected error: %#v", i, err)
}
expect := []byte{}
if test.ExpectObject != nil {
expect = []byte(runtime.EncodeOrDie(corev1Codec, test.ExpectObject))
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))
}
})
}
}

View File

@ -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) {
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, expectedErr
return 0, "", nil, fmt.Errorf("Failed to get http")
}
return 0, "", nil, fmt.Errorf("Unexpected error")
}, 0, "hello", 3)
assert.Equal(t, expectedErr, actualErr)
assert.Nil(t, actualBytes)
assert.Equal(t, 3, i)
// Test that 500s are retried.
i = 0
actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) {
},
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
}, 0, "hello", 3)
assert.Error(t, actualErr)
assert.Nil(t, actualBytes)
assert.Equal(t, 3, i)
// Test that 300s are not retried
i = 0
actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) {
},
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
}, 0, "hello", 3)
assert.Error(t, actualErr)
assert.Nil(t, actualBytes)
assert.Equal(t, 1, i)
// Test attempt count is respected
i = 0
actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) {
},
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
}, 0, "hello", 1)
assert.Error(t, actualErr)
assert.Nil(t, actualBytes)
assert.Equal(t, 1, i)
// 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: 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 Success
i = 0
b = bytes.Buffer{}
actualBytes, actualErr = readHttpWithRetries(func(url string) (int, string, io.ReadCloser, error) {
},
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(&b), nil
return 200, "Status", ioutil.NopCloser(new(bytes.Buffer)), nil
}
return 501, "Status", nil, nil
}, 0, "hello", 3)
},
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)
assert.Equal(t, 2, i)
} 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)
})
}
}

View File

@ -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)
for index, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
obj, err := generator.Generate(tt.params)
switch {
case test.expectErr && err != nil:
continue // loop, since there's no output to check
case test.expectErr && err == nil:
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)
continue // loop, no expected output object
case !test.expectErr && err != nil:
return // loop, no expected output object
case !tt.expectErr && err != nil:
t.Errorf("%v: unexpected error %v", index, err)
continue // loop, no output object
case !test.expectErr && err == nil:
return // loop, no output object
case !tt.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))
if !reflect.DeepEqual(obj.(*v1.Namespace), tt.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.Namespace))
}
})
}
}

View File

@ -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 <nil> 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)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
obj, err := generator.Generate(tt.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())
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())
}
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
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
}
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 <nil> 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 <nil> 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)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
obj, err := generator.Generate(tt.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())
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())
}
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
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
}
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))
}
})
}
}

View File

@ -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,19 +72,23 @@ 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
}{
{
name: "test1",
add: []string{"FOO=BAR", "EMPTY=", "EQUALS===", "JUSTNAME"},
expected: EnvList{
{"FOO", "BAR"},
@ -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 {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
provider := &PluginDescriptorEnvProvider{
Plugin: test.plugin,
Plugin: tt.plugin,
}
env, _ := provider.Env()
if !reflect.DeepEqual(test.expected, env) {
t.Errorf("%v: expected %v, got %v", test.plugin.Name, test.expected, env)
if !reflect.DeepEqual(tt.expected, env) {
t.Errorf("%v: expected %v, got %v", tt.plugin.Name, tt.expected, env)
}
})
}
}

View File

@ -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)
}
})
}
}

View File

@ -50,14 +50,15 @@ func TestExecRunner(t *testing.T) {
os.Setenv("KUBECTL_PLUGINS_TEST", "ok")
defer os.Unsetenv("KUBECTL_PLUGINS_TEST")
for _, test := range tests {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
streams, _, outBuf, _ := genericclioptions.NewTestIOStreams()
plugin := &Plugin{
Description: Description{
Name: test.name,
Name: tt.name,
ShortDesc: "Test Runner Plugin",
Command: test.command,
Command: tt.command,
},
}
@ -70,13 +71,13 @@ func TestExecRunner(t *testing.T) {
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)
}
})
}
}

View File

@ -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)
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*scheduling.PriorityClass), test.expected) {
t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", name, test.expected, obj.(*scheduling.PriorityClass))
if !reflect.DeepEqual(obj.(*scheduling.PriorityClass), tt.expected) {
t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", tt.name, tt.expected, obj.(*scheduling.PriorityClass))
}
})
}
}

View File

@ -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 {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
filter := &FilterServer{
AcceptPaths: MakeRegexpArrayOrDie(test.acceptPaths),
RejectPaths: MakeRegexpArrayOrDie(test.rejectPaths),
AcceptHosts: MakeRegexpArrayOrDie(test.acceptHosts),
RejectMethods: MakeRegexpArrayOrDie(test.rejectMethods),
AcceptPaths: MakeRegexpArrayOrDie(tt.acceptPaths),
RejectPaths: MakeRegexpArrayOrDie(tt.rejectPaths),
AcceptHosts: MakeRegexpArrayOrDie(tt.acceptHosts),
RejectMethods: MakeRegexpArrayOrDie(tt.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)
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,19 +394,20 @@ 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 {
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)
continue
return
}
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
@ -386,6 +418,7 @@ func TestAPIRequests(t *testing.T) {
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)
}
}()
})
}
}

View File

@ -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)
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*v1.ResourceQuota), test.expected) {
t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", name, test.expected, obj.(*v1.ResourceQuota))
if !reflect.DeepEqual(obj.(*v1.ResourceQuota), tt.expected) {
t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", tt.name, tt.expected, obj.(*v1.ResourceQuota))
}
})
}
}

View File

@ -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 <namespace>:<name>",
},
"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)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
obj, err := generator.Generate(tt.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())
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())
}
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
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
}
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))
}
})
}
}

View File

@ -748,16 +748,17 @@ 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.
t.Run(tt.name, func(t *testing.T) {
oldReady := []int{}
newReady := []int{}
upTo := []int{}
downTo := []int{}
for _, event := range test.expected {
for _, event := range tt.expected {
switch e := event.(type) {
case down:
oldReady = append(oldReady, e.oldReady)
@ -785,7 +786,7 @@ Scaling foo-v2 up to 2
}
return v
}
t.Logf("running test %d (%s) (up: %v, down: %v, oldReady: %v, newReady: %v)", i, test.name, upTo, downTo, oldReady, newReady)
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) {
@ -794,10 +795,10 @@ Scaling foo-v2 up to 2
// call.
expected := -1
switch {
case rc == test.newRc:
case rc == tt.newRc:
t.Logf("scaling up %s to %d", rc.Name, rc.Spec.Replicas)
expected = next(&upTo)
case rc == test.oldRc:
case rc == tt.oldRc:
t.Logf("scaling down %s to %d", rc.Name, rc.Spec.Replicas)
expected = next(&downTo)
}
@ -812,7 +813,7 @@ Scaling foo-v2 up to 2
},
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
return tt.newRc, tt.newRcExists, nil
},
cleanup: func(oldRc, newRc *api.ReplicationController, config *RollingUpdaterConfig) error {
return nil
@ -832,22 +833,23 @@ Scaling foo-v2 up to 2
var buffer bytes.Buffer
config := &RollingUpdaterConfig{
Out: &buffer,
OldRc: test.oldRc,
NewRc: test.newRc,
OldRc: tt.oldRc,
NewRc: tt.newRc,
UpdatePeriod: 0,
Interval: time.Millisecond,
Timeout: time.Millisecond,
CleanupPolicy: DeleteRollingUpdateCleanupPolicy,
MaxUnavailable: test.maxUnavail,
MaxSurge: test.maxSurge,
MaxUnavailable: tt.maxUnavail,
MaxSurge: tt.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())
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 {
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()
deploymentHash, err := util.HashObject(test.newRc, codec)
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,
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, test.newRc) {
t.Errorf("expected:\n%#v\ngot:\n%#v\n", test.newRc, updatedRc)
if !reflect.DeepEqual(updatedRc, tt.newRc) {
t.Errorf("expected:\n%#v\ngot:\n%#v\n", tt.newRc, updatedRc)
}
})
}
}
@ -1163,9 +1169,10 @@ func TestRollingUpdater_cleanupWithClients(t *testing.T) {
//},
}
for _, test := range tests {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
objs := []runtime.Object{rc}
objs = append(objs, test.responses...)
objs = append(objs, tt.responses...)
fake := fake.NewSimpleClientset(objs...)
updater := &RollingUpdater{
ns: "default",
@ -1179,20 +1186,21 @@ func TestRollingUpdater_cleanupWithClients(t *testing.T) {
UpdatePeriod: 0,
Interval: time.Millisecond,
Timeout: time.Millisecond,
CleanupPolicy: test.policy,
CleanupPolicy: tt.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)
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 := test.expected[j], action.GetVerb(); e != a {
t.Errorf("%s: unexpected action: expected %s, got %s", test.name, e, a)
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 {
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 !test.expectError && err != nil {
if !tt.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)
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 {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
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)
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 test.expectErr && err == nil {
if tt.expectErr && err == nil {
t.Errorf("unexpected non-error")
}
if !test.expectErr && err != nil {
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,31 +1768,32 @@ func TestRollingUpdater_readyPods(t *testing.T) {
},
}
for i, test := range tests {
for i, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Logf("evaluating test %d", i)
if test.nowFn == nil {
test.nowFn = func() metav1.Time { return now }
if tt.nowFn == nil {
tt.nowFn = func() metav1.Time { return now }
}
if test.podReadyTimeFn == nil {
test.podReadyTimeFn = test.nowFn
if tt.podReadyTimeFn == nil {
tt.podReadyTimeFn = tt.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 {
for _, ready := range tt.oldPods {
pod := mkpod(tt.oldRc, ready, tt.podReadyTimeFn())
if tt.oldPodDeletions > 0 {
now := metav1.Now()
pod.DeletionTimestamp = &now
test.oldPodDeletions--
tt.oldPodDeletions--
}
pods = append(pods, pod)
}
for _, ready := range test.newPods {
pod := mkpod(test.newRc, ready, test.podReadyTimeFn())
if test.newPodDeletions > 0 {
for _, ready := range tt.newPods {
pod := mkpod(tt.newRc, ready, tt.podReadyTimeFn())
if tt.newPodDeletions > 0 {
now := metav1.Now()
pod.DeletionTimestamp = &now
test.newPodDeletions--
tt.newPodDeletions--
}
pods = append(pods, pod)
}
@ -1783,17 +1803,18 @@ func TestRollingUpdater_readyPods(t *testing.T) {
ns: "default",
rcClient: client.Core(),
podClient: client.Core(),
nowFn: test.nowFn,
nowFn: tt.nowFn,
}
oldReady, newReady, err := updater.readyPods(test.oldRc, test.newRc, test.minReadySeconds)
oldReady, newReady, err := updater.readyPods(tt.oldRc, tt.newRc, tt.minReadySeconds)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if e, a := test.oldReady, oldReady; e != a {
if e, a := tt.oldReady, oldReady; e != a {
t.Errorf("expected old ready %d, got %d", e, a)
}
if e, a := test.newReady, newReady; e != a {
if e, a := tt.newReady, newReady; e != a {
t.Errorf("expected new ready %d, got %d", e, a)
}
})
}
}

View File

@ -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,6 +113,7 @@ func TestDeploymentStatusViewerStatus(t *testing.T) {
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
d := &apps.Deployment{
ObjectMeta: metav1.ObjectMeta{
Namespace: "bar",
@ -136,17 +143,20 @@ func TestDeploymentStatusViewerStatus(t *testing.T) {
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,9 +209,8 @@ func TestDaemonSetStatusViewerStatus(t *testing.T) {
},
}
for i := range tests {
test := tests[i]
t.Logf("testing scenario %d", i)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
d := &apps.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Namespace: "bar",
@ -230,6 +242,7 @@ func TestDaemonSetStatusViewerStatus(t *testing.T) {
test.done,
)
}
})
}
}
@ -350,8 +363,9 @@ func TestStatefulSetStatusViewerStatus(t *testing.T) {
err: false,
},
}
for i := range tests {
test := tests[i]
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
s := newStatefulSet(3)
s.Status = test.status
s.Spec.UpdateStrategy = test.strategy
@ -371,6 +385,7 @@ func TestStatefulSetStatusViewerStatus(t *testing.T) {
if msg != test.msg {
t.Errorf("%s: want message %s got %s", test.name, test.msg, msg)
}
})
}
}

View File

@ -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)
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 !test.expectErr && err != nil {
if !tt.expectErr && err != nil {
t.Errorf("unexpected error: %v", err)
continue
return
}
if test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
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)
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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*v1.Pod), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.Pod))
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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*extensionsv1beta1.Deployment), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*extensionsv1beta1.Deployment))
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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*appsv1beta1.Deployment), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*appsv1beta1.Deployment))
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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*batchv1.Job), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*batchv1.Job))
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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*batchv2alpha1.CronJob), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*batchv2alpha1.CronJob))
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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*batchv1beta1.CronJob), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*batchv1beta1.CronJob))
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)
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(envs, test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v (%s)", test.expected, envs, test.test)
if !reflect.DeepEqual(envs, tt.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v (%s)", tt.expected, envs, tt.test)
}
})
}
}

View File

@ -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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*v1.Secret), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.Secret))
if !reflect.DeepEqual(obj.(*v1.Secret), tt.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.Secret))
}
})
}
}

View File

@ -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 {
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 test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*v1.Secret), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.Secret))
if !reflect.DeepEqual(obj.(*v1.Secret), tt.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.Secret))
}
})
}
}

View File

@ -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 {
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 {
obj, err := generator.Generate(tt.params)
if !tt.expectErr && err != nil {
t.Errorf("case %d, unexpected error: %v", i, err)
continue
return
}
if test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*v1.Secret), test.expected) {
t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, test.expected, obj.(*v1.Secret))
if !reflect.DeepEqual(obj.(*v1.Secret), tt.expected) {
t.Errorf("\ncase %d, expected:\n%#v\nsaw:\n%#v", i, tt.expected, obj.(*v1.Secret))
}
})
}
}

View File

@ -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)
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)
}
})
}
}

View File

@ -43,19 +43,21 @@ func TestServiceAccountGenerate(t *testing.T) {
expectErr: true,
},
}
for _, test := range tests {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
generator := ServiceAccountGeneratorV1{
Name: test.name,
Name: tt.name,
}
obj, err := generator.StructuredGenerate()
if !test.expectErr && err != nil {
if !tt.expectErr && err != nil {
t.Errorf("unexpected error: %v", err)
}
if test.expectErr && err != nil {
continue
if tt.expectErr && err != nil {
return
}
if !reflect.DeepEqual(obj.(*v1.ServiceAccount), test.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*v1.ServiceAccount))
if !reflect.DeepEqual(obj.(*v1.ServiceAccount), tt.expected) {
t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", tt.expected, obj.(*v1.ServiceAccount))
}
})
}
}

View File

@ -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)
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(test.expectedErr) > 0 {
if strings.Contains(err.Error(), test.expectedErr) {
continue
if len(tt.expectedErr) > 0 {
if strings.Contains(err.Error(), tt.expectedErr) {
return
}
t.Fatalf("%s: expected error containing: %q, got: \"%v\"", test.name, test.expectedErr, err)
t.Fatalf("%s: expected error containing: %q, got: \"%v\"", tt.name, tt.expectedErr, err)
}
t.Fatalf("%s: unexpected error: %v", test.name, err)
t.Fatalf("%s: unexpected error: %v", tt.name, err)
}
if len(test.expectedErr) > 0 {
t.Fatalf("%s: expected error containing: %q, got none", test.name, test.expectedErr)
if len(tt.expectedErr) > 0 {
t.Fatalf("%s: expected error containing: %q, got none", tt.name, tt.expectedErr)
}
if !reflect.DeepEqual(test.obj, test.sort) {
t.Errorf("[%s]\nexpected:\n%v\nsaw:\n%v", test.name, test.sort, test.obj)
if !reflect.DeepEqual(tt.obj, tt.sort) {
t.Errorf("[%s]\nexpected:\n%v\nsaw:\n%v", tt.name, tt.sort, tt.obj)
}
})
}
}

View File

@ -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)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
portnum, err := LookupContainerPortNumberByName(tt.pod, tt.portname)
if err != nil {
if tc.err {
continue
if tt.err {
return
}
t.Errorf("%v: unexpected error: %v", tc.name, err)
continue
t.Errorf("%v: unexpected error: %v", tt.name, err)
return
}
if tc.err {
t.Errorf("%v: unexpected success", tc.name)
continue
if tt.err {
t.Errorf("%v: unexpected success", tt.name)
return
}
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)
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 tc.err {
if containerPort != tc.containerPort {
t.Errorf("%v: expected port %v; got %v", tc.name, tc.containerPort, containerPort)
if tt.err {
if containerPort != tt.containerPort {
t.Errorf("%v: expected port %v; got %v", tt.name, tt.containerPort, containerPort)
}
continue
return
}
t.Errorf("%v: unexpected error: %v", tc.name, err)
continue
t.Errorf("%v: unexpected error: %v", tt.name, err)
return
}
if tc.err {
t.Errorf("%v: unexpected success", tc.name)
continue
if tt.err {
t.Errorf("%v: unexpected success", tt.name)
return
}
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)
}
})
}
}

View File

@ -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)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
key, filepath, err := ParseFileSource(tt.input)
if err != nil {
if tc.err {
continue
if tt.err {
return
}
t.Errorf("%v: unexpected error: %v", tc.name, err)
continue
t.Errorf("%v: unexpected error: %v", tt.name, err)
return
}
if tc.err {
t.Errorf("%v: unexpected success", tc.name)
continue
if tt.err {
t.Errorf("%v: unexpected success", tt.name)
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 := tt.key, key; e != a {
t.Errorf("%v: expected key %v; got %v", tt.name, e, a)
return
}
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)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
key, value, err := ParseLiteralSource(tt.input)
if err != nil {
if tc.err {
continue
if tt.err {
return
}
t.Errorf("%v: unexpected error: %v", tc.name, err)
continue
t.Errorf("%v: unexpected error: %v", tt.name, err)
return
}
if tc.err {
t.Errorf("%v: unexpected success", tc.name)
continue
if tt.err {
t.Errorf("%v: unexpected success", tt.name)
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 := tt.key, key; e != a {
t.Errorf("%v: expected key %v; got %v", tt.name, e, a)
return
}
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)
}
})
}
}

View File

@ -126,14 +126,16 @@ func TestConjunctiveSchema(t *testing.T) {
},
}
for _, test := range tests {
schema := ConjunctiveSchema(test.schemas)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
schema := ConjunctiveSchema(tt.schemas)
err := schema.ValidateBytes([]byte{})
if err != nil && test.shouldPass {
t.Errorf("Unexpected error: %v in %s", err, test.name)
if err != nil && tt.shouldPass {
t.Errorf("Unexpected error: %v in %s", err, tt.name)
}
if err == nil && !test.shouldPass {
t.Errorf("Unexpected non-error: %s", test.name)
if err == nil && !tt.shouldPass {
t.Errorf("Unexpected non-error: %s", tt.name)
}
})
}
}