-
Notifications
You must be signed in to change notification settings - Fork 8
/
webhooks_test.go
109 lines (89 loc) · 2.24 KB
/
webhooks_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
package gocardless
import (
"errors"
"net/http"
"net/http/httptest"
"os"
"testing"
)
func TestWebhookFailsWithInvalidSignature(t *testing.T) {
wh, err := NewWebhookHandler("testing", EventHandlerFunc(func(e Event) error {
t.Error("unexpected call")
return nil
}))
if err != nil {
t.Fatal(err)
}
f, err := os.Open("testdata/webhook_request.json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/webhook", f)
wh.ServeHTTP(w, r)
if w.Code != 498 {
t.Fatalf("Expected %d, got %d", 498, w.Code)
}
}
func TestWebhookFailsWithValidSignature(t *testing.T) {
var called int
wh, err := NewWebhookHandler("testing", EventHandlerFunc(func(e Event) error {
called++
expectedID := "EVTESTNE86TNZS"
if e.Id != expectedID {
t.Fatalf("Expected %q, got %q", expectedID, e.Id)
}
return nil
}))
if err != nil {
t.Fatal(err)
}
f, err := os.Open("testdata/webhook_request.json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/webhook", f)
r.Header.Set("Webhook-Signature", "243f3efa57743c24eec7c5e10edc475b547830d256d5b583745afe319dd90936")
wh.ServeHTTP(w, r)
if w.Code != http.StatusNoContent {
t.Fatalf("Expected %d, got %d", http.StatusNoContent, w.Code)
}
if called != 1 {
t.Fatalf("Expected 1 call, got %d", called)
}
}
func TestWebhookWhenHandlerFails(t *testing.T) {
var called int
wh, err := NewWebhookHandler("testing", EventHandlerFunc(func(e Event) error {
called++
expectedID := "EVTESTNE86TNZS"
if e.Id != expectedID {
t.Fatalf("Expected %q, got %q", expectedID, e.Id)
}
if called == 0 {
return nil
}
return errors.New("failed")
}))
if err != nil {
t.Fatal(err)
}
f, err := os.Open("testdata/webhook_request.json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/webhook", f)
r.Header.Set("Webhook-Signature", "243f3efa57743c24eec7c5e10edc475b547830d256d5b583745afe319dd90936")
wh.ServeHTTP(w, r)
if w.Code != http.StatusInternalServerError {
t.Fatalf("Expected %d, got %d", http.StatusInternalServerError, w.Code)
}
if called != 1 {
t.Fatalf("Expected 1 call, got %d", called)
}
}