k3s/pkg/apiserver/apiserver_test.go

726 lines
21 KiB
Go
Raw Normal View History

2014-06-06 23:40:48 +00:00
/*
Copyright 2014 Google Inc. 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.
*/
2014-06-23 18:32:11 +00:00
2014-06-06 23:40:48 +00:00
package apiserver
import (
"bytes"
2014-07-31 18:16:13 +00:00
"encoding/json"
"errors"
2014-06-06 23:40:48 +00:00
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync"
2014-06-06 23:40:48 +00:00
"testing"
2014-06-25 20:21:32 +00:00
"time"
2014-06-17 01:03:44 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
apierrs "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
2014-06-17 01:03:44 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
2014-07-31 18:16:13 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/version"
"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
2014-06-06 23:40:48 +00:00
)
2014-07-16 21:30:28 +00:00
func convert(obj interface{}) (interface{}, error) {
return obj, nil
}
var codec = runtime.DefaultCodec
func init() {
runtime.AddKnownTypes("", Simple{}, SimpleList{})
runtime.AddKnownTypes("v1beta1", Simple{}, SimpleList{})
}
2014-06-06 23:40:48 +00:00
type Simple struct {
2014-06-20 23:50:56 +00:00
api.JSONBase `yaml:",inline" json:",inline"`
Name string `yaml:"name,omitempty" json:"name,omitempty"`
2014-06-06 23:40:48 +00:00
}
type SimpleList struct {
2014-06-20 23:50:56 +00:00
api.JSONBase `yaml:",inline" json:",inline"`
Items []Simple `yaml:"items,omitempty" json:"items,omitempty"`
2014-06-06 23:40:48 +00:00
}
type SimpleRESTStorage struct {
errors map[string]error
2014-06-06 23:40:48 +00:00
list []Simple
item Simple
deleted string
updated *Simple
created *Simple
2014-06-25 20:21:32 +00:00
// These are set when Watch is called
fakeWatch *watch.FakeWatcher
requestedLabelSelector labels.Selector
requestedFieldSelector labels.Selector
requestedResourceVersion uint64
2014-08-25 21:36:15 +00:00
// The location
requestedResourceLocationID string
// If non-nil, called inside the WorkFunc when answering update, delete, create.
2014-07-28 13:15:50 +00:00
// obj receives the original input to the update, delete, or create call.
2014-06-25 20:21:32 +00:00
injectedFunction func(obj interface{}) (returnObj interface{}, err error)
2014-06-06 23:40:48 +00:00
}
2014-06-18 23:47:41 +00:00
func (storage *SimpleRESTStorage) List(labels.Selector) (interface{}, error) {
result := &SimpleList{
2014-06-06 23:40:48 +00:00
Items: storage.list,
}
return result, storage.errors["list"]
2014-06-06 23:40:48 +00:00
}
func (storage *SimpleRESTStorage) Get(id string) (interface{}, error) {
return storage.item, storage.errors["get"]
2014-06-06 23:40:48 +00:00
}
func (storage *SimpleRESTStorage) Delete(id string) (<-chan interface{}, error) {
2014-06-06 23:40:48 +00:00
storage.deleted = id
if err := storage.errors["delete"]; err != nil {
return nil, err
2014-06-25 20:21:32 +00:00
}
return MakeAsync(func() (interface{}, error) {
if storage.injectedFunction != nil {
return storage.injectedFunction(id)
}
return &api.Status{Status: api.StatusSuccess}, nil
2014-06-25 20:21:32 +00:00
}), nil
2014-06-06 23:40:48 +00:00
}
func (storage *SimpleRESTStorage) New() interface{} {
return &Simple{}
2014-06-06 23:40:48 +00:00
}
2014-06-25 20:21:32 +00:00
func (storage *SimpleRESTStorage) Create(obj interface{}) (<-chan interface{}, error) {
storage.created = obj.(*Simple)
if err := storage.errors["create"]; err != nil {
return nil, err
2014-06-25 20:21:32 +00:00
}
return MakeAsync(func() (interface{}, error) {
if storage.injectedFunction != nil {
return storage.injectedFunction(obj)
}
return obj, nil
}), nil
2014-06-06 23:40:48 +00:00
}
2014-06-25 20:21:32 +00:00
func (storage *SimpleRESTStorage) Update(obj interface{}) (<-chan interface{}, error) {
storage.updated = obj.(*Simple)
if err := storage.errors["update"]; err != nil {
return nil, err
2014-06-25 20:21:32 +00:00
}
return MakeAsync(func() (interface{}, error) {
if storage.injectedFunction != nil {
return storage.injectedFunction(obj)
}
return obj, nil
}), nil
2014-06-06 23:40:48 +00:00
}
// Implement ResourceWatcher.
func (storage *SimpleRESTStorage) Watch(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error) {
storage.requestedLabelSelector = label
storage.requestedFieldSelector = field
storage.requestedResourceVersion = resourceVersion
if err := storage.errors["watch"]; err != nil {
return nil, err
}
storage.fakeWatch = watch.NewFake()
return storage.fakeWatch, nil
}
2014-08-25 21:36:15 +00:00
// Implement Redirector.
func (storage *SimpleRESTStorage) ResourceLocation(id string) (string, error) {
storage.requestedResourceLocationID = id
if err := storage.errors["resourceLocation"]; err != nil {
return "", err
}
return id, nil
}
2014-06-06 23:40:48 +00:00
func extractBody(response *http.Response, object interface{}) (string, error) {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return string(body), err
}
err = codec.DecodeInto(body, object)
2014-06-06 23:40:48 +00:00
return string(body), err
}
2014-07-31 18:16:13 +00:00
func TestNotFound(t *testing.T) {
type T struct {
Method string
Path string
}
cases := map[string]T{
"PATCH method": {"PATCH", "/prefix/version/foo"},
"GET long prefix": {"GET", "/prefix/"},
"GET missing storage": {"GET", "/prefix/version/blah"},
"GET with extra segment": {"GET", "/prefix/version/foo/bar/baz"},
"POST with extra segment": {"POST", "/prefix/version/foo/bar"},
"DELETE without extra segment": {"DELETE", "/prefix/version/foo"},
"DELETE with extra segment": {"DELETE", "/prefix/version/foo/bar/baz"},
"PUT without extra segment": {"PUT", "/prefix/version/foo"},
"PUT with extra segment": {"PUT", "/prefix/version/foo/bar/baz"},
"watch missing storage": {"GET", "/prefix/version/watch/"},
"watch with bad method": {"POST", "/prefix/version/watch/foo/bar"},
2014-07-31 18:16:13 +00:00
}
handler := Handle(map[string]RESTStorage{
2014-07-31 18:16:13 +00:00
"foo": &SimpleRESTStorage{},
}, codec, "/prefix/version")
2014-07-31 18:16:13 +00:00
server := httptest.NewServer(handler)
client := http.Client{}
for k, v := range cases {
request, err := http.NewRequest(v.Method, server.URL+v.Path, nil)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-07-31 18:16:13 +00:00
response, err := client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-07-31 18:16:13 +00:00
if response.StatusCode != http.StatusNotFound {
t.Errorf("Expected %d for %s (%s), Got %#v", http.StatusNotFound, v, k, response)
}
}
}
func TestVersion(t *testing.T) {
handler := Handle(map[string]RESTStorage{}, codec, "/prefix/version")
2014-07-31 18:16:13 +00:00
server := httptest.NewServer(handler)
client := http.Client{}
request, err := http.NewRequest("GET", server.URL+"/version", nil)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-07-31 18:16:13 +00:00
response, err := client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-07-31 18:16:13 +00:00
var info version.Info
err = json.NewDecoder(response.Body).Decode(&info)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-07-31 18:16:13 +00:00
if !reflect.DeepEqual(version.Get(), info) {
t.Errorf("Expected %#v, Got %#v", version.Get(), info)
}
}
2014-06-06 23:40:48 +00:00
func TestSimpleList(t *testing.T) {
storage := map[string]RESTStorage{}
simpleStorage := SimpleRESTStorage{}
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
2014-06-06 23:40:48 +00:00
server := httptest.NewServer(handler)
resp, err := http.Get(server.URL + "/prefix/version/simple")
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected status: %d, Expected: %d, %#v", resp.StatusCode, http.StatusOK, resp)
2014-06-06 23:40:48 +00:00
}
}
func TestErrorList(t *testing.T) {
storage := map[string]RESTStorage{}
simpleStorage := SimpleRESTStorage{
errors: map[string]error{"list": fmt.Errorf("test Error")},
2014-06-06 23:40:48 +00:00
}
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
2014-06-06 23:40:48 +00:00
server := httptest.NewServer(handler)
resp, err := http.Get(server.URL + "/prefix/version/simple")
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
if resp.StatusCode != http.StatusInternalServerError {
t.Errorf("Unexpected status: %d, Expected: %d, %#v", resp.StatusCode, http.StatusOK, resp)
2014-06-06 23:40:48 +00:00
}
}
func TestNonEmptyList(t *testing.T) {
storage := map[string]RESTStorage{}
simpleStorage := SimpleRESTStorage{
list: []Simple{
2014-06-12 21:09:40 +00:00
{
2014-07-16 21:30:28 +00:00
JSONBase: api.JSONBase{Kind: "Simple"},
Name: "foo",
2014-06-06 23:40:48 +00:00
},
},
}
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
2014-06-06 23:40:48 +00:00
server := httptest.NewServer(handler)
resp, err := http.Get(server.URL + "/prefix/version/simple")
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
if resp.StatusCode != http.StatusOK {
t.Errorf("Unexpected status: %d, Expected: %d, %#v", resp.StatusCode, http.StatusOK, resp)
2014-06-06 23:40:48 +00:00
}
var listOut SimpleList
body, err := extractBody(resp, &listOut)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
if len(listOut.Items) != 1 {
t.Errorf("Unexpected response: %#v", listOut)
return
2014-06-06 23:40:48 +00:00
}
if listOut.Items[0].Name != simpleStorage.list[0].Name {
t.Errorf("Unexpected data: %#v, %s", listOut.Items[0], string(body))
}
}
func TestGet(t *testing.T) {
storage := map[string]RESTStorage{}
simpleStorage := SimpleRESTStorage{
item: Simple{
Name: "foo",
},
}
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
2014-06-06 23:40:48 +00:00
server := httptest.NewServer(handler)
resp, err := http.Get(server.URL + "/prefix/version/simple/id")
var itemOut Simple
body, err := extractBody(resp, &itemOut)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
if itemOut.Name != simpleStorage.item.Name {
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simpleStorage.item, string(body))
}
}
func TestGetMissing(t *testing.T) {
storage := map[string]RESTStorage{}
simpleStorage := SimpleRESTStorage{
errors: map[string]error{"get": apierrs.NewNotFound("simple", "id")},
}
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
server := httptest.NewServer(handler)
resp, err := http.Get(server.URL + "/prefix/version/simple/id")
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if resp.StatusCode != http.StatusNotFound {
t.Errorf("Unexpected response %#v", resp)
}
}
2014-06-06 23:40:48 +00:00
func TestDelete(t *testing.T) {
storage := map[string]RESTStorage{}
simpleStorage := SimpleRESTStorage{}
ID := "id"
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
2014-06-06 23:40:48 +00:00
server := httptest.NewServer(handler)
client := http.Client{}
request, err := http.NewRequest("DELETE", server.URL+"/prefix/version/simple/"+ID, nil)
_, err = client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
if simpleStorage.deleted != ID {
2014-07-18 19:03:22 +00:00
t.Errorf("Unexpected delete: %s, expected %s", simpleStorage.deleted, ID)
2014-06-06 23:40:48 +00:00
}
}
func TestDeleteMissing(t *testing.T) {
storage := map[string]RESTStorage{}
ID := "id"
simpleStorage := SimpleRESTStorage{
errors: map[string]error{"delete": apierrs.NewNotFound("simple", ID)},
}
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
server := httptest.NewServer(handler)
client := http.Client{}
request, err := http.NewRequest("DELETE", server.URL+"/prefix/version/simple/"+ID, nil)
response, err := client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if response.StatusCode != http.StatusNotFound {
t.Errorf("Unexpected response %#v", response)
}
}
2014-06-06 23:40:48 +00:00
func TestUpdate(t *testing.T) {
storage := map[string]RESTStorage{}
simpleStorage := SimpleRESTStorage{}
ID := "id"
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
2014-06-06 23:40:48 +00:00
server := httptest.NewServer(handler)
item := Simple{
Name: "bar",
}
body, err := codec.Encode(item)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
client := http.Client{}
request, err := http.NewRequest("PUT", server.URL+"/prefix/version/simple/"+ID, bytes.NewReader(body))
_, err = client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
if simpleStorage.updated.Name != item.Name {
t.Errorf("Unexpected update value %#v, expected %#v.", simpleStorage.updated, item)
}
}
func TestUpdateMissing(t *testing.T) {
storage := map[string]RESTStorage{}
ID := "id"
simpleStorage := SimpleRESTStorage{
errors: map[string]error{"update": apierrs.NewNotFound("simple", ID)},
}
storage["simple"] = &simpleStorage
handler := Handle(storage, codec, "/prefix/version")
server := httptest.NewServer(handler)
item := Simple{
Name: "bar",
}
body, err := codec.Encode(item)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
client := http.Client{}
request, err := http.NewRequest("PUT", server.URL+"/prefix/version/simple/"+ID, bytes.NewReader(body))
response, err := client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if response.StatusCode != http.StatusNotFound {
t.Errorf("Unexpected response %#v", response)
}
}
2014-06-06 23:40:48 +00:00
func TestCreate(t *testing.T) {
2014-06-25 20:21:32 +00:00
simpleStorage := &SimpleRESTStorage{}
handler := Handle(map[string]RESTStorage{
2014-06-25 20:21:32 +00:00
"foo": simpleStorage,
}, codec, "/prefix/version")
handler.(*defaultAPIServer).group.handler.asyncOpWait = 0
2014-06-06 23:40:48 +00:00
server := httptest.NewServer(handler)
client := http.Client{}
2014-07-16 21:30:28 +00:00
simple := Simple{
Name: "foo",
}
data, _ := codec.Encode(simple)
2014-06-06 23:40:48 +00:00
request, err := http.NewRequest("POST", server.URL+"/prefix/version/foo", bytes.NewBuffer(data))
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-06 23:40:48 +00:00
response, err := client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if response.StatusCode != http.StatusAccepted {
2014-06-06 23:40:48 +00:00
t.Errorf("Unexpected response %#v", response)
}
2014-06-25 20:21:32 +00:00
var itemOut api.Status
2014-06-06 23:40:48 +00:00
body, err := extractBody(response, &itemOut)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
Evolve the api.Status object with Reason/Details Contains breaking API change on api.Status#Details (type change) Turn Details from string -> StatusDetails - a general bucket for keyed error behavior. Define an open enumeration ReasonType exposed as Reason on the status object to provide machine readable subcategorization beyond HTTP Status Code. Define a human readable field Message which is common convention (previously this was joined into Details). Precedence order: HTTP Status Code, Reason, Details. apiserver would impose restraints on the ReasonTypes defined by the main apiobject, and ensure their use is consistent. There are four long term scenarios this change supports: 1. Allow a client access to a machine readable field that can be easily switched on for improving or translating the generic server Message. 2. Return a 404 when a composite operation on multiple resources fails with enough data so that a client can distinguish which item does not exist. E.g. resource Parent and resource Child, POST /parents/1/children to create a new Child, but /parents/1 is deleted. POST returns 404, ReasonTypeNotFound, and Details.ID = "1", Details.Kind = "parent" 3. Allow a client to receive validation data that is keyed by attribute for building user facing UIs around field submission. Validation is usually expressed as map[string][]string, but that type is less appropriate for many other uses. 4. Allow specific API errors to return more granular failure status for specific operations. An example might be a minion proxy, where the operation that failed may be both proxying OR the minion itself. In this case a reason may be defined "proxy_failed" corresponding to 502, where the Details field may be extended to contain a nested error object. At this time only ID and Kind are exposed
2014-07-31 18:12:26 +00:00
if itemOut.Status != api.StatusWorking || itemOut.Details == nil || itemOut.Details.ID == "" {
2014-06-25 20:21:32 +00:00
t.Errorf("Unexpected status: %#v (%s)", itemOut, string(body))
}
}
func TestCreateNotFound(t *testing.T) {
handler := Handle(map[string]RESTStorage{
2014-07-31 18:16:13 +00:00
"simple": &SimpleRESTStorage{
// storage.Create can fail with not found error in theory.
// See https://github.com/GoogleCloudPlatform/kubernetes/pull/486#discussion_r15037092.
errors: map[string]error{"create": apierrs.NewNotFound("simple", "id")},
2014-07-31 18:16:13 +00:00
},
}, codec, "/prefix/version")
server := httptest.NewServer(handler)
client := http.Client{}
simple := Simple{Name: "foo"}
data, _ := codec.Encode(simple)
2014-07-31 18:16:13 +00:00
request, err := http.NewRequest("POST", server.URL+"/prefix/version/simple", bytes.NewBuffer(data))
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
response, err := client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if response.StatusCode != http.StatusNotFound {
t.Errorf("Unexpected response %#v", response)
}
}
2014-06-25 20:21:32 +00:00
func TestParseTimeout(t *testing.T) {
if d := parseTimeout(""); d != 30*time.Second {
t.Errorf("blank timeout produces %v", d)
}
if d := parseTimeout("not a timeout"); d != 30*time.Second {
t.Errorf("bad timeout produces %v", d)
}
if d := parseTimeout("10s"); d != 10*time.Second {
t.Errorf("10s timeout produced: %v", d)
2014-06-06 23:40:48 +00:00
}
}
func TestSyncCreate(t *testing.T) {
storage := SimpleRESTStorage{
2014-06-25 20:21:32 +00:00
injectedFunction: func(obj interface{}) (interface{}, error) {
2014-07-31 18:16:13 +00:00
time.Sleep(5 * time.Millisecond)
2014-06-25 20:21:32 +00:00
return obj, nil
},
}
handler := Handle(map[string]RESTStorage{
"foo": &storage,
}, codec, "/prefix/version")
server := httptest.NewServer(handler)
client := http.Client{}
2014-07-16 21:30:28 +00:00
simple := Simple{
Name: "foo",
}
data, _ := codec.Encode(simple)
request, err := http.NewRequest("POST", server.URL+"/prefix/version/foo?sync=true", bytes.NewBuffer(data))
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
wg := sync.WaitGroup{}
wg.Add(1)
var response *http.Response
go func() {
response, err = client.Do(request)
wg.Done()
}()
wg.Wait()
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
var itemOut Simple
body, err := extractBody(response, &itemOut)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-06-25 20:21:32 +00:00
if !reflect.DeepEqual(itemOut, simple) {
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simple, string(body))
}
2014-06-25 20:21:32 +00:00
if response.StatusCode != http.StatusOK {
t.Errorf("Unexpected status: %d, Expected: %d, %#v", response.StatusCode, http.StatusOK, response)
}
}
2014-07-31 18:16:13 +00:00
func expectApiStatus(t *testing.T, method, url string, data []byte, code int) *api.Status {
client := http.Client{}
request, err := http.NewRequest(method, url, bytes.NewBuffer(data))
if err != nil {
t.Fatalf("unexpected error %#v", err)
return nil
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("unexpected error on %s %s: %v", method, url, err)
2014-07-31 18:16:13 +00:00
return nil
}
var status api.Status
_, err = extractBody(response, &status)
if err != nil {
t.Fatalf("unexpected error on %s %s: %v", method, url, err)
2014-07-31 18:16:13 +00:00
return nil
}
if code != response.StatusCode {
t.Fatalf("Expected %s %s to return %d, Got %d", method, url, code, response.StatusCode)
2014-07-31 18:16:13 +00:00
}
return &status
}
func TestAsyncDelayReturnsError(t *testing.T) {
storage := SimpleRESTStorage{
injectedFunction: func(obj interface{}) (interface{}, error) {
return nil, apierrs.NewAlreadyExists("foo", "bar")
2014-07-31 18:16:13 +00:00
},
}
handler := Handle(map[string]RESTStorage{"foo": &storage}, codec, "/prefix/version")
handler.(*defaultAPIServer).group.handler.asyncOpWait = time.Millisecond / 2
2014-07-31 18:16:13 +00:00
server := httptest.NewServer(handler)
status := expectApiStatus(t, "DELETE", fmt.Sprintf("%s/prefix/version/foo/bar", server.URL), nil, http.StatusConflict)
if status.Status != api.StatusFailure || status.Message == "" || status.Details == nil || status.Reason != api.StatusReasonAlreadyExists {
2014-07-31 18:16:13 +00:00
t.Errorf("Unexpected status %#v", status)
}
}
func TestAsyncCreateError(t *testing.T) {
ch := make(chan struct{})
storage := SimpleRESTStorage{
injectedFunction: func(obj interface{}) (interface{}, error) {
<-ch
return nil, apierrs.NewAlreadyExists("foo", "bar")
2014-07-31 18:16:13 +00:00
},
}
handler := Handle(map[string]RESTStorage{"foo": &storage}, codec, "/prefix/version")
handler.(*defaultAPIServer).group.handler.asyncOpWait = 0
2014-07-31 18:16:13 +00:00
server := httptest.NewServer(handler)
simple := Simple{Name: "foo"}
data, _ := codec.Encode(simple)
2014-07-31 18:16:13 +00:00
status := expectApiStatus(t, "POST", fmt.Sprintf("%s/prefix/version/foo", server.URL), data, http.StatusAccepted)
Evolve the api.Status object with Reason/Details Contains breaking API change on api.Status#Details (type change) Turn Details from string -> StatusDetails - a general bucket for keyed error behavior. Define an open enumeration ReasonType exposed as Reason on the status object to provide machine readable subcategorization beyond HTTP Status Code. Define a human readable field Message which is common convention (previously this was joined into Details). Precedence order: HTTP Status Code, Reason, Details. apiserver would impose restraints on the ReasonTypes defined by the main apiobject, and ensure their use is consistent. There are four long term scenarios this change supports: 1. Allow a client access to a machine readable field that can be easily switched on for improving or translating the generic server Message. 2. Return a 404 when a composite operation on multiple resources fails with enough data so that a client can distinguish which item does not exist. E.g. resource Parent and resource Child, POST /parents/1/children to create a new Child, but /parents/1 is deleted. POST returns 404, ReasonTypeNotFound, and Details.ID = "1", Details.Kind = "parent" 3. Allow a client to receive validation data that is keyed by attribute for building user facing UIs around field submission. Validation is usually expressed as map[string][]string, but that type is less appropriate for many other uses. 4. Allow specific API errors to return more granular failure status for specific operations. An example might be a minion proxy, where the operation that failed may be both proxying OR the minion itself. In this case a reason may be defined "proxy_failed" corresponding to 502, where the Details field may be extended to contain a nested error object. At this time only ID and Kind are exposed
2014-07-31 18:12:26 +00:00
if status.Status != api.StatusWorking || status.Details == nil || status.Details.ID == "" {
2014-07-31 18:16:13 +00:00
t.Errorf("Unexpected status %#v", status)
}
Evolve the api.Status object with Reason/Details Contains breaking API change on api.Status#Details (type change) Turn Details from string -> StatusDetails - a general bucket for keyed error behavior. Define an open enumeration ReasonType exposed as Reason on the status object to provide machine readable subcategorization beyond HTTP Status Code. Define a human readable field Message which is common convention (previously this was joined into Details). Precedence order: HTTP Status Code, Reason, Details. apiserver would impose restraints on the ReasonTypes defined by the main apiobject, and ensure their use is consistent. There are four long term scenarios this change supports: 1. Allow a client access to a machine readable field that can be easily switched on for improving or translating the generic server Message. 2. Return a 404 when a composite operation on multiple resources fails with enough data so that a client can distinguish which item does not exist. E.g. resource Parent and resource Child, POST /parents/1/children to create a new Child, but /parents/1 is deleted. POST returns 404, ReasonTypeNotFound, and Details.ID = "1", Details.Kind = "parent" 3. Allow a client to receive validation data that is keyed by attribute for building user facing UIs around field submission. Validation is usually expressed as map[string][]string, but that type is less appropriate for many other uses. 4. Allow specific API errors to return more granular failure status for specific operations. An example might be a minion proxy, where the operation that failed may be both proxying OR the minion itself. In this case a reason may be defined "proxy_failed" corresponding to 502, where the Details field may be extended to contain a nested error object. At this time only ID and Kind are exposed
2014-07-31 18:12:26 +00:00
otherStatus := expectApiStatus(t, "GET", fmt.Sprintf("%s/prefix/version/operations/%s", server.URL, status.Details.ID), []byte{}, http.StatusAccepted)
2014-07-31 18:16:13 +00:00
if !reflect.DeepEqual(status, otherStatus) {
t.Errorf("Expected %#v, Got %#v", status, otherStatus)
}
ch <- struct{}{}
time.Sleep(time.Millisecond)
Evolve the api.Status object with Reason/Details Contains breaking API change on api.Status#Details (type change) Turn Details from string -> StatusDetails - a general bucket for keyed error behavior. Define an open enumeration ReasonType exposed as Reason on the status object to provide machine readable subcategorization beyond HTTP Status Code. Define a human readable field Message which is common convention (previously this was joined into Details). Precedence order: HTTP Status Code, Reason, Details. apiserver would impose restraints on the ReasonTypes defined by the main apiobject, and ensure their use is consistent. There are four long term scenarios this change supports: 1. Allow a client access to a machine readable field that can be easily switched on for improving or translating the generic server Message. 2. Return a 404 when a composite operation on multiple resources fails with enough data so that a client can distinguish which item does not exist. E.g. resource Parent and resource Child, POST /parents/1/children to create a new Child, but /parents/1 is deleted. POST returns 404, ReasonTypeNotFound, and Details.ID = "1", Details.Kind = "parent" 3. Allow a client to receive validation data that is keyed by attribute for building user facing UIs around field submission. Validation is usually expressed as map[string][]string, but that type is less appropriate for many other uses. 4. Allow specific API errors to return more granular failure status for specific operations. An example might be a minion proxy, where the operation that failed may be both proxying OR the minion itself. In this case a reason may be defined "proxy_failed" corresponding to 502, where the Details field may be extended to contain a nested error object. At this time only ID and Kind are exposed
2014-07-31 18:12:26 +00:00
finalStatus := expectApiStatus(t, "GET", fmt.Sprintf("%s/prefix/version/operations/%s?after=1", server.URL, status.Details.ID), []byte{}, http.StatusOK)
expectedErr := apierrs.NewAlreadyExists("foo", "bar")
2014-07-31 18:16:13 +00:00
expectedStatus := &api.Status{
Status: api.StatusFailure,
Code: http.StatusConflict,
Reason: "already_exists",
Message: expectedErr.Error(),
Details: &api.StatusDetails{
Kind: "foo",
ID: "bar",
},
2014-07-31 18:16:13 +00:00
}
if !reflect.DeepEqual(expectedStatus, finalStatus) {
t.Errorf("Expected %#v, Got %#v", expectedStatus, finalStatus)
if finalStatus.Details != nil {
t.Logf("Details %#v, Got %#v", *expectedStatus.Details, *finalStatus.Details)
}
2014-07-31 18:16:13 +00:00
}
}
func TestWriteJSONDecodeError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
type T struct {
Value string
}
writeJSON(http.StatusOK, runtime.DefaultCodec, &T{"Undecodable"}, w)
2014-07-31 18:16:13 +00:00
}))
status := expectApiStatus(t, "GET", server.URL, nil, http.StatusInternalServerError)
if status.Reason != api.StatusReasonUnknown {
t.Errorf("unexpected reason %#v", status)
2014-08-04 00:01:15 +00:00
}
if !strings.Contains(status.Message, "type apiserver.T is not registered") {
t.Errorf("unexpected message %#v", status)
2014-07-31 18:16:13 +00:00
}
}
type marshalError struct {
err error
}
func (m *marshalError) MarshalJSON() ([]byte, error) {
return []byte{}, m.err
}
func TestWriteRAWJSONMarshalError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
writeRawJSON(http.StatusOK, &marshalError{errors.New("Undecodable")}, w)
}))
client := http.Client{}
resp, err := client.Get(server.URL)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
2014-07-31 18:16:13 +00:00
if resp.StatusCode != http.StatusInternalServerError {
t.Errorf("unexpected status code %d", resp.StatusCode)
}
}
func TestSyncCreateTimeout(t *testing.T) {
testOver := make(chan struct{})
defer close(testOver)
2014-06-25 20:21:32 +00:00
storage := SimpleRESTStorage{
injectedFunction: func(obj interface{}) (interface{}, error) {
// Eliminate flakes by ensuring the create operation takes longer than this test.
<-testOver
2014-06-25 20:21:32 +00:00
return obj, nil
},
}
handler := Handle(map[string]RESTStorage{
2014-06-25 20:21:32 +00:00
"foo": &storage,
}, codec, "/prefix/version")
server := httptest.NewServer(handler)
simple := Simple{Name: "foo"}
data, _ := codec.Encode(simple)
2014-07-31 18:16:13 +00:00
itemOut := expectApiStatus(t, "POST", server.URL+"/prefix/version/foo?sync=true&timeout=4ms", data, http.StatusAccepted)
Evolve the api.Status object with Reason/Details Contains breaking API change on api.Status#Details (type change) Turn Details from string -> StatusDetails - a general bucket for keyed error behavior. Define an open enumeration ReasonType exposed as Reason on the status object to provide machine readable subcategorization beyond HTTP Status Code. Define a human readable field Message which is common convention (previously this was joined into Details). Precedence order: HTTP Status Code, Reason, Details. apiserver would impose restraints on the ReasonTypes defined by the main apiobject, and ensure their use is consistent. There are four long term scenarios this change supports: 1. Allow a client access to a machine readable field that can be easily switched on for improving or translating the generic server Message. 2. Return a 404 when a composite operation on multiple resources fails with enough data so that a client can distinguish which item does not exist. E.g. resource Parent and resource Child, POST /parents/1/children to create a new Child, but /parents/1 is deleted. POST returns 404, ReasonTypeNotFound, and Details.ID = "1", Details.Kind = "parent" 3. Allow a client to receive validation data that is keyed by attribute for building user facing UIs around field submission. Validation is usually expressed as map[string][]string, but that type is less appropriate for many other uses. 4. Allow specific API errors to return more granular failure status for specific operations. An example might be a minion proxy, where the operation that failed may be both proxying OR the minion itself. In this case a reason may be defined "proxy_failed" corresponding to 502, where the Details field may be extended to contain a nested error object. At this time only ID and Kind are exposed
2014-07-31 18:12:26 +00:00
if itemOut.Status != api.StatusWorking || itemOut.Details == nil || itemOut.Details.ID == "" {
2014-06-25 20:21:32 +00:00
t.Errorf("Unexpected status %#v", itemOut)
}
}