Skip to content

Commit

Permalink
additional tests to govultr_test
Browse files Browse the repository at this point in the history
  • Loading branch information
ddymko committed Jan 5, 2021
1 parent a3dcf50 commit 200a910
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
3 changes: 1 addition & 2 deletions govultr.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,7 @@ func (c *Client) NewRequest(ctx context.Context, method, uri string, body interf

buf := new(bytes.Buffer)
if body != nil {
err = json.NewEncoder(buf).Encode(body)
if err != nil {
if err = json.NewEncoder(buf).Encode(body); err != nil {
return nil, err
}
}
Expand Down
50 changes: 50 additions & 0 deletions govultr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,10 @@ func TestClient_SetBaseUrl(t *testing.T) {
if client.BaseURL.String() != base {
t.Errorf("NewClient BaseUrl = %v, expected %v", client.BaseURL, base)
}

if err := client.SetBaseURL(":"); err == nil {
t.Error("Expected invalid BaseURL to fail")
}
}

func TestClient_SetUserAgent(t *testing.T) {
Expand Down Expand Up @@ -273,3 +277,49 @@ func TestClient_SetRetryLimit(t *testing.T) {
t.Errorf("NewClient RateLimit = %v, expected %v", client.client.RetryMax, 4)
}
}

func TestNewRequest_badURI(t *testing.T) {
c := NewClient(nil)
_, err := c.NewRequest(ctx, http.MethodGet, ":/1.", nil)
if err == nil {
t.Error("expected invalid URI to fail")
}
}

func TestNewRequest_badBody(t *testing.T) {
c := NewClient(nil)
_, err := c.NewRequest(ctx, http.MethodGet, "/", make(chan int))
if err == nil {
t.Error("expected invalid Body to fail")
}
}

func TestRequest_InvalidCall(t *testing.T) {
setup()
defer teardown()

mux.HandleFunc("/wrong", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusBadRequest)
fmt.Fprint(writer, nil)
})

req, _ := client.NewRequest(ctx, http.MethodGet, "/wrong", nil)
if err := client.DoWithContext(ctx, req, nil); err == nil {
t.Error("Expected invalid status code to bad request")
}
}

func TestRequest_InvalidResponseBody(t *testing.T) {
setup()
defer teardown()

mux.HandleFunc("/wrong", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
fmt.Fprint(writer, `{`)
})

req, _ := client.NewRequest(ctx, http.MethodGet, "/wrong", nil)
if err := client.DoWithContext(ctx, req, struct{}{}); err == nil {
t.Error("Expected response body to be invalid")
}
}

0 comments on commit 200a910

Please sign in to comment.