Merge pull request #43490 from xingzhou/add-testcases

Automatic merge from submit-queue (batch tested with PRs 43304, 41427, 43490, 44352)

Supplement unit tests to `kubectl create rolebinding` command.

Supplement unit tests to `kubectl create rolebinding` command,
including:
1. Unit tests for pkg/kubectl/role.go
2. Unit tests for pkg/kubectl/cmd/create_role.go
This commit is contained in:
Kubernetes Submit Queue 2017-04-11 13:46:16 -07:00 committed by GitHub
commit 785299eea5
4 changed files with 278 additions and 0 deletions

View File

@ -120,6 +120,7 @@ go_test(
"namespace_test.go",
"proxy_server_test.go",
"quota_test.go",
"rolebinding_test.go",
"rolling_updater_test.go",
"rollout_status_test.go",
"run_test.go",
@ -147,6 +148,7 @@ go_test(
"//pkg/apis/batch/v2alpha1:go_default_library",
"//pkg/apis/extensions:go_default_library",
"//pkg/apis/extensions/v1beta1:go_default_library",
"//pkg/apis/rbac:go_default_library",
"//pkg/client/clientset_generated/internalclientset:go_default_library",
"//pkg/client/clientset_generated/internalclientset/fake:go_default_library",
"//pkg/client/clientset_generated/internalclientset/typed/batch/internalversion:go_default_library",

View File

@ -158,6 +158,7 @@ go_test(
"create_namespace_test.go",
"create_quota_test.go",
"create_role_test.go",
"create_rolebinding_test.go",
"create_secret_test.go",
"create_service_test.go",
"create_serviceaccount_test.go",

View File

@ -0,0 +1,140 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bytes"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"testing"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/rest/fake"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/rbac"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
)
var groupVersion = schema.GroupVersion{Group: "rbac.authorization.k8s.io", Version: "v1alpha1"}
func TestCreateRoleBinding(t *testing.T) {
expectBinding := &rbac.RoleBinding{
ObjectMeta: v1.ObjectMeta{
Name: "fake-binding",
},
RoleRef: rbac.RoleRef{
APIGroup: rbac.GroupName,
Kind: "Role",
Name: "fake-role",
},
Subjects: []rbac.Subject{
{
Kind: rbac.UserKind,
APIGroup: "rbac.authorization.k8s.io",
Name: "fake-user",
},
{
Kind: rbac.GroupKind,
APIGroup: "rbac.authorization.k8s.io",
Name: "fake-group",
},
{
Kind: rbac.ServiceAccountKind,
Namespace: "fake-namespace",
Name: "fake-account",
},
},
}
f, tf, _, ns := cmdtesting.NewAPIFactory()
info, _ := runtime.SerializerInfoForMediaType(ns.SupportedMediaTypes(), runtime.ContentTypeJSON)
encoder := ns.EncoderForVersion(info.Serializer, groupVersion)
decoder := ns.DecoderToVersion(info.Serializer, groupVersion)
tf.Namespace = "test"
tf.Printer = &testPrinter{}
tf.Client = &RoleBindingRESTClient{
RESTClient: &fake.RESTClient{
APIRegistry: api.Registry,
NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/rolebindings" && m == "POST":
bodyBits, err := ioutil.ReadAll(req.Body)
if err != nil {
t.Fatalf("TestCreateRoleBinding error: %v", err)
return nil, nil
}
if obj, _, err := decoder.Decode(bodyBits, nil, &rbac.RoleBinding{}); err == nil {
if !reflect.DeepEqual(obj.(*rbac.RoleBinding), expectBinding) {
t.Fatalf("TestCreateRoleBinding: expected:\n%#v\nsaw:\n%#v", expectBinding, obj.(*rbac.RoleBinding))
return nil, nil
}
} else {
t.Fatalf("TestCreateRoleBinding error, could not decode the request body into rbac.RoleBinding object: %v", err)
return nil, nil
}
responseBinding := &rbac.RoleBinding{}
responseBinding.Name = "fake-binding"
return &http.Response{StatusCode: 201, Header: defaultHeader(), Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(encoder, responseBinding))))}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
},
}
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateRoleBinding(f, buf)
cmd.Flags().Set("role", "fake-role")
cmd.Flags().Set("user", "fake-user")
cmd.Flags().Set("group", "fake-group")
cmd.Flags().Set("serviceaccount", "fake-namespace:fake-account")
cmd.Run(cmd, []string{"fake-binding"})
}
type RoleBindingRESTClient struct {
*fake.RESTClient
}
func (c *RoleBindingRESTClient) Post() *restclient.Request {
config := restclient.ContentConfig{
ContentType: runtime.ContentTypeJSON,
GroupVersion: &groupVersion,
NegotiatedSerializer: c.NegotiatedSerializer,
}
info, _ := runtime.SerializerInfoForMediaType(c.NegotiatedSerializer.SupportedMediaTypes(), runtime.ContentTypeJSON)
serializers := restclient.Serializers{
Encoder: c.NegotiatedSerializer.EncoderForVersion(info.Serializer, groupVersion),
Decoder: c.NegotiatedSerializer.DecoderToVersion(info.Serializer, groupVersion),
}
if info.StreamSerializer != nil {
serializers.StreamingSerializer = info.StreamSerializer.Serializer
serializers.Framer = info.StreamSerializer.Framer
}
return restclient.NewRequest(c, "POST", &url.URL{Host: "localhost"}, c.VersionedAPIPath, config, serializers, nil, nil)
}

View File

@ -0,0 +1,135 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubectl
import (
"reflect"
"testing"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/apis/rbac"
)
func TestRoleBindingGenerate(t *testing.T) {
tests := map[string]struct {
params map[string]interface{}
expectErrMsg string
expectBinding *rbac.RoleBinding
}{
"test-missing-name": {
params: map[string]interface{}{
"role": "fake-role",
"groups": []string{"fake-group"},
"serviceaccount": []string{"fake-namespace:fake-account"},
},
expectErrMsg: "Parameter: name is required",
},
"test-missing-role-and-clusterrole": {
params: map[string]interface{}{
"name": "fake-binding",
"group": []string{"fake-group"},
"serviceaccount": []string{"fake-namespace:fake-account"},
},
expectErrMsg: "exactly one of clusterrole or role must be specified",
},
"test-both-role-and-clusterrole-provided": {
params: map[string]interface{}{
"name": "fake-binding",
"role": "fake-role",
"clusterrole": "fake-clusterrole",
"group": []string{"fake-group"},
"serviceaccount": []string{"fake-namespace:fake-account"},
},
expectErrMsg: "exactly one of clusterrole or role must be specified",
},
"test-invalid-parameter-type": {
params: map[string]interface{}{
"name": "fake-binding",
"role": []string{"fake-role"},
"group": []string{"fake-group"},
"serviceaccount": []string{"fake-namespace:fake-account"},
},
expectErrMsg: "expected string, saw [fake-role] for 'role'",
},
"test-invalid-serviceaccount": {
params: map[string]interface{}{
"name": "fake-binding",
"role": "fake-role",
"group": []string{"fake-group"},
"serviceaccount": []string{"fake-account"},
},
expectErrMsg: "serviceaccount must be <namespace>:<name>",
},
"test-valid-case": {
params: map[string]interface{}{
"name": "fake-binding",
"role": "fake-role",
"user": []string{"fake-user"},
"group": []string{"fake-group"},
"serviceaccount": []string{"fake-namespace:fake-account"},
},
expectBinding: &rbac.RoleBinding{
ObjectMeta: v1.ObjectMeta{
Name: "fake-binding",
},
RoleRef: rbac.RoleRef{
APIGroup: rbac.GroupName,
Kind: "Role",
Name: "fake-role",
},
Subjects: []rbac.Subject{
{
Kind: rbac.UserKind,
APIGroup: "rbac.authorization.k8s.io",
Name: "fake-user",
},
{
Kind: rbac.GroupKind,
APIGroup: "rbac.authorization.k8s.io",
Name: "fake-group",
},
{
Kind: rbac.ServiceAccountKind,
Namespace: "fake-namespace",
Name: "fake-account",
},
},
},
},
}
generator := RoleBindingGeneratorV1{}
for name, test := range tests {
obj, err := generator.Generate(test.params)
switch {
case test.expectErrMsg != "" && err != nil:
if err.Error() != test.expectErrMsg {
t.Errorf("test '%s': expect error '%s', but saw '%s'", name, test.expectErrMsg, err.Error())
}
continue
case test.expectErrMsg != "" && err == nil:
t.Errorf("test '%s': expected error '%s' and didn't get one", name, test.expectErrMsg)
continue
case test.expectErrMsg == "" && err != nil:
t.Errorf("test '%s': unexpected error %s", name, err.Error())
continue
}
if !reflect.DeepEqual(obj.(*rbac.RoleBinding), test.expectBinding) {
t.Errorf("test '%s': expected:\n%#v\nsaw:\n%#v", name, test.expectBinding, obj.(*rbac.RoleBinding))
}
}
}