spud/webclient/client_test.go

73 lines
1.8 KiB
Go

package webclient
import (
"bytes"
"encoding/json"
"io"
"net/http"
daemon "spud/daemon"
service_definition "spud/service_definition"
"testing"
)
type RecordedRequest struct {
method string
url string
contentType string
data io.Reader
}
type DummyHttpClient struct {
requests []RecordedRequest
}
func (d *DummyHttpClient) Post(url string, contentType string, data io.Reader) (*http.Response, error) {
d.requests = append(d.requests, RecordedRequest{method: http.MethodPost, url: url, contentType: contentType, data: data})
return nil, nil
}
func Test_WebClient_GetBaseUrlGetsUrlFromHostPort(t *testing.T) {
c := NewWebClient("http://host", 9999)
actual := c.getBaseUrl()
expected := "http://host:9999"
if actual != expected {
t.Errorf("Expected %s, got %s.", expected, actual)
}
}
func Test_WebClient_CreateServicePostsToDaemon(t *testing.T) {
c := NewWebClient("http://host", 9999)
httpClient := &DummyHttpClient{}
c.httpClient = httpClient
def := service_definition.ServiceDefinition{Name: "test-service"}
c.CreateService(def)
if len(httpClient.requests) != 1 || httpClient.requests[0].method != http.MethodPost {
t.Errorf("Expected one POST requests, got none.")
}
}
func Test_WebClient_CreateServiceSendsDefinition(t *testing.T) {
c := NewWebClient("http://host", 9999)
httpClient := &DummyHttpClient{}
c.httpClient = httpClient
payload := daemon.ServiceListPayload{
Definition: service_definition.ServiceDefinition{Name: "test-service"},
}
c.CreateService(payload.Definition)
req := httpClient.requests[0]
actualDef := bytes.NewBuffer([]byte{})
actualDef.ReadFrom(req.data)
expectedDef, _ := json.Marshal(payload)
if actualDef.String() != string(expectedDef) {
t.Errorf("Unexpected data: %s != %s", actualDef.String(), string(expectedDef))
}
}