func TestUntypedFileUpload(t *testing.T) {
	binder := paramsForFileUpload()

	body := bytes.NewBuffer(nil)
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", "plain-jane.txt")
	assert.NoError(t, err)

	part.Write([]byte("the file contents"))
	writer.WriteField("name", "the-name")
	assert.NoError(t, writer.Close())

	urlStr := "http://localhost:8002/hello"
	req, _ := http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	data := make(map[string]interface{})
	assert.NoError(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
	assert.Equal(t, "the-name", data["name"])
	assert.NotNil(t, data["file"])
	assert.IsType(t, httpkit.File{}, data["file"])
	file := data["file"].(httpkit.File)
	assert.NotNil(t, file.Header)
	assert.Equal(t, "plain-jane.txt", file.Header.Filename)

	bb, err := ioutil.ReadAll(file.Data)
	assert.NoError(t, err)
	assert.Equal(t, []byte("the file contents"), bb)

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", "application/json")
	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", "application(")
	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	body = bytes.NewBuffer(nil)
	writer = multipart.NewWriter(body)
	part, err = writer.CreateFormFile("bad-name", "plain-jane.txt")
	assert.NoError(t, err)

	part.Write([]byte("the file contents"))
	writer.WriteField("name", "the-name")
	assert.NoError(t, writer.Close())
	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	req.MultipartReader()

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
}
func TestUntypedFormPost(t *testing.T) {
	params := parametersForFormUpload()
	binder := newUntypedRequestBinder(params, nil, strfmt.Default)

	urlStr := "http://localhost:8002/hello"
	req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=the-name&age=32`))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	data := make(map[string]interface{})
	assert.NoError(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
	assert.Equal(t, "the-name", data["name"])
	assert.EqualValues(t, 32, data["age"])

	req, _ = http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=%3&age=32`))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
}
func TestUntypedBindingTypesForValid(t *testing.T) {

	op2 := parametersForAllTypes("")
	binder := newUntypedRequestBinder(op2, nil, strfmt.Default)

	confirmed := true
	name := "thomas"
	friend := map[string]interface{}{"name": "toby", "age": float64(32)}
	id, age, score, factor := int64(7575), int32(348), float32(5.309), float64(37.403)
	requestID := 19394858
	tags := []string{"one", "two", "three"}
	dt1 := time.Date(2014, 8, 9, 0, 0, 0, 0, time.UTC)
	planned := strfmt.Date{Time: dt1}
	dt2 := time.Date(2014, 10, 12, 8, 5, 5, 0, time.UTC)
	delivered := strfmt.DateTime{Time: dt2}
	picture := base64.URLEncoding.EncodeToString([]byte("hello"))
	uri, _ := url.Parse("http://localhost:8002/hello/7575")
	qs := uri.Query()
	qs.Add("name", name)
	qs.Add("confirmed", "true")
	qs.Add("age", "348")
	qs.Add("score", "5.309")
	qs.Add("factor", "37.403")
	qs.Add("tags", strings.Join(tags, ","))
	qs.Add("planned", planned.String())
	qs.Add("delivered", delivered.String())
	qs.Add("picture", picture)

	req, _ := http.NewRequest("POST", uri.String()+"?"+qs.Encode(), bytes.NewBuffer([]byte(`{"name":"toby","age":32}`)))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Request-Id", "19394858")

	data := make(map[string]interface{})
	err := binder.Bind(req, RouteParams([]RouteParam{{"id", "7575"}}), httpkit.JSONConsumer(), &data)
	assert.NoError(t, err)
	assert.Equal(t, id, data["id"])
	assert.Equal(t, name, data["name"])
	assert.Equal(t, friend, data["friend"])
	assert.EqualValues(t, requestID, data["X-Request-Id"])
	assert.Equal(t, tags, data["tags"])
	assert.Equal(t, planned, data["planned"])
	assert.Equal(t, delivered, data["delivered"])
	assert.Equal(t, confirmed, data["confirmed"])
	assert.Equal(t, age, data["age"])
	assert.Equal(t, factor, data["factor"])
	assert.Equal(t, score, data["score"])
	pb, _ := base64.URLEncoding.DecodeString(picture)
	assert.EqualValues(t, pb, data["picture"].(strfmt.Base64))

}
Example #4
0
// NewAPI creates the default untyped API
func NewAPI(spec *spec.Document) *API {
	return &API{
		spec:            spec,
		DefaultProduces: "application/json",
		DefaultConsumes: "application/json",
		consumers: map[string]httpkit.Consumer{
			"application/json": httpkit.JSONConsumer(),
		},
		producers: map[string]httpkit.Producer{
			"application/json": httpkit.JSONProducer(),
		},
		authenticators: make(map[string]httpkit.Authenticator),
		operations:     make(map[string]httpkit.OperationHandler),
		ServeError:     errors.ServeError,
		Models:         make(map[string]func() interface{}),
		formats:        strfmt.NewFormats(),
	}
}
Example #5
0
// New creates a new default runtime for a swagger api client.
func New(swaggerSpec *spec.Document, host string) *Runtime {
	var rt Runtime
	rt.DefaultMediaType = httpkit.JSONMime
	rt.Consumers = map[string]httpkit.Consumer{
		httpkit.JSONMime: httpkit.JSONConsumer(),
	}
	rt.Producers = map[string]httpkit.Producer{
		httpkit.JSONMime: httpkit.JSONProducer(),
	}
	rt.Spec = swaggerSpec
	rt.Transport = http.DefaultTransport
	rt.client = http.DefaultClient
	rt.Host = host
	rt.BasePath = swaggerSpec.BasePath()
	rt.methodsAndPaths = make(map[string]methodAndPath)
	for mth, pathItem := range rt.Spec.Operations() {
		for pth, op := range pathItem {
			rt.methodsAndPaths[op.ID] = methodAndPath{mth, pth}
		}
	}
	return &rt
}
func configureAPI(api *operations.SwaggerPetstoreAPI) {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.XMLConsumer = httpkit.ConsumerFunc(func(r io.Reader, target interface{}) error {
		return errors.NotImplemented("xml consumer has not yet been implemented")
	})

	api.JSONProducer = httpkit.JSONProducer()

	api.XMLProducer = httpkit.ProducerFunc(func(w io.Writer, data interface{}) error {
		return errors.NotImplemented("xml producer has not yet been implemented")
	})

	api.APIKeyAuth = func(token string) (*models.User, error) {
		return nil, errors.NotImplemented("api key auth apiKey from header has not yet been implemented")
	}

	api.AddPetHandler = pet.AddPetHandlerFunc(func(params pet.AddPetParams, principal *models.User) error {
		return errors.NotImplemented("operation addPet has not yet been implemented")
	})

	api.CreateUserHandler = user.CreateUserHandlerFunc(func(params user.CreateUserParams) error {
		return errors.NotImplemented("operation createUser has not yet been implemented")
	})

	api.CreateUsersWithArrayInputHandler = user.CreateUsersWithArrayInputHandlerFunc(func(params user.CreateUsersWithArrayInputParams) error {
		return errors.NotImplemented("operation createUsersWithArrayInput has not yet been implemented")
	})

	api.LogoutUserHandler = user.LogoutUserHandlerFunc(func() error {
		return errors.NotImplemented("operation logoutUser has not yet been implemented")
	})

	api.UpdateUserHandler = user.UpdateUserHandlerFunc(func(params user.UpdateUserParams) error {
		return errors.NotImplemented("operation updateUser has not yet been implemented")
	})

	api.FindPetsByStatusHandler = pet.FindPetsByStatusHandlerFunc(func(params pet.FindPetsByStatusParams, principal *models.User) ([]models.Pet, error) {
		return nil, errors.NotImplemented("operation findPetsByStatus has not yet been implemented")
	})

	api.LoginUserHandler = user.LoginUserHandlerFunc(func(params user.LoginUserParams) (string, error) {
		return "", errors.NotImplemented("operation loginUser has not yet been implemented")
	})

	api.GetPetByIDHandler = pet.GetPetByIDHandlerFunc(func(params pet.GetPetByIDParams, principal *models.User) (*models.Pet, error) {
		return nil, errors.NotImplemented("operation getPetById has not yet been implemented")
	})

	api.GetOrderByIDHandler = store.GetOrderByIDHandlerFunc(func(params store.GetOrderByIDParams) (*models.Order, error) {
		return nil, errors.NotImplemented("operation getOrderById has not yet been implemented")
	})

	api.GetUserByNameHandler = user.GetUserByNameHandlerFunc(func(params user.GetUserByNameParams) (*models.User, error) {
		return nil, errors.NotImplemented("operation getUserByName has not yet been implemented")
	})

	api.DeletePetHandler = pet.DeletePetHandlerFunc(func(params pet.DeletePetParams, principal *models.User) error {
		return errors.NotImplemented("operation deletePet has not yet been implemented")
	})

	api.DeleteUserHandler = user.DeleteUserHandlerFunc(func(params user.DeleteUserParams) error {
		return errors.NotImplemented("operation deleteUser has not yet been implemented")
	})

	api.UpdatePetHandler = pet.UpdatePetHandlerFunc(func(params pet.UpdatePetParams, principal *models.User) error {
		return errors.NotImplemented("operation updatePet has not yet been implemented")
	})

	api.CreateUsersWithListInputHandler = user.CreateUsersWithListInputHandlerFunc(func(params user.CreateUsersWithListInputParams) error {
		return errors.NotImplemented("operation createUsersWithListInput has not yet been implemented")
	})

	api.PlaceOrderHandler = store.PlaceOrderHandlerFunc(func(params store.PlaceOrderParams) (*models.Order, error) {
		return nil, errors.NotImplemented("operation placeOrder has not yet been implemented")
	})

	api.UpdatePetWithFormHandler = pet.UpdatePetWithFormHandlerFunc(func(params pet.UpdatePetWithFormParams, principal *models.User) error {
		return errors.NotImplemented("operation updatePetWithForm has not yet been implemented")
	})

	api.FindPetsByTagsHandler = pet.FindPetsByTagsHandlerFunc(func(params pet.FindPetsByTagsParams, principal *models.User) ([]models.Pet, error) {
		return nil, errors.NotImplemented("operation findPetsByTags has not yet been implemented")
	})

	api.DeleteOrderHandler = store.DeleteOrderHandlerFunc(func(params store.DeleteOrderParams) error {
		return errors.NotImplemented("operation deleteOrder has not yet been implemented")
	})

}