1
0
mirror of https://github.com/jhillyerd/inbucket.git synced 2025-12-17 17:47:03 +00:00
Files
go-inbucket/pkg/rest/client/rest_test.go
James Hillyerd f8c30a678a Reorganize packages, closes #79
- All packages go into either cmd or pkg directories
- Most packages renamed
- Server packages moved into pkg/server
- sanitize moved into webui, as that's the only place it's used
- filestore moved into pkg/storage/file
- Makefile updated, and PKG variable use fixed
2018-03-10 12:04:13 -08:00

126 lines
2.1 KiB
Go

package client
import (
"bytes"
"io/ioutil"
"net/http"
"net/url"
"testing"
)
const baseURLStr = "http://test.local:8080"
var baseURL *url.URL
func init() {
var err error
baseURL, err = url.Parse(baseURLStr)
if err != nil {
panic(err)
}
}
type mockHTTPClient struct {
req *http.Request
statusCode int
body string
}
func (m *mockHTTPClient) Do(req *http.Request) (resp *http.Response, err error) {
m.req = req
if m.statusCode == 0 {
m.statusCode = 200
}
resp = &http.Response{
StatusCode: m.statusCode,
Body: ioutil.NopCloser(bytes.NewBufferString(m.body)),
}
return
}
func TestDo(t *testing.T) {
var want, got string
mth := &mockHTTPClient{}
c := &restClient{mth, baseURL}
_, err := c.do("POST", "/dopost")
if err != nil {
t.Fatal(err)
}
want = "POST"
got = mth.req.Method
if got != want {
t.Errorf("req.Method == %q, want %q", got, want)
}
want = baseURLStr + "/dopost"
got = mth.req.URL.String()
if got != want {
t.Errorf("req.URL == %q, want %q", got, want)
}
}
func TestDoJSON(t *testing.T) {
var want, got string
mth := &mockHTTPClient{
body: `{"foo": "bar"}`,
}
c := &restClient{mth, baseURL}
var v map[string]interface{}
err := c.doJSON("GET", "/doget", &v)
if err != nil {
t.Fatal(err)
}
want = "GET"
got = mth.req.Method
if got != want {
t.Errorf("req.Method == %q, want %q", got, want)
}
want = baseURLStr + "/doget"
got = mth.req.URL.String()
if got != want {
t.Errorf("req.URL == %q, want %q", got, want)
}
want = "bar"
if val, ok := v["foo"]; ok {
got = val.(string)
if got != want {
t.Errorf("map[foo] == %q, want: %q", got, want)
}
} else {
t.Errorf("Map did not contain key foo, want: %q", want)
}
}
func TestDoJSONNilV(t *testing.T) {
var want, got string
mth := &mockHTTPClient{}
c := &restClient{mth, baseURL}
err := c.doJSON("GET", "/doget", nil)
if err != nil {
t.Fatal(err)
}
want = "GET"
got = mth.req.Method
if got != want {
t.Errorf("req.Method == %q, want %q", got, want)
}
want = baseURLStr + "/doget"
got = mth.req.URL.String()
if got != want {
t.Errorf("req.URL == %q, want %q", got, want)
}
}