Exemple #1
0
func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) {
	bd := []struct {
		XMLName xml.Name `xml:"person"`
		Name    string   `xml:"name"`
		Hobby   string   `xml:"hobby"`
	}{{xml.Name{}, "Tom", "Organ trail"}, {xml.Name{}, "John", "Bird watching"}}
	reqWrtr := client.RequestWriterFunc(func(req client.Request, reg strfmt.Registry) error {
		req.SetBodyParam(bd)
		req.SetQueryParam("hello", "world")
		req.SetPathParam("id", "1234")
		req.SetHeaderParam("X-Rate-Limit", "200")
		return nil
	})
	r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
	r.SetHeaderParam(httpkit.HeaderContentType, httpkit.XMLMime)

	req, err := r.BuildHTTP(httpkit.XMLMime, testProducers, nil)
	if assert.NoError(t, err) && assert.NotNil(t, req) {
		assert.Equal(t, "200", req.Header.Get("x-rate-limit"))
		assert.Equal(t, "world", req.URL.Query().Get("hello"))
		assert.Equal(t, "/flats/1234/", req.URL.Path)
		expectedBody, _ := xml.Marshal(bd)
		actualBody, _ := ioutil.ReadAll(req.Body)
		assert.Equal(t, expectedBody, actualBody)
	}
}
Exemple #2
0
func TestBuildRequest_BuildHTTP_Files(t *testing.T) {
	cont, _ := ioutil.ReadFile("./client.go")
	reqWrtr := client.RequestWriterFunc(func(req client.Request, reg strfmt.Registry) error {
		req.SetFormParam("something", "some value")
		req.SetFileParam("file", "./client.go")
		req.SetQueryParam("hello", "world")
		req.SetPathParam("id", "1234")
		req.SetHeaderParam("X-Rate-Limit", "200")
		return nil
	})
	r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
	r.SetHeaderParam(httpkit.HeaderContentType, httpkit.JSONMime)

	req, err := r.BuildHTTP(httpkit.JSONProducer(), nil)
	if assert.NoError(t, err) && assert.NotNil(t, req) {
		assert.Equal(t, "200", req.Header.Get("x-rate-limit"))
		assert.Equal(t, "world", req.URL.Query().Get("hello"))
		assert.Equal(t, "/flats/1234/", req.URL.Path)
		mediaType, params, err := mime.ParseMediaType(req.Header.Get(httpkit.HeaderContentType))
		if assert.NoError(t, err) {
			assert.Equal(t, httpkit.MultipartFormMime, mediaType)
			boundary := params["boundary"]
			mr := multipart.NewReader(req.Body, boundary)
			frm, err := mr.ReadForm(1 << 20)
			if assert.NoError(t, err) {
				assert.Equal(t, "some value", frm.Value["something"][0])
				mpff := frm.File["file"][0]
				mpf, _ := mpff.Open()
				assert.Equal(t, "client.go", mpff.Filename)
				actual, _ := ioutil.ReadAll(mpf)
				assert.Equal(t, cont, actual)
			}
		}
	}
}
Exemple #3
0
func TestRuntime_CustomCookieJar(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		authenticated := false
		for _, cookie := range req.Cookies() {
			if cookie.Name == "sessionid" && cookie.Value == "abc" {
				authenticated = true
			}
		}
		if !authenticated {
			username, password, ok := req.BasicAuth()
			if ok && username == "username" && password == "password" {
				authenticated = true
				http.SetCookie(rw, &http.Cookie{Name: "sessionid", Value: "abc"})
			}
		}
		if authenticated {
			rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime)
			rw.WriteHeader(http.StatusOK)
			jsongen := json.NewEncoder(rw)
			jsongen.Encode([]task{})
		} else {
			rw.WriteHeader(http.StatusUnauthorized)
		}
	}))
	defer server.Close()

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})

	hu, _ := url.Parse(server.URL)
	runtime := New(hu.Host, "/", []string{"http"})
	runtime.Jar, _ = cookiejar.New(nil)

	submit := func(authInfo client.AuthInfoWriter) {
		_, err := runtime.Submit(&client.Operation{
			ID:          "getTasks",
			Method:      "GET",
			PathPattern: "/",
			Params:      rwrtr,
			AuthInfo:    authInfo,
			Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
				if response.Code() == 200 {
					return nil, nil
				}
				return nil, errors.New("Generic error")
			}),
		})

		assert.NoError(t, err)
	}

	submit(BasicAuth("username", "password"))
	submit(nil)
}
Exemple #4
0
func TestRuntime_ChunkedResponse(t *testing.T) {
	// test that it can make a simple request
	// and get the response for it.
	// defaults all the way down
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}
	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
			rw.WriteHeader(400)
			return
		}
		rw.Header().Add(httpkit.HeaderTransferEncoding, "chunked")
		rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime+";charset=utf-8")
		rw.WriteHeader(http.StatusOK)
		jsongen := json.NewEncoder(rw)
		jsongen.Encode(result)
	}))
	defer server.Close()

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})

	//specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml")
	hu, _ := url.Parse(server.URL)

	runtime := New(hu.Host, "/", []string{"http"})
	res, err := runtime.Submit(&client.Operation{
		ID:          "getTasks",
		Method:      "GET",
		PathPattern: "/",
		Schemes:     []string{"http"},
		Params:      rwrtr,
		Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
			if response.Code() == 200 {
				var result []task
				if err := consumer.Consume(response.Body(), &result); err != nil {
					return nil, err
				}
				return result, nil
			}
			return nil, errors.New("Generic error")
		}),
		AuthInfo: BearerToken("the-super-secret-token"),
	})

	if assert.NoError(t, err) {
		assert.IsType(t, []task{}, res)
		actual := res.([]task)
		assert.EqualValues(t, result, actual)
	}
}
Exemple #5
0
func TestRuntime_CustomTransport(t *testing.T) {
	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}

	specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml")
	specDoc.Spec().BasePath = "/"
	specDoc.Spec().Host = "localhost:3245"
	specDoc.Spec().Schemes = []string{"ws", "wss", "https"}

	if assert.NoError(t, err) {
		runtime := New(specDoc)
		runtime.Transport = roundTripperFunc(func(req *http.Request) (*http.Response, error) {
			if req.URL.Scheme != "https" {
				return nil, errors.New("this was not a https request")
			}
			var resp http.Response
			resp.StatusCode = 200
			resp.Header = make(http.Header)
			resp.Header.Set("content-type", "application/json")
			buf := bytes.NewBuffer(nil)
			enc := json.NewEncoder(buf)
			enc.Encode(result)
			resp.Body = ioutil.NopCloser(buf)
			return &resp, nil
		})

		res, err := runtime.Submit(&client.Operation{
			ID:     "getTasks",
			Params: rwrtr,
			Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
				if response.Code() == 200 {
					var result []task
					if err := consumer.Consume(response.Body(), &result); err != nil {
						return nil, err
					}
					return result, nil
				}
				return nil, errors.New("Generic error")
			}),
		})

		if assert.NoError(t, err) {
			assert.IsType(t, []task{}, res)
			actual := res.([]task)
			assert.EqualValues(t, result, actual)
		}
	}
}
Exemple #6
0
func TestRuntime_PickConsumer(t *testing.T) {
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}
	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		if req.Header.Get("Content-Type") != "application/octet-stream" {
			rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime+";charset=utf-8")
			rw.WriteHeader(400)
			return
		}
		rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime+";charset=utf-8")
		rw.WriteHeader(http.StatusOK)
		jsongen := json.NewEncoder(rw)
		jsongen.Encode(result)
	}))
	defer server.Close()

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		req.SetBodyParam(bytes.NewBufferString("hello"))
		return nil
	})

	hu, _ := url.Parse(server.URL)
	runtime := New(hu.Host, "/", []string{"http"})
	res, err := runtime.Submit(&client.Operation{
		ID:                 "getTasks",
		Method:             "POST",
		PathPattern:        "/",
		Schemes:            []string{"http"},
		ConsumesMediaTypes: []string{"application/octet-stream"},
		Params:             rwrtr,
		Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
			if response.Code() == 200 {
				var result []task
				if err := consumer.Consume(response.Body(), &result); err != nil {
					return nil, err
				}
				return result, nil
			}
			return nil, errors.New("Generic error")
		}),
		AuthInfo: BearerToken("the-super-secret-token"),
	})

	if assert.NoError(t, err) {
		assert.IsType(t, []task{}, res)
		actual := res.([]task)
		assert.EqualValues(t, result, actual)
	}
}
Exemple #7
0
func TestRuntime_Canary(t *testing.T) {
	// test that it can make a simple request
	// and get the response for it.
	// defaults all the way down
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}
	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime)
		rw.WriteHeader(http.StatusOK)
		jsongen := json.NewEncoder(rw)
		jsongen.Encode(result)
	}))

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})

	specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml")
	hu, _ := url.Parse(server.URL)
	specDoc.Spec().Host = hu.Host
	specDoc.Spec().BasePath = "/"
	if assert.NoError(t, err) {

		runtime := New(specDoc)
		res, err := runtime.Submit(&client.Operation{
			ID:     "getTasks",
			Params: rwrtr,
			Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
				if response.Code() == 200 {
					var result []task
					if err := consumer.Consume(response.Body(), &result); err != nil {
						return nil, err
					}
					return result, nil
				}
				return nil, errors.New("Generic error")
			}),
		})

		if assert.NoError(t, err) {
			assert.IsType(t, []task{}, res)
			actual := res.([]task)
			assert.EqualValues(t, result, actual)
		}
	}
}
Exemple #8
0
func TestRuntime_XMLCanary(t *testing.T) {
	// test that it can make a simple XML request
	// and get the response for it.
	result := tasks{
		Tasks: []task{
			{false, "task 1 content", 1},
			{false, "task 2 content", 2},
		},
	}
	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Add(httpkit.HeaderContentType, httpkit.XMLMime)
		rw.WriteHeader(http.StatusOK)
		xmlgen := xml.NewEncoder(rw)
		xmlgen.Encode(result)
	}))
	defer server.Close()

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})

	hu, _ := url.Parse(server.URL)
	runtime := New(hu.Host, "/", []string{"http"})
	res, err := runtime.Submit(&client.Operation{
		ID:          "getTasks",
		Method:      "GET",
		PathPattern: "/",
		Params:      rwrtr,
		Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
			if response.Code() == 200 {
				var result tasks
				if err := consumer.Consume(response.Body(), &result); err != nil {
					return nil, err
				}
				return result, nil
			}
			return nil, errors.New("Generic error")
		}),
	})

	if assert.NoError(t, err) {
		assert.IsType(t, tasks{}, res)
		actual := res.(tasks)
		assert.EqualValues(t, result, actual)
	}
}
func TestRuntime_PreserveTrailingSlash(t *testing.T) {
	var redirected bool

	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime+";charset=utf-8")

		if req.URL.Path == "/api/tasks" {
			redirected = true
			return
		}
		if req.URL.Path == "/api/tasks/" {
			rw.WriteHeader(http.StatusOK)
		}
	}))
	defer server.Close()

	hu, _ := url.Parse(server.URL)

	runtime := New(hu.Host, "/", []string{"http"})

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})

	_, err := runtime.Submit(&client.Operation{
		ID:          "getTasks",
		Method:      "GET",
		PathPattern: "/api/tasks/",
		Params:      rwrtr,
		Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
			if redirected {
				return nil, errors.New("expected Submit to preserve trailing slashes - this caused a redirect")
			}
			if response.Code() == http.StatusOK {
				return nil, nil
			}
			return nil, errors.New("Generic error")
		}),
	})

	assert.NoError(t, err)
}
Exemple #10
0
func TestBuildRequest_BuildHTTP_Form(t *testing.T) {
	reqWrtr := client.RequestWriterFunc(func(req client.Request, reg strfmt.Registry) error {
		req.SetFormParam("something", "some value")
		req.SetQueryParam("hello", "world")
		req.SetPathParam("id", "1234")
		req.SetHeaderParam("X-Rate-Limit", "200")
		return nil
	})
	r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
	r.SetHeaderParam(httpkit.HeaderContentType, httpkit.JSONMime)

	req, err := r.BuildHTTP(httpkit.JSONProducer(), nil)
	if assert.NoError(t, err) && assert.NotNil(t, req) {
		assert.Equal(t, "200", req.Header.Get("x-rate-limit"))
		assert.Equal(t, "world", req.URL.Query().Get("hello"))
		assert.Equal(t, "/flats/1234/", req.URL.Path)
		expected := []byte("something=some+value")
		actual, _ := ioutil.ReadAll(req.Body)
		assert.Equal(t, expected, actual)
	}
}
Exemple #11
0
func TestBuildRequest_BuildHTTP_TextPayload(t *testing.T) {
	bd := "Tom: Organ trail; John: Bird watching"
	reqWrtr := client.RequestWriterFunc(func(req client.Request, reg strfmt.Registry) error {
		req.SetBodyParam(bd)
		req.SetQueryParam("hello", "world")
		req.SetPathParam("id", "1234")
		req.SetHeaderParam("X-Rate-Limit", "200")
		return nil
	})
	r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
	r.SetHeaderParam(httpkit.HeaderContentType, httpkit.TextMime)

	req, err := r.BuildHTTP(httpkit.TextMime, testProducers, nil)
	if assert.NoError(t, err) && assert.NotNil(t, req) {
		assert.Equal(t, "200", req.Header.Get("x-rate-limit"))
		assert.Equal(t, "world", req.URL.Query().Get("hello"))
		assert.Equal(t, "/flats/1234/", req.URL.Path)
		expectedBody := []byte(bd)
		actualBody, _ := ioutil.ReadAll(req.Body)
		assert.Equal(t, expectedBody, actualBody)
	}
}
func TestRuntime_Concurrent(t *testing.T) {
	// test that it can make a simple request
	// and get the response for it.
	// defaults all the way down
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}
	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime)
		rw.WriteHeader(http.StatusOK)
		jsongen := json.NewEncoder(rw)
		jsongen.Encode(result)
	}))
	defer server.Close()

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})

	hu, _ := url.Parse(server.URL)
	runtime := New(hu.Host, "/", []string{"http"})
	resCC := make(chan interface{})
	errCC := make(chan error)
	var res interface{}
	var err error

	for j := 0; j < 6; j++ {
		go func() {
			resC := make(chan interface{})
			errC := make(chan error)

			go func() {
				var resp interface{}
				var errp error
				for i := 0; i < 3; i++ {
					resp, errp = runtime.Submit(&client.Operation{
						ID:          "getTasks",
						Method:      "GET",
						PathPattern: "/",
						Params:      rwrtr,
						Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
							if response.Code() == 200 {
								var result []task
								if err := consumer.Consume(response.Body(), &result); err != nil {
									return nil, err
								}
								return result, nil
							}
							return nil, errors.New("Generic error")
						}),
					})
					<-time.After(100 * time.Millisecond)
				}
				resC <- resp
				errC <- errp
			}()
			resCC <- <-resC
			errCC <- <-errC
		}()
	}

	c := 6
	for c > 0 {
		res = <-resCC
		err = <-errCC
		c--
	}

	if assert.NoError(t, err) {
		assert.IsType(t, []task{}, res)
		actual := res.([]task)
		assert.EqualValues(t, result, actual)
	}
}