96 lines
2.1 KiB
Go
96 lines
2.1 KiB
Go
package remote
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func mockHTTP(status int, response string) (*HTTP, *httptest.Server) {
|
|
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(status)
|
|
w.Write([]byte(response))
|
|
}))
|
|
return &HTTP{
|
|
password: "",
|
|
domain: s.URL,
|
|
client: &http.Client{},
|
|
}, s
|
|
}
|
|
|
|
func TestNewHTTP(t *testing.T) {
|
|
h, srv := mockHTTP(http.StatusOK, "")
|
|
defer srv.Close()
|
|
if _, err := NewHTTP(h.domain, ""); err != nil {
|
|
t.Fatalf("cannot make new HTTP: %v", err)
|
|
}
|
|
|
|
h, srv = mockHTTP(http.StatusNotFound, "")
|
|
defer srv.Close()
|
|
if _, err := NewHTTP(h.domain, ""); err == nil {
|
|
t.Fatalf("can make new HTTP on bad status: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestHTTPGet(t *testing.T) {
|
|
validBody := "body"
|
|
h, srv := mockHTTP(http.StatusOK, validBody)
|
|
defer srv.Close()
|
|
resp, err := h.Get("/anything")
|
|
if err != nil {
|
|
t.Fatalf("cannot use HTTP GET: %v", err)
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Errorf("cannot use HTTP GET: %v", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestHTTPPost(t *testing.T) {
|
|
validBody := "body"
|
|
h, srv := mockHTTP(http.StatusOK, validBody)
|
|
defer srv.Close()
|
|
resp, err := h.Post("/anything", validBody)
|
|
if err != nil {
|
|
t.Fatalf("cannot use HTTP GET: %v", err)
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Errorf("cannot use HTTP GET: %v", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestHTTPNewReq(t *testing.T) {
|
|
cases := []struct {
|
|
method string
|
|
path string
|
|
body string
|
|
}{
|
|
{
|
|
method: "GET",
|
|
path: "/",
|
|
body: "",
|
|
},
|
|
{
|
|
method: "POST",
|
|
path: "/asdf/asdf",
|
|
body: "bod",
|
|
},
|
|
}
|
|
|
|
h := &HTTP{}
|
|
for i, c := range cases {
|
|
r, _ := h.NewReq(c.method, c.path, c.body)
|
|
if r.Method != c.method {
|
|
t.Errorf("[%d] wrong method on newreq: got %v, want %v", i, r.Method, c.method)
|
|
}
|
|
if r.URL.Path != c.path {
|
|
t.Errorf("[%d] wrong path on newreq: got %v, want %v", i, r.URL.Path, c.path)
|
|
}
|
|
if b, err := ioutil.ReadAll(r.Body); err != nil {
|
|
t.Errorf("[%d] bad body on newreq: %v", i, err)
|
|
} else if string(b) != c.body {
|
|
t.Errorf("[%d] wrong body on newreq: got %v, want %v", i, string(b), c.body)
|
|
}
|
|
}
|
|
}
|