File: client_test.go

package info (click to toggle)
golang-github-hetznercloud-hcloud-go 1.17.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 548 kB
  • sloc: sh: 5; makefile: 2
file content (286 lines) | stat: -rw-r--r-- 6,972 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package hcloud

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/hetznercloud/hcloud-go/hcloud/schema"
)

type testEnv struct {
	Server *httptest.Server
	Mux    *http.ServeMux
	Client *Client
}

func (env *testEnv) Teardown() {
	env.Server.Close()
	env.Server = nil
	env.Mux = nil
	env.Client = nil
}

func newTestEnv() testEnv {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	client := NewClient(
		WithEndpoint(server.URL),
		WithToken("token"),
		WithBackoffFunc(func(_ int) time.Duration { return 0 }),
	)
	return testEnv{
		Server: server,
		Mux:    mux,
		Client: client,
	}
}

func TestClientEndpointTrailingSlashesRemoved(t *testing.T) {
	client := NewClient(WithEndpoint("http://api/v1.0/////"))
	if strings.HasSuffix(client.endpoint, "/") {
		t.Fatalf("endpoint has trailing slashes: %q", client.endpoint)
	}
}

func TestClientError(t *testing.T) {
	env := newTestEnv()
	defer env.Teardown()

	env.Mux.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusUnprocessableEntity)
		json.NewEncoder(w).Encode(schema.ErrorResponse{
			Error: schema.Error{
				Code:    "service_error",
				Message: "An error occured",
			},
		})
	})

	ctx := context.Background()
	req, err := env.Client.NewRequest(ctx, "GET", "/error", nil)
	if err != nil {
		t.Fatalf("error creating request: %s", err)
	}

	_, err = env.Client.Do(req, nil)
	if _, ok := err.(Error); !ok {
		t.Fatalf("unexpected error of type %T: %v", err, err)
	}

	apiError := err.(Error)

	if apiError.Code != "service_error" {
		t.Errorf("unexpected error code: %q", apiError.Code)
	}
	if apiError.Message != "An error occured" {
		t.Errorf("unexpected error message: %q", apiError.Message)
	}
}

func TestClientMeta(t *testing.T) {
	env := newTestEnv()
	defer env.Teardown()

	env.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Header().Set("RateLimit-Limit", "1000")
		w.Header().Set("RateLimit-Remaining", "999")
		w.Header().Set("RateLimit-Reset", "1511954577")
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, `{
			"foo": "bar",
			"meta": {
				"pagination": {
					"page": 1
				}
			}
		}`)
	})

	ctx := context.Background()
	req, err := env.Client.NewRequest(ctx, "GET", "/", nil)
	if err != nil {
		t.Fatalf("error creating request: %s", err)
	}

	response, err := env.Client.Do(req, nil)
	if err != nil {
		t.Fatalf("request failed: %s", err)
	}

	if response.Meta.Ratelimit.Limit != 1000 {
		t.Errorf("unexpected ratelimit limit: %d", response.Meta.Ratelimit.Limit)
	}
	if response.Meta.Ratelimit.Remaining != 999 {
		t.Errorf("unexpected ratelimit remaining: %d", response.Meta.Ratelimit.Remaining)
	}
	if !response.Meta.Ratelimit.Reset.Equal(time.Unix(1511954577, 0)) {
		t.Errorf("unexpected ratelimit reset: %v", response.Meta.Ratelimit.Reset)
	}

	if response.Meta.Pagination.Page != 1 {
		t.Error("missing pagination")
	}
}

func TestClientMetaNonJSON(t *testing.T) {
	env := newTestEnv()
	defer env.Teardown()

	env.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, "foo")
	})

	ctx := context.Background()
	req, err := env.Client.NewRequest(ctx, "GET", "/", nil)
	if err != nil {
		t.Fatalf("error creating request: %s", err)
	}

	response, err := env.Client.Do(req, nil)
	if err != nil {
		t.Fatalf("request failed: %s", err)
	}

	if response.Meta.Pagination != nil {
		t.Fatal("pagination should not be present")
	}
}

func TestClientAll(t *testing.T) {
	env := newTestEnv()
	defer env.Teardown()

	var (
		ctx          = context.Background()
		ratelimited  bool
		expectedPage = 1
	)

	env.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		respBody := schema.MetaResponse{
			Meta: schema.Meta{
				Pagination: &schema.MetaPagination{
					LastPage:     3,
					PerPage:      1,
					TotalEntries: 3,
				},
			},
		}

		switch page := r.URL.Query().Get("page"); page {
		case "", "1":
			respBody.Meta.Pagination.Page = 1
			respBody.Meta.Pagination.NextPage = 2
		case "2":
			if !ratelimited {
				ratelimited = true
				w.WriteHeader(http.StatusTooManyRequests)
				json.NewEncoder(w).Encode(schema.ErrorResponse{
					Error: schema.Error{
						Code:    string(ErrorCodeRateLimitExceeded),
						Message: "ratelimited",
					},
				})
				return
			}
			respBody.Meta.Pagination.Page = 2
			respBody.Meta.Pagination.PreviousPage = 1
			respBody.Meta.Pagination.NextPage = 3
		case "3":
			respBody.Meta.Pagination.Page = 3
			respBody.Meta.Pagination.PreviousPage = 2
		default:
			t.Errorf("bad page: %q", page)
		}

		json.NewEncoder(w).Encode(respBody)
	})

	env.Client.all(func(page int) (*Response, error) {
		if page != expectedPage {
			t.Fatalf("expected page %d, but called for %d", expectedPage, page)
		}

		path := fmt.Sprintf("/?page=%d&per_page=1", page)
		req, err := env.Client.NewRequest(ctx, "GET", path, nil)
		if err != nil {
			return nil, err
		}
		resp, err := env.Client.Do(req, nil)
		if err != nil {
			return resp, err
		}
		expectedPage++
		return resp, err
	})

	if expectedPage != 4 {
		t.Errorf("expected to have walked through 3 pages, but walked through %d pages", expectedPage-1)
	}
}

func TestClientDo(t *testing.T) {
	env := newTestEnv()
	defer env.Teardown()

	callCount := 0
	env.Mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		callCount++
		w.Header().Set("Content-Type", "application/json")
		switch callCount {
		case 1:
			w.WriteHeader(http.StatusTooManyRequests)
			json.NewEncoder(w).Encode(schema.ErrorResponse{
				Error: schema.Error{
					Code:    string(ErrorCodeRateLimitExceeded),
					Message: "ratelimited",
				},
			})
		case 2:
			fmt.Fprintln(w, "{}")
		default:
			t.Errorf("unexpected number of calls to the test server: %v", callCount)
		}
	})

	ctx := context.Background()
	request, _ := env.Client.NewRequest(ctx, http.MethodGet, "/test", nil)
	_, err := env.Client.Do(request, nil)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}

func TestBuildUserAgent(t *testing.T) {
	testCases := []struct {
		name               string
		applicationName    string
		applicationVersion string
		userAgent          string
	}{
		{"with application name and version", "test", "1.0", "test/1.0 " + UserAgent},
		{"with application name but no version", "test", "", "test " + UserAgent},
		{"without application name and version", "", "", UserAgent},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			client := NewClient(WithApplication(testCase.applicationName, testCase.applicationVersion))
			if client.userAgent != testCase.userAgent {
				t.Errorf("unexpected user agent: %v", client.userAgent)
			}
		})
	}
}