forked from pterodactyl/wings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_test.go
94 lines (84 loc) · 2.46 KB
/
http_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
package remote
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func createTestClient(h http.HandlerFunc) (*client, *httptest.Server) {
s := httptest.NewServer(h)
c := &client{
httpClient: s.Client(),
baseUrl: s.URL,
maxAttempts: 1,
tokenId: "testid",
token: "testtoken",
}
return c, s
}
func TestRequest(t *testing.T) {
c, _ := createTestClient(func(rw http.ResponseWriter, r *http.Request) {
assert.Equal(t, "application/vnd.pterodactyl.v1+json", r.Header.Get("Accept"))
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
assert.Equal(t, "Bearer testid.testtoken", r.Header.Get("Authorization"))
assert.Equal(t, "/test", r.URL.Path)
rw.WriteHeader(http.StatusOK)
})
r, err := c.requestOnce(context.Background(), "", "/test", nil)
assert.NoError(t, err)
assert.NotNil(t, r)
}
func TestRequestRetry(t *testing.T) {
// Test if the client attempts failed requests
i := 0
c, _ := createTestClient(func(rw http.ResponseWriter, r *http.Request) {
if i < 1 {
rw.WriteHeader(http.StatusInternalServerError)
} else {
rw.WriteHeader(http.StatusOK)
}
i++
})
c.maxAttempts = 2
r, err := c.request(context.Background(), "", "", nil)
assert.NoError(t, err)
assert.NotNil(t, r)
assert.Equal(t, http.StatusOK, r.StatusCode)
assert.Equal(t, 2, i)
// Test whether the client returns the last request after retry limit is reached
i = 0
c, _ = createTestClient(func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusInternalServerError)
i++
})
c.maxAttempts = 2
r, err = c.request(context.Background(), "get", "", nil)
assert.Error(t, err)
assert.Nil(t, r)
v := AsRequestError(err)
assert.NotNil(t, v)
assert.Equal(t, http.StatusInternalServerError, v.StatusCode())
assert.Equal(t, 3, i)
}
func TestGet(t *testing.T) {
c, _ := createTestClient(func(rw http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method)
assert.Len(t, r.URL.Query(), 1)
assert.Equal(t, "world", r.URL.Query().Get("hello"))
})
r, err := c.Get(context.Background(), "/test", q{"hello": "world"})
assert.NoError(t, err)
assert.NotNil(t, r)
}
func TestPost(t *testing.T) {
test := map[string]string{
"hello": "world",
}
c, _ := createTestClient(func(rw http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
})
r, err := c.Post(context.Background(), "/test", test)
assert.NoError(t, err)
assert.NotNil(t, r)
}