-
Notifications
You must be signed in to change notification settings - Fork 335
/
client_test.go
477 lines (423 loc) · 14.9 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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package apns2_test
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"errors"
"fmt"
"io"
"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.sandbox.push.apple.com", client.Host)
}
func TestTokenDefaultHost(t *testing.T) {
client := apns.NewTokenClient(mockToken()).Development()
assert.Equal(t, "https://api.sandbox.push.apple.com", client.Host)
}
func TestClientDevelopmentHost(t *testing.T) {
client := apns.NewClient(mockCert()).Development()
assert.Equal(t, "https://api.sandbox.push.apple.com", client.Host)
}
func TestTokenClientDevelopmentHost(t *testing.T) {
client := apns.NewTokenClient(mockToken()).Development()
assert.Equal(t, "https://api.sandbox.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 TestClientBadDeviceToken(t *testing.T) {
n := &apns.Notification{}
n.DeviceToken = "DGw\aOoD+HwSroh#Ug]%xzd]"
n.Payload = []byte(`{"aps":{"alert":"Hello!"}}`)
res, err := mockClient("https://api.push.apple.com").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")
}
// Go 1.7.x and later will return a context deadline exceeded error
// Previous versions will return a time out
if !strings.Contains(e.Error(), "timed out") && !errors.Is(e, context.DeadlineExceeded) {
t.Errorf("Unexpected error: %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"))
assert.Equal(t, "alert", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestClientPushWithContextWithTimeout(t *testing.T) {
const timeout = time.Nanosecond
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()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
time.Sleep(timeout)
res, err := mockClient(server.URL).PushWithContext(ctx, n)
assert.Error(t, err)
assert.Nil(t, res)
cancel()
}
func TestClientPushWithContext(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).PushWithContext(context.Background(), n)
assert.Nil(t, err)
assert.Equal(t, res.ApnsID, apnsID)
}
func TestClientPushWithNilContext(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).PushWithContext(nil, n)
assert.EqualError(t, err, "net/http: nil Context")
assert.Nil(t, res)
}
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 TestExpirationHeader(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.Unix(0, 0)
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, "", r.Header.Get("apns-expiration"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeAlertHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeAlert
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "alert", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeBackgroundHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeBackground
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "background", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeLocationHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeLocation
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "location", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeVOIPHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeVOIP
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "voip", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeComplicationHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeComplication
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "complication", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeFileProviderHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeFileProvider
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "fileprovider", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeMDMHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeMDM
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "mdm", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypeLiveActivityHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypeLiveActivity
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "liveactivity", r.Header.Get("apns-push-type"))
}))
defer server.Close()
_, err := mockClient(server.URL).Push(n)
assert.NoError(t, err)
}
func TestPushTypePushToTalkHeader(t *testing.T) {
n := mockNotification()
n.PushType = apns.PushTypePushToTalk
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "pushtotalk", r.Header.Get("apns-push-type"))
}))
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 := io.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"
var apnsUniqueID = "A6739D99-D92A-424B-A91E-BF012365BD4E"
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.Header().Set("apns-unique-id", apnsUniqueID)
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, apnsUniqueID, res.ApnsUniqueID)
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)
}