Commit 05e3cb8b authored by Chao Xu's avatar Chao Xu

adding a mock.testType to test the generated client code

parent 775369a8
......@@ -18,9 +18,7 @@ limitations under the License.
package generators
import (
"os"
"path/filepath"
"strings"
"k8s.io/kubernetes/cmd/libs/go2idl/args"
"k8s.io/kubernetes/cmd/libs/go2idl/generator"
......@@ -66,6 +64,10 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
continue
}
group := filepath.Base(t.Name.Package)
// Special case for the legacy API.
if group == "api" {
group = ""
}
if _, found := groupToTypes[group]; !found {
groupToTypes[group] = []*types.Type{}
}
......@@ -74,15 +76,9 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
}
return generator.Packages{&generator.DefaultPackage{
PackageName: "unversioned",
PackageName: filepath.Base(arguments.OutputPackagePath),
PackagePath: arguments.OutputPackagePath,
HeaderText: append(boilerplate, []byte(
`
// This file was autogenerated by the command:
// $ `+strings.Join(os.Args, " ")+`
// Do not edit it manually!
`)...),
HeaderText: boilerplate,
PackageDocumentation: []byte(
`// Package unversioned has the automatically generated clients for unversioned resources.
`),
......
......@@ -46,13 +46,20 @@ func (g *genGroup) Namers(c *generator.Context) namer.NameSystems {
}
func (g *genGroup) Imports(c *generator.Context) (imports []string) {
return append(g.imports.ImportLines(), "fmt", "strings")
return append(g.imports.ImportLines(), "fmt")
}
func (g *genGroup) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "$", "$")
const pkgUnversioned = "k8s.io/kubernetes/pkg/client/unversioned"
const pkgLatest = "k8s.io/kubernetes/pkg/api/latest"
prefix := func(group string) string {
if group == "" {
return `"/api"`
}
return `"/apis"`
}
m := map[string]interface{}{
"group": g.group,
"Group": namer.IC(g.group),
......@@ -63,6 +70,7 @@ func (g *genGroup) GenerateType(c *generator.Context, t *types.Type, w io.Writer
"RESTClientFor": c.Universe.Function(types.Name{Package: pkgUnversioned, Name: "RESTClientFor"}),
"latestGroup": c.Universe.Variable(types.Name{Package: pkgLatest, Name: "Group"}),
"GroupOrDie": c.Universe.Variable(types.Name{Package: pkgLatest, Name: "GroupOrDie"}),
"prefix": prefix(g.group),
}
sw.Do(groupInterfaceTemplate, m)
sw.Do(groupClientTemplate, m)
......@@ -135,19 +143,20 @@ func set$.Group$Defaults(config *$.Config|raw$) error {
if err != nil {
return err
}
config.Prefix = "apis/"
config.Prefix = $.prefix$
if config.UserAgent == "" {
config.UserAgent = $.DefaultKubernetesUserAgent|raw$()
}
// TODO: Unconditionally set the config.Version, until we fix the config.
//if config.Version == "" {
config.Version = g.GroupVersion
copyGroupVersion := g.GroupVersion
config.GroupVersion = &copyGroupVersion
//}
versionInterfaces, err := g.InterfacesFor(config.Version)
versionInterfaces, err := g.InterfacesFor(*config.GroupVersion)
if err != nil {
return fmt.Errorf("$.Group$ API version '%s' is not recognized (valid values: %s)",
config.Version, strings.Join($.GroupOrDie|raw$("$.group$").Versions, ", "))
config.GroupVersion, g.GroupVersions)
}
config.Codec = versionInterfaces.Codec
if config.QPS == 0 {
......
......@@ -103,7 +103,7 @@ type $.type|privatePlural$ struct {
`
var newStructTemplate = `
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *ExtensionsClient, namespace string) *$.type|privatePlural$ {
func new$.type|publicPlural$(c *$.Package$Client, namespace string) *$.type|privatePlural$ {
return &$.type|privatePlural${
client: c,
ns: namespace,
......@@ -143,7 +143,7 @@ func (c *$.type|privatePlural$) Delete(name string, options *$.apiDeleteOptions|
if options == nil {
return c.client.Delete().Namespace(c.ns).Resource("$.type|privatePlural$").Name(name).Do().Error()
}
body, err := api.Scheme.EncodeToVersion(options, c.client.APIVersion())
body, err := api.Scheme.EncodeToVersion(options, c.client.APIVersion().String())
if err != nil {
return err
}
......
......@@ -22,24 +22,42 @@ import (
"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/generators"
"github.com/golang/glog"
flag "github.com/spf13/pflag"
)
var test = flag.BoolP("test", "t", false, "set this flag to generate the client code for the testdata")
func main() {
arguments := args.Default()
// Override defaults. These are Kubernetes specific input and output
// locations.
arguments.InputDirs = []string{
"k8s.io/kubernetes/pkg/api",
"k8s.io/kubernetes/pkg/apis/extensions",
"k8s.io/kubernetes/pkg/fields",
"k8s.io/kubernetes/pkg/labels",
"k8s.io/kubernetes/pkg/watch",
"k8s.io/kubernetes/pkg/client/unversioned",
"k8s.io/kubernetes/pkg/api/latest",
flag.Parse()
if *test {
// Override defaults. These are Kubernetes specific input and output
// locations.
arguments.InputDirs = []string{
"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup",
"k8s.io/kubernetes/pkg/fields",
"k8s.io/kubernetes/pkg/labels",
"k8s.io/kubernetes/pkg/watch",
"k8s.io/kubernetes/pkg/client/unversioned",
"k8s.io/kubernetes/pkg/api/latest",
}
// We may change the output path later.
arguments.OutputPackagePath = "k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testoutput"
} else {
// Override defaults. These are Kubernetes specific input and output
// locations.
arguments.InputDirs = []string{
"k8s.io/kubernetes/pkg/api",
"k8s.io/kubernetes/pkg/apis/extensions",
"k8s.io/kubernetes/pkg/fields",
"k8s.io/kubernetes/pkg/labels",
"k8s.io/kubernetes/pkg/watch",
"k8s.io/kubernetes/pkg/client/unversioned",
"k8s.io/kubernetes/pkg/api/latest",
}
// We may change the output path later.
arguments.OutputPackagePath = "k8s.io/kubernetes/pkg/client/clientset/unversioned"
}
// We may change the output path later.
arguments.OutputPackagePath = "k8s.io/kubernetes/pkg/client/clientset/unversioned"
if err := arguments.Execute(
generators.NameSystems(),
......
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 install installs the experimental API group, making it available as
// an option to all of the API encoding/decoding machinery.
package install
import (
"fmt"
"github.com/golang/glog"
"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup/v1"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/latest"
"k8s.io/kubernetes/pkg/api/meta"
"k8s.io/kubernetes/pkg/api/registered"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util/sets"
)
const importPrefix = "k8s.io/kubernetes/pkg/apis/testgroup"
var accessor = meta.NewAccessor()
func init() {
registered.RegisteredGroupVersions = append(registered.RegisteredGroupVersions, v1.SchemeGroupVersion)
groupMeta, err := latest.RegisterGroup("testgroup")
if err != nil {
glog.V(4).Infof("%v", err)
return
}
registeredGroupVersions := []unversioned.GroupVersion{
{
"testgroup",
"v1",
},
}
groupVersion := registeredGroupVersions[0]
*groupMeta = latest.GroupMeta{
GroupVersion: groupVersion,
Codec: runtime.CodecFor(api.Scheme, groupVersion.String()),
}
worstToBestGroupVersions := []unversioned.GroupVersion{}
for i := len(registeredGroupVersions) - 1; i >= 0; i-- {
worstToBestGroupVersions = append(worstToBestGroupVersions, registeredGroupVersions[i])
}
groupMeta.GroupVersions = registeredGroupVersions
groupMeta.SelfLinker = runtime.SelfLinker(accessor)
// the list of kinds that are scoped at the root of the api hierarchy
// if a kind is not enumerated here, it is assumed to have a namespace scope
rootScoped := sets.NewString()
ignoredKinds := sets.NewString()
groupMeta.RESTMapper = api.NewDefaultRESTMapper(worstToBestGroupVersions, interfacesFor, importPrefix, ignoredKinds, rootScoped)
api.RegisterRESTMapper(groupMeta.RESTMapper)
groupMeta.InterfacesFor = interfacesFor
}
// InterfacesFor returns the default Codec and ResourceVersioner for a given version
// string, or an error if the version is not known.
func interfacesFor(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
switch version {
case v1.SchemeGroupVersion:
return &meta.VersionInterfaces{
Codec: v1.Codec,
ObjectConvertor: api.Scheme,
MetadataAccessor: accessor,
}, nil
default:
g, _ := latest.Group("testgroup")
return nil, fmt.Errorf("unsupported storage version: %s (valid: %v)", version, g.GroupVersions)
}
}
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 testgroup
import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
)
var SchemeGroupVersion = unversioned.GroupVersion{Group: "testgroup", Version: ""}
func init() {
// Register the API.
addKnownTypes()
}
// Adds the list of known types to api.Scheme.
func addKnownTypes() {
api.Scheme.AddKnownTypes(SchemeGroupVersion,
&TestType{},
&TestTypeList{},
)
api.Scheme.AddKnownTypes(SchemeGroupVersion,
&unversioned.ListOptions{})
}
func (*TestType) IsAnAPIObject() {}
func (*TestTypeList) IsAnAPIObject() {}
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 testgroup
import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
)
// +genclient=true
type TestType struct {
unversioned.TypeMeta `json:",inline"`
api.ObjectMeta `json:"metadata,omitempty"`
}
type TestTypeList struct {
unversioned.TypeMeta `json:",inline"`
unversioned.ListMeta `json:"metadata,omitempty"`
Items []TestType `json:"items"`
}
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 v1
import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
)
var SchemeGroupVersion = unversioned.GroupVersion{Group: "testgroup", Version: "v1"}
var Codec = runtime.CodecFor(api.Scheme, SchemeGroupVersion.String())
func init() {
// Register the API.
addKnownTypes()
}
// Adds the list of known types to api.Scheme.
func addKnownTypes() {
api.Scheme.AddKnownTypes(SchemeGroupVersion,
&TestType{},
&TestTypeList{},
)
api.Scheme.AddKnownTypes(SchemeGroupVersion,
&unversioned.ListOptions{})
}
func (*TestType) IsAnAPIObject() {}
func (*TestTypeList) IsAnAPIObject() {}
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 v1
import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
)
// +genclient=true
type TestType struct {
unversioned.TypeMeta `json:",inline"`
api.ObjectMeta `json:"metadata,omitempty"`
}
type TestTypeList struct {
unversioned.TypeMeta `json:",inline"`
unversioned.ListMeta `json:"metadata,omitempty"`
Items []TestType `json:"items"`
}
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 unversioned has the automatically generated clients for unversioned resources.
package testoutput
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 testoutput
import (
testgroup "k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup"
api "k8s.io/kubernetes/pkg/api"
unversioned "k8s.io/kubernetes/pkg/api/unversioned"
watch "k8s.io/kubernetes/pkg/watch"
)
// TestTypeNamespacer has methods to work with TestType resources in a namespace
type TestTypeNamespacer interface {
TestTypes(namespace string) TestTypeInterface
}
// TestTypeInterface has methods to work with TestType resources.
type TestTypeInterface interface {
Create(*testgroup.TestType) (*testgroup.TestType, error)
Update(*testgroup.TestType) (*testgroup.TestType, error)
Delete(name string, options *api.DeleteOptions) error
Get(name string) (*testgroup.TestType, error)
List(opts unversioned.ListOptions) (*testgroup.TestTypeList, error)
Watch(opts unversioned.ListOptions) (watch.Interface, error)
}
// testTypes implements TestTypeInterface
type testTypes struct {
client *TestgroupClient
ns string
}
// newTestTypes returns a TestTypes
func newTestTypes(c *TestgroupClient, namespace string) *testTypes {
return &testTypes{
client: c,
ns: namespace,
}
}
// Create takes the representation of a testType and creates it. Returns the server's representation of the testType, and an error, if there is any.
func (c *testTypes) Create(testType *testgroup.TestType) (result *testgroup.TestType, err error) {
result = &testgroup.TestType{}
err = c.client.Post().
Namespace(c.ns).
Resource("testTypes").
Body(testType).
Do().
Into(result)
return
}
// Update takes the representation of a testType and updates it. Returns the server's representation of the testType, and an error, if there is any.
func (c *testTypes) Update(testType *testgroup.TestType) (result *testgroup.TestType, err error) {
result = &testgroup.TestType{}
err = c.client.Put().
Namespace(c.ns).
Resource("testTypes").
Name(testType.Name).
Body(testType).
Do().
Into(result)
return
}
// Delete takes name of the testType and deletes it. Returns an error if one occurs.
func (c *testTypes) Delete(name string, options *api.DeleteOptions) error {
if options == nil {
return c.client.Delete().Namespace(c.ns).Resource("testTypes").Name(name).Do().Error()
}
body, err := api.Scheme.EncodeToVersion(options, c.client.APIVersion().String())
if err != nil {
return err
}
return c.client.Delete().
Namespace(c.ns).
Resource("testTypes").
Name(name).
Body(body).
Do().
Error()
}
// Get takes name of the testType, and returns the corresponding testType object, and an error if there is any.
func (c *testTypes) Get(name string) (result *testgroup.TestType, err error) {
result = &testgroup.TestType{}
err = c.client.Get().
Namespace(c.ns).
Resource("testTypes").
Name(name).
Do().
Into(result)
return
}
// List takes label and field selectors, and returns the list of TestTypes that match those selectors.
func (c *testTypes) List(opts unversioned.ListOptions) (result *testgroup.TestTypeList, err error) {
result = &testgroup.TestTypeList{}
err = c.client.Get().
Namespace(c.ns).
Resource("testTypes").
VersionedParams(&opts, api.Scheme).
Do().
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested testTypes.
func (c *testTypes) Watch(opts unversioned.ListOptions) (watch.Interface, error) {
return c.client.Get().
Prefix("watch").
Namespace(c.ns).
Resource("testTypes").
VersionedParams(&opts, api.Scheme).
Watch()
}
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 testoutput
import (
"fmt"
latest "k8s.io/kubernetes/pkg/api/latest"
unversioned "k8s.io/kubernetes/pkg/client/unversioned"
)
type TestgroupInterface interface {
TestTypeNamespacer
}
// TestgroupClient is used to interact with features provided by the Testgroup group.
type TestgroupClient struct {
*unversioned.RESTClient
}
func (c *TestgroupClient) TestTypes(namespace string) TestTypeInterface {
return newTestTypes(c, namespace)
}
// NewTestgroup creates a new TestgroupClient for the given config.
func NewTestgroup(c *unversioned.Config) (*TestgroupClient, error) {
config := *c
if err := setTestgroupDefaults(&config); err != nil {
return nil, err
}
client, err := unversioned.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &TestgroupClient{client}, nil
}
// NewTestgroupOrDie creates a new TestgroupClient for the given config and
// panics if there is an error in the config.
func NewTestgroupOrDie(c *unversioned.Config) *TestgroupClient {
client, err := NewTestgroup(c)
if err != nil {
panic(err)
}
return client
}
func setTestgroupDefaults(config *unversioned.Config) error {
// if testgroup group is not registered, return an error
g, err := latest.Group("testgroup")
if err != nil {
return err
}
config.Prefix = "/apis"
if config.UserAgent == "" {
config.UserAgent = unversioned.DefaultKubernetesUserAgent()
}
// TODO: Unconditionally set the config.Version, until we fix the config.
//if config.Version == "" {
copyGroupVersion := g.GroupVersion
config.GroupVersion = &copyGroupVersion
//}
versionInterfaces, err := g.InterfacesFor(*config.GroupVersion)
if err != nil {
return fmt.Errorf("Testgroup API version '%s' is not recognized (valid values: %s)",
config.GroupVersion, g.GroupVersions)
}
config.Codec = versionInterfaces.Codec
if config.QPS == 0 {
config.QPS = 5
}
if config.Burst == 0 {
config.Burst = 10
}
return nil
}
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 testoutput_test
import (
"net/http"
"net/url"
"testing"
"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup"
_ "k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup/install"
. "k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testoutput"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/latest"
"k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/api/unversioned"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/client/unversioned/testclient/simple"
"k8s.io/kubernetes/pkg/labels"
)
var testHelper testapi.TestGroup
func init() {
if _, found := testapi.Groups[testgroup.SchemeGroupVersion.Group]; found {
return
}
testapi.Groups[testgroup.SchemeGroupVersion.Group] = testapi.NewTestGroup(
unversioned.GroupVersion{Group: testgroup.SchemeGroupVersion.Group, Version: latest.GroupOrDie(testgroup.SchemeGroupVersion.Group).GroupVersion.Version},
testgroup.SchemeGroupVersion)
testHelper = testapi.Groups[testgroup.SchemeGroupVersion.Group]
}
type DecoratedSimpleClient struct {
*TestgroupClient
simpleClient simple.Client
}
func (c *DecoratedSimpleClient) Setup(t *testing.T) *DecoratedSimpleClient {
c.simpleClient.Setup(t)
url := c.simpleClient.ServerURL()
c.TestgroupClient = NewTestgroupOrDie(&client.Config{
Host: url,
})
return c
}
func TestCreateTestTypes(t *testing.T) {
ns := api.NamespaceDefault
requestTestType := &testgroup.TestType{}
c := DecoratedSimpleClient{
simpleClient: simple.Client{
Request: simple.Request{Method: "POST", Path: testHelper.ResourcePath("testtypes", ns, ""), Query: simple.BuildQueryValues(nil), Body: requestTestType},
Response: simple.Response{
StatusCode: http.StatusOK,
Body: requestTestType,
},
},
}
receivedTestType, err := c.Setup(t).TestTypes(ns).Create(requestTestType)
c.simpleClient.Validate(t, receivedTestType, err)
}
func TestUpdateTestType(t *testing.T) {
ns := api.NamespaceDefault
requestTestType := &testgroup.TestType{
ObjectMeta: api.ObjectMeta{
Name: "foo",
ResourceVersion: "1",
Labels: map[string]string{
"foo": "bar",
"name": "baz",
},
},
}
c := DecoratedSimpleClient{
simpleClient: simple.Client{
Request: simple.Request{Method: "PUT", Path: testHelper.ResourcePath("testtypes", ns, "foo"), Query: simple.BuildQueryValues(nil)},
Response: simple.Response{StatusCode: http.StatusOK, Body: requestTestType},
},
}
receivedTestType, err := c.Setup(t).TestTypes(ns).Update(requestTestType)
c.simpleClient.Validate(t, receivedTestType, err)
}
func TestDeleteTestType(t *testing.T) {
ns := api.NamespaceDefault
c := DecoratedSimpleClient{
simpleClient: simple.Client{
Request: simple.Request{Method: "DELETE", Path: testHelper.ResourcePath("testtypes", ns, "foo"), Query: simple.BuildQueryValues(nil)},
Response: simple.Response{StatusCode: http.StatusOK},
},
}
err := c.Setup(t).TestTypes(ns).Delete("foo", nil)
c.simpleClient.Validate(t, nil, err)
}
func TestGetTestType(t *testing.T) {
ns := api.NamespaceDefault
c := DecoratedSimpleClient{
simpleClient: simple.Client{
Request: simple.Request{Method: "GET", Path: testHelper.ResourcePath("testtypes", ns, "foo"), Query: simple.BuildQueryValues(nil)},
Response: simple.Response{
StatusCode: http.StatusOK,
Body: &testgroup.TestType{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{
"foo": "bar",
"name": "baz",
},
},
},
},
},
}
receivedTestType, err := c.Setup(t).TestTypes(ns).Get("foo")
c.simpleClient.Validate(t, receivedTestType, err)
}
func TestGetTestTypeWithNoName(t *testing.T) {
ns := api.NamespaceDefault
c := DecoratedSimpleClient{
simpleClient: simple.Client{Error: true},
}
receivedTestType, err := c.Setup(t).TestTypes(ns).Get("")
if (err != nil) && (err.Error() != simple.NameRequiredError) {
t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err)
}
c.simpleClient.Validate(t, receivedTestType, err)
}
func TestListEmptyTestTypes(t *testing.T) {
ns := api.NamespaceDefault
c := DecoratedSimpleClient{
simpleClient: simple.Client{
Request: simple.Request{Method: "GET", Path: testHelper.ResourcePath("testtypes", ns, ""), Query: simple.BuildQueryValues(nil)},
Response: simple.Response{StatusCode: http.StatusOK, Body: &testgroup.TestTypeList{}},
},
}
podList, err := c.Setup(t).TestTypes(ns).List(unversioned.ListOptions{})
c.simpleClient.Validate(t, podList, err)
}
func TestListTestTypes(t *testing.T) {
ns := api.NamespaceDefault
c := DecoratedSimpleClient{
simpleClient: simple.Client{
Request: simple.Request{Method: "GET", Path: testHelper.ResourcePath("testtypes", ns, ""), Query: simple.BuildQueryValues(nil)},
Response: simple.Response{StatusCode: http.StatusOK,
Body: &testgroup.TestTypeList{
Items: []testgroup.TestType{
{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{
"foo": "bar",
"name": "baz",
},
},
},
},
},
},
},
}
receivedTestTypeList, err := c.Setup(t).TestTypes(ns).List(unversioned.ListOptions{})
c.simpleClient.Validate(t, receivedTestTypeList, err)
}
func TestListTestTypesLabels(t *testing.T) {
ns := api.NamespaceDefault
labelSelectorQueryParamName := unversioned.LabelSelectorQueryParam(testHelper.GroupVersion().String())
c := DecoratedSimpleClient{
simpleClient: simple.Client{
Request: simple.Request{
Method: "GET",
Path: testHelper.ResourcePath("testtypes", ns, ""),
Query: simple.BuildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})},
Response: simple.Response{
StatusCode: http.StatusOK,
Body: &testgroup.TestTypeList{
Items: []testgroup.TestType{
{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{
"foo": "bar",
"name": "baz",
},
},
},
},
},
},
},
}
c.Setup(t)
c.simpleClient.QueryValidator[labelSelectorQueryParamName] = simple.ValidateLabels
selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector()
options := unversioned.ListOptions{LabelSelector: unversioned.LabelSelector{selector}}
receivedTestTypeList, err := c.TestTypes(ns).List(options)
c.simpleClient.Validate(t, receivedTestTypeList, err)
}
......@@ -200,3 +200,7 @@ func GetCodecForObject(obj runtime.Object) (runtime.Codec, error) {
}
return nil, fmt.Errorf("unexpected kind: %v", kind)
}
func NewTestGroup(external, internal unversioned.GroupVersion) TestGroup {
return TestGroup{external, internal}
}
......@@ -91,11 +91,15 @@ func (c *Client) Setup(t *testing.T) *Client {
return c
}
func (c *Client) ServerURL() string {
return c.server.URL
}
func (c *Client) Validate(t *testing.T, received runtime.Object, err error) {
c.ValidateCommon(t, err)
if c.Response.Body != nil && !api.Semantic.DeepDerivative(c.Response.Body, received) {
t.Errorf("bad response for request %#v: expected %#v, got %#v", c.Request, c.Response.Body, received)
t.Errorf("bad response for request %#v: \nexpected %#v\ngot %#v\n", c.Request, c.Response.Body, received)
}
}
......@@ -199,23 +203,14 @@ func body(t *testing.T, obj runtime.Object, raw *string) *string {
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
}
// TODO: caesarxuchao: we should detect which group an object belongs to
// by using the version returned by Schem.ObjectVersionAndKind() once we
// split the schemes for internal objects.
// TODO: caesarxuchao: we should add a map from kind to group in Scheme.
var bs []byte
if api.Scheme.Recognizes(testapi.Default.GroupVersion().WithKind(fqKind.Kind)) {
bs, err = testapi.Default.Codec().Encode(obj)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
}
} else if api.Scheme.Recognizes(testapi.Extensions.GroupVersion().WithKind(fqKind.Kind)) {
bs, err = testapi.Extensions.Codec().Encode(obj)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
}
} else {
t.Errorf("unexpected kind: %v", fqKind.Kind)
g, found := testapi.Groups[fqKind.GroupVersion().Group]
if !found {
t.Errorf("Group %s is not registered in testapi", fqKind.GroupVersion().Group)
}
bs, err = g.Codec().Encode(obj)
if err != nil {
t.Errorf("unexpected encoding error: %v", err)
}
body := string(bs)
return &body
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment