Commit 5ec4f25e authored by Janos Guljas's avatar Janos Guljas

improve jsonhttptest

parent 84040016
...@@ -16,56 +16,49 @@ import ( ...@@ -16,56 +16,49 @@ import (
func ResponseDirect(t *testing.T, client *http.Client, method, url string, body io.Reader, responseCode int, response interface{}) { func ResponseDirect(t *testing.T, client *http.Client, method, url string, body io.Reader, responseCode int, response interface{}) {
t.Helper() t.Helper()
resp, err := request(client, method, url, body, responseCode) resp := request(t, client, method, url, body, responseCode)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != responseCode { got, err := ioutil.ReadAll(resp.Body)
t.Errorf("got response status %s, want %v %s", resp.Status, responseCode, http.StatusText(responseCode))
}
gotBytes, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
wantBytes, err := json.Marshal(response) got = bytes.TrimSpace(got)
want, err := json.Marshal(response)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
got := string(bytes.TrimSpace(gotBytes)) if !bytes.Equal(got, want) {
want := string(wantBytes) t.Errorf("got response %s, want %s", string(got), string(want))
if got != want {
t.Errorf("got response %s, want %s", got, want)
} }
} }
func ResponseUnmarshal(t *testing.T, client *http.Client, method, url string, body io.Reader, responseCode int, response interface{}) { func ResponseUnmarshal(t *testing.T, client *http.Client, method, url string, body io.Reader, responseCode int, response interface{}) {
t.Helper() t.Helper()
resp, err := request(client, method, url, body, responseCode) resp := request(t, client, method, url, body, responseCode)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != responseCode { if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
t.Errorf("got response status %s, want %v %s", resp.Status, responseCode, http.StatusText(responseCode))
}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func request(client *http.Client, method, url string, body io.Reader, responseCode int) (resp *http.Response, err error) { func request(t *testing.T, client *http.Client, method, url string, body io.Reader, responseCode int) *http.Response {
t.Helper()
req, err := http.NewRequest(method, url, body) req, err := http.NewRequest(method, url, body)
if err != nil { if err != nil {
return nil, err t.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != responseCode {
t.Errorf("got response status %s, want %v %s", resp.Status, responseCode, http.StatusText(responseCode))
} }
return client.Do(req) return resp
} }
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