forked from sideshow/apns2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
293 lines (256 loc) · 8.82 KB
/
client_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
package apns2_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"golang.org/x/net/http2"
apns "github.com/sideshow/apns2"
"github.com/sideshow/apns2/certificate"
"github.com/sideshow/apns2/token"
"github.com/stretchr/testify/assert"
)
// Mocks
func mockNotification() *apns.Notification {
n := &apns.Notification{}
n.DeviceToken = "11aa01229f15f0f0c52029d8cf8cd0aeaf2365fe4cebc4af26cd6d76b7919ef7"
n.Payload = []byte(`{"aps":{"alert":"Hello!"}}`)
return n
}
func mockToken() *token.Token {
pubkeyCurve := elliptic.P256()
authKey, _ := ecdsa.GenerateKey(pubkeyCurve, rand.Reader)
return &token.Token{AuthKey: authKey}
}
func mockCert() tls.Certificate {
return tls.Certificate{}
}
func mockClient(url string) *apns.Client {
return &apns.Client{Host: url, HTTPClient: http.DefaultClient}
}
type mockTransport struct {
*http2.Transport
closed bool
}
func (c *mockTransport) CloseIdleConnections() {
c.closed = true
}
// Unit Tests
func TestClientDefaultHost(t *testing.T) {
client := apns.NewClient(mockCert())
assert.Equal(t, "https://api.development.push.apple.com", client.Host)
}
func TestTokenDefaultHost(t *testing.T) {
client := apns.NewTokenClient(mockToken()).Development()
assert.Equal(t, "https://api.development.push.apple.com", client.Host)
}
func TestClientDevelopmentHost(t *testing.T) {
client := apns.NewClient(mockCert()).Development()
assert.Equal(t, "https://api.development.push.apple.com", client.Host)
}
func TestTokenClientDevelopmentHost(t *testing.T) {
client := apns.NewTokenClient(mockToken()).Development()
assert.Equal(t, "https://api.development.push.apple.com", client.Host)
}
func TestClientProductionHost(t *testing.T) {
client := apns.NewClient(mockCert()).Production()
assert.Equal(t, "https://api.push.apple.com", client.Host)
}
func TestTokenClientProductionHost(t *testing.T) {
client := apns.NewTokenClient(mockToken()).Production()
assert.Equal(t, "https://api.push.apple.com", client.Host)
}
func TestClientBadUrlError(t *testing.T) {
n := mockNotification()
res, err := mockClient("badurl://badurl.com").Push(n)
assert.Error(t, err)
assert.Nil(t, res)
}
func TestClientBadTransportError(t *testing.T) {
n := mockNotification()
client := mockClient("badurl://badurl.com")
client.HTTPClient.Transport = nil
res, err := client.Push(n)
assert.Error(t, err)
assert.Nil(t, res)
}
func TestClientNameToCertificate(t *testing.T) {
crt, _ := certificate.FromP12File("certificate/_fixtures/certificate-valid.p12", "")
client := apns.NewClient(crt)
name := client.HTTPClient.Transport.(*http2.Transport).TLSClientConfig.NameToCertificate
assert.Len(t, name, 1)
certificate2 := tls.Certificate{}
client2 := apns.NewClient(certificate2)
name2 := client2.HTTPClient.Transport.(*http2.Transport).TLSClientConfig.NameToCertificate
assert.Len(t, name2, 0)
}
func TestDialTLSTimeout(t *testing.T) {
apns.TLSDialTimeout = 10 * time.Millisecond
crt, _ := certificate.FromP12File("certificate/_fixtures/certificate-valid.p12", "")
client := apns.NewClient(crt)
dialTLS := client.HTTPClient.Transport.(*http2.Transport).DialTLS
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
address := listener.Addr().String()
defer listener.Close()
var e error
if _, e = dialTLS("tcp", address, nil); e == nil {
t.Fatal("Dial completed successfully")
}
if !strings.Contains(e.Error(), "timed out") {
t.Errorf("resulting error not a timeout: %s", e)
}
}
// Functional Tests
func TestURL(t *testing.T) {
n := mockNotification()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "POST", r.Method)
assert.Equal(t, fmt.Sprintf("/3/device/%s", n.DeviceToken), r.URL.String())
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestDefaultHeaders(t *testing.T) {
n := mockNotification()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "application/json; charset=utf-8", r.Header.Get("Content-Type"))
assert.Equal(t, "", r.Header.Get("apns-id"))
assert.Equal(t, "", r.Header.Get("apns-collapse-id"))
assert.Equal(t, "", r.Header.Get("apns-priority"))
assert.Equal(t, "", r.Header.Get("apns-topic"))
assert.Equal(t, "", r.Header.Get("apns-expiration"))
assert.Equal(t, "", r.Header.Get("thread-id"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestHeaders(t *testing.T) {
n := mockNotification()
n.ApnsID = "84DB694F-464F-49BD-960A-D6DB028335C9"
n.CollapseID = "game1.start.identifier"
n.Topic = "com.testapp"
n.Priority = 10
n.Expiration = time.Now()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, n.ApnsID, r.Header.Get("apns-id"))
assert.Equal(t, n.CollapseID, r.Header.Get("apns-collapse-id"))
assert.Equal(t, "10", r.Header.Get("apns-priority"))
assert.Equal(t, n.Topic, r.Header.Get("apns-topic"))
assert.Equal(t, fmt.Sprintf("%v", n.Expiration.Unix()), r.Header.Get("apns-expiration"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestAuthorizationHeader(t *testing.T) {
n := mockNotification()
token := mockToken()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "application/json; charset=utf-8", r.Header.Get("Content-Type"))
assert.Equal(t, fmt.Sprintf("bearer %v", token.Bearer), r.Header.Get("authorization"))
}))
defer server.Close()
client := mockClient(server.URL)
client.Token = token
_, err := client.Push(n)
assert.NoError(t, err)
}
func TestPayload(t *testing.T) {
n := mockNotification()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
assert.NoError(t, err)
assert.Equal(t, n.Payload, body)
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestBadPayload(t *testing.T) {
n := mockNotification()
n.Payload = func() {}
_, err := mockClient("").Push(n)
assert.Error(t, err)
}
func Test200SuccessResponse(t *testing.T) {
n := mockNotification()
var apnsID = "02ABC856-EF8D-4E49-8F15-7B8A61D978D6"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("apns-id", apnsID)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
res, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, apnsID, res.ApnsID)
assert.Equal(t, true, res.Sent())
}
func Test400BadRequestPayloadEmptyResponse(t *testing.T) {
n := mockNotification()
var apnsID = "02ABC856-EF8D-4E49-8F15-7B8A61D978D6"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("apns-id", apnsID)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("{\"reason\":\"PayloadEmpty\"}"))
}))
defer server.Close()
res, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
assert.Equal(t, 400, res.StatusCode)
assert.Equal(t, apnsID, res.ApnsID)
assert.Equal(t, apns.ReasonPayloadEmpty, res.Reason)
assert.Equal(t, false, res.Sent())
}
func Test410UnregisteredResponse(t *testing.T) {
n := mockNotification()
var apnsID = "9F595474-356C-485E-B67F-9870BAE68702"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("apns-id", apnsID)
w.WriteHeader(http.StatusGone)
w.Write([]byte("{\"reason\":\"Unregistered\", \"timestamp\": 1458114061260 }"))
}))
defer server.Close()
res, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
assert.Equal(t, 410, res.StatusCode)
assert.Equal(t, apnsID, res.ApnsID)
assert.Equal(t, apns.ReasonUnregistered, res.Reason)
assert.Equal(t, int64(1458114061260)/1000, res.Timestamp.Unix())
assert.Equal(t, false, res.Sent())
}
func TestMalformedJSONResponse(t *testing.T) {
n := mockNotification()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write([]byte("{{MalformedJSON}}"))
}))
defer server.Close()
res, err := mockClient(server.URL).Push(n)
assert.Error(t, err)
assert.Equal(t, false, res.Sent())
}
func TestCloseIdleConnections(t *testing.T) {
transport := &mockTransport{}
client := mockClient("")
client.HTTPClient.Transport = transport
assert.Equal(t, false, transport.closed)
client.CloseIdleConnections()
assert.Equal(t, true, transport.closed)
}