-
Notifications
You must be signed in to change notification settings - Fork 29
/
powerdns_test.go
395 lines (356 loc) · 11 KB
/
powerdns_test.go
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package powerdns
import (
"context"
"fmt"
"maps"
"net/http"
"net/url"
"testing"
"github.com/jarcoal/httpmock"
)
const (
testBaseURL string = "http://localhost:8080"
testVHost string = "localhost"
testAPIKey string = "apipw"
)
func generateTestAPIURL() string {
return fmt.Sprintf("%s/api/v1", testBaseURL)
}
func generateTestAPIVHostURL() string {
return fmt.Sprintf("%s/servers/%s", generateTestAPIURL(), testVHost)
}
func verifyAPIKey(req *http.Request) *http.Response {
if req.Header.Get("X-Api-Key") != testAPIKey {
return httpmock.NewStringResponse(http.StatusUnauthorized, "Unauthorized")
}
return nil
}
func initialisePowerDNSTestClient() *Client {
return New(testBaseURL, testVHost, WithAPIKey(testAPIKey))
}
func registerDoMockResponder() {
httpmock.RegisterResponder("GET", fmt.Sprintf("%s/servers/doesnt-exist", generateTestAPIURL()),
func(req *http.Request) (*http.Response, error) {
if res := verifyAPIKey(req); res != nil {
return res, nil
}
return httpmock.NewStringResponse(http.StatusNotFound, "Not Found"), nil
},
)
httpmock.RegisterResponder("GET", fmt.Sprintf("%s/servers/localhost", generateTestAPIURL()),
func(req *http.Request) (*http.Response, error) {
return verifyAPIKey(req), nil
},
)
httpmock.RegisterResponder("GET", fmt.Sprintf("%s/server", generateTestAPIURL()),
func(req *http.Request) (*http.Response, error) {
mock := Error{
Status: "Not Found",
StatusCode: http.StatusNotFound,
Message: "Not Found",
}
return httpmock.NewJsonResponse(http.StatusNotImplemented, mock)
},
)
}
func TestWithHeaders(t *testing.T) {
p := &Client{}
withHeaders := WithHeaders(map[string]string{"X-Test-Header": "test-header"})
withHeaders(p)
if !maps.Equal(p.Headers, map[string]string{"X-Test-Header": "test-header"}) {
t.Error("Unexpected header")
}
}
func TestWithHttpClient(t *testing.T) {
p := &Client{}
httpClient := &http.Client{}
withHTTPClient := WithHTTPClient(httpClient)
withHTTPClient(p)
if p.httpClient != httpClient {
t.Error("Unexpected HTTP client")
}
}
func TestWithAPIKey(t *testing.T) {
p := &Client{}
withAPIKey := WithAPIKey("apipw")
withAPIKey(p)
if *p.apiKey != "apipw" {
t.Error("Unexpected API key")
}
}
func TestNewClient(t *testing.T) {
t.Run("TestMinimalConstructor", func(t *testing.T) {
p := NewClient("http://localhost:8080", "localhost", nil, nil)
if p.Scheme != "http" {
t.Error("NewClient returns invalid scheme")
}
if p.Hostname != "localhost" {
t.Error("NewClient returns invalid hostname")
}
if p.Port != "8080" {
t.Error("NewClient returns invalid port")
}
if p.VHost != "localhost" {
t.Error("NewClient returns invalid vHost")
}
if !maps.Equal(p.Headers, map[string]string{}) {
t.Error("NewClient returns invalid headers")
}
if p.httpClient != http.DefaultClient {
t.Error("NewClient returns invalid HTTP client")
}
if p.common.client != p {
t.Error("NewClient returns invalid common client")
}
})
t.Run("TestCustomHeaders", func(t *testing.T) {
p := NewClient("http://localhost:8080", "localhost", map[string]string{"X-API-Key": "apipw"}, nil)
if !maps.Equal(p.Headers, map[string]string{"X-API-Key": "apipw"}) {
t.Error("NewClient returns invalid headers")
}
})
t.Run("TestCustomHTTPClient", func(t *testing.T) {
httpClient := &http.Client{}
p := NewClient("http://localhost:8080", "localhost", nil, httpClient)
if p.httpClient != httpClient {
t.Error("NewClient returns invalid HTTP Client")
}
})
}
func TestNew(t *testing.T) {
t.Run("TestNoOptions", func(t *testing.T) {
p := New("http://localhost:8080", "localhost")
if p.Scheme != "http" {
t.Error("New returns invalid scheme")
}
if p.Hostname != "localhost" {
t.Error("New returns invalid hostname")
}
if p.Port != "8080" {
t.Error("New returns invalid port")
}
if p.VHost != "localhost" {
t.Error("New returns invalid vHost")
}
if !maps.Equal(p.Headers, map[string]string{}) {
t.Error("New returns invalid headers")
}
if p.httpClient != http.DefaultClient {
t.Error("New returns invalid HTTP client")
}
if p.common.client != p {
t.Error("New returns invalid common client")
}
})
t.Run("TestOptionInvocation", func(t *testing.T) {
testOptionInvocationCount := 0
testOption := func(client *Client) {
testOptionInvocationCount++
}
_ = New("http://localhost:8080", "localhost", testOption, testOption)
if testOptionInvocationCount != 2 {
t.Error("New does not call all options")
}
})
t.Run("TestInvalidURL", func(t *testing.T) {
originalLogFatalf := logFatalf
defer func() {
logFatalf = originalLogFatalf
}()
var errors []string
logFatalf = func(format string, args ...interface{}) {
if len(args) > 0 {
errors = append(errors, fmt.Sprintf(format, args))
} else {
errors = append(errors, format)
}
}
_ = New("http://1.2:foo", "localhost")
if len(errors) < 1 {
t.Error("NewClient does not exit with fatal error")
}
})
}
func TestNewRequest(t *testing.T) {
t.Run("TestValidRequest", func(t *testing.T) {
p := initialisePowerDNSTestClient()
if _, err := p.newRequest(context.Background(), "GET", "servers", nil, nil); err != nil {
t.Error("error is not nil")
}
})
t.Run("TestUserAgentHeader", func(t *testing.T) {
p := initialisePowerDNSTestClient()
req, _ := p.newRequest(context.Background(), "GET", "servers", nil, nil)
if req.Header.Get("User-Agent") != "go-powerdns" {
t.Error("Unexpected user agent header")
}
})
t.Run("TestContentTypeHeaderWithoutBody", func(t *testing.T) {
p := initialisePowerDNSTestClient()
req, _ := p.newRequest(context.Background(), "GET", "servers", nil, nil)
if req.Header.Get("Content-Type") != "" {
t.Error("Unexpected content type header")
}
if req.Header.Get("Accept") != "" {
t.Error("Unexpected accept header")
}
})
t.Run("TestContentTypeHeaderWithBody", func(t *testing.T) {
p := initialisePowerDNSTestClient()
req, _ := p.newRequest(context.Background(), "GET", "servers", nil, "test-body")
if req.Header.Get("Content-Type") != "application/json" {
t.Error("Unexpected content type header")
}
if req.Header.Get("Accept") != "application/json" {
t.Error("Unexpected accept header")
}
})
t.Run("TestAPIKeyHeader", func(t *testing.T) {
p := New(testBaseURL, testVHost, WithAPIKey("test-key"))
req, _ := p.newRequest(context.Background(), "GET", "servers", nil, nil)
if req.Header.Get("X-API-Key") != "test-key" {
t.Error("Unexpected API key header")
}
})
t.Run("TestCustomHeaders", func(t *testing.T) {
p := New(testBaseURL, testVHost, WithHeaders(map[string]string{"X-Test-Header": "test-header"}))
req, _ := p.newRequest(context.Background(), "GET", "servers", nil, nil)
if req.Header.Get("X-Test-Header") != "test-header" {
t.Error("Unexpected API key header")
}
})
}
func TestDo(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
registerDoMockResponder()
t.Run("TestStringErrorResponse", func(t *testing.T) {
p := initialisePowerDNSTestClient()
req, _ := p.newRequest(context.Background(), "GET", "servers/doesnt-exist", nil, nil)
if _, err := p.do(req, nil); err == nil {
t.Error("err is nil")
}
})
t.Run("Test401Handling", func(t *testing.T) {
p := New(testBaseURL, testVHost)
req, _ := p.newRequest(context.Background(), "GET", "servers/localhost", nil, nil)
if _, err := p.do(req, nil); err.Error() != "Unauthorized" {
t.Error("401 response does not result into an error with correct message.")
}
})
t.Run("TestErrorHandling", func(t *testing.T) {
p := initialisePowerDNSTestClient()
req, _ := p.newRequest(context.Background(), "GET", "servers/doesnt-exist", nil, nil)
_, err := p.do(req, nil)
wantResultBeforePowerDNSAuth49 := "Not Found"
wantResultFromPowerDNSAuth49 := "Method Not Allowed"
if err.Error() != wantResultBeforePowerDNSAuth49 && err.Error() != wantResultFromPowerDNSAuth49 {
t.Error("Error response does not result into an error with correct message.", err.Error())
}
})
t.Run("TestJSONErrorHandling", func(t *testing.T) {
p := initialisePowerDNSTestClient()
req, _ := p.newRequest(context.Background(), "GET", "server", nil, nil)
_, err := p.do(req, nil)
wantResultBeforePowerDNSAuth49 := "Not Found"
wantResultFromPowerDNSAuth49 := "Method Not Allowed"
if err.Error() != wantResultBeforePowerDNSAuth49 && err.Error() != wantResultFromPowerDNSAuth49 {
t.Error("Error response does not result into an error with correct message.", err.Error())
}
})
}
func TestParseBaseURL(t *testing.T) {
testCases := []struct {
baseURL string
wantScheme string
wantHostname string
wantPort string
wantError bool
}{
{"https://example.com", "https", "example.com", "443", false},
{"http://example.com", "http", "example.com", "80", false},
{"https://example.com:8080", "https", "example.com", "8080", false},
{"http://example.com:8080", "http", "example.com", "8080", false},
{"http%%%foo", "http", "", "", true},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("TestCase%d", i), func(t *testing.T) {
scheme, hostname, port, err := parseBaseURL(tc.baseURL)
if err != nil && tc.wantError == true {
return
}
if err != nil && tc.wantError == false {
t.Error("Error was returned unexpectedly")
}
if err == nil && tc.wantError == true {
t.Error("No error was returned")
}
if scheme != tc.wantScheme {
t.Errorf("Scheme parsing failed: %s != %s", scheme, tc.wantScheme)
}
if hostname != tc.wantHostname {
t.Errorf("Hostname parsing failed: %s != %s", hostname, tc.wantHostname)
}
if port != tc.wantPort {
t.Errorf("Port parsing failed: %s != %s", port, tc.wantPort)
}
})
}
}
func TestParseVHost(t *testing.T) {
testCases := []struct {
vHost string
wantVHost string
}{
{"example.com", "example.com"},
{"", "localhost"},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("TestCase%d", i), func(t *testing.T) {
if parseVHost(tc.vHost) != tc.wantVHost {
t.Error("parseVHost returned an invalid value")
}
})
}
}
func TestGenerateAPIURL(t *testing.T) {
tmpl := "https://localhost:8080/api/v1/foo?a=b"
query := url.Values{}
query.Add("a", "b")
g := generateAPIURL("https", "localhost", "8080", "foo", &query)
if tmpl != g.String() {
t.Errorf("Template does not match generated API URL: %s", g.String())
}
}
func TestTrimDomain(t *testing.T) {
testCases := []struct {
domain string
wantDomain string
}{
{"example.com.", "example.com"},
{"example.com", "example.com"},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("TestCase%d", i), func(t *testing.T) {
if trimDomain(tc.domain) != tc.wantDomain {
t.Error("trimDomain returned an invalid value")
}
})
}
}
func TestMakeDomainCanonical(t *testing.T) {
testCases := []struct {
domain string
wantDomain string
}{
{"example.com.", "example.com."},
{"example.com", "example.com."},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("TestCase%d", i), func(t *testing.T) {
if makeDomainCanonical(tc.domain) != tc.wantDomain {
t.Error("makeDomainCanonical returned an invalid value")
}
})
}
}