open-vault/http/http_test.go

66 lines
1.4 KiB
Go
Raw Normal View History

2015-03-12 17:46:45 +00:00
package http
import (
2015-03-12 18:12:44 +00:00
"bytes"
2015-03-12 17:46:45 +00:00
"encoding/json"
2015-03-12 18:12:44 +00:00
"io"
2015-03-12 17:46:45 +00:00
"net/http"
"testing"
)
2015-03-16 17:41:08 +00:00
func testHttpDelete(t *testing.T, addr string) *http.Response {
return testHttpData(t, "DELETE", addr, nil)
}
2015-03-16 17:36:29 +00:00
func testHttpPost(t *testing.T, addr string, body interface{}) *http.Response {
return testHttpData(t, "POST", addr, body)
}
2015-03-12 18:12:44 +00:00
func testHttpPut(t *testing.T, addr string, body interface{}) *http.Response {
2015-03-16 17:36:29 +00:00
return testHttpData(t, "PUT", addr, body)
}
func testHttpData(t *testing.T, method string, addr string, body interface{}) *http.Response {
2015-03-12 18:12:44 +00:00
bodyReader := new(bytes.Buffer)
if body != nil {
enc := json.NewEncoder(bodyReader)
if err := enc.Encode(body); err != nil {
t.Fatalf("err:%s", err)
}
}
2015-03-16 17:36:29 +00:00
req, err := http.NewRequest(method, addr, bodyReader)
2015-03-12 18:12:44 +00:00
if err != nil {
t.Fatalf("err: %s", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("err: %s", err)
}
return resp
}
2015-03-12 17:46:45 +00:00
func testResponseStatus(t *testing.T, resp *http.Response, code int) {
if resp.StatusCode != code {
2015-03-12 18:12:44 +00:00
body := new(bytes.Buffer)
io.Copy(body, resp.Body)
resp.Body.Close()
t.Fatalf(
"Expected status %d, got %d. Body:\n\n%s",
code, resp.StatusCode, body.String())
2015-03-12 17:46:45 +00:00
}
}
func testResponseBody(t *testing.T, resp *http.Response, out interface{}) {
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(out); err != nil {
t.Fatalf("err: %s", err)
}
}