-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook_test.go
118 lines (98 loc) · 2.53 KB
/
webhook_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
// Copyright 2019 RetailNext, Inc.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package easypost
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestNewWebHookHandler(t *testing.T) {
setup()
username := "user"
secret := "secret"
webHookHandler := NewWebHookHandler(username, secret)
m := http.NewServeMux()
var (
testEvent *Event
testError error
)
m.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
testEvent, testError = webHookHandler(r)
})
testServer = httptest.NewServer(m)
c := &http.Client{}
request, err := http.NewRequest("POST", fmt.Sprintf("%s/webhook", testServer.URL), nil)
if err != nil {
t.Fatalf("error: %s", err)
}
request.SetBasicAuth("user", "secret1")
_, err = c.Do(request)
if err != nil {
t.Fatalf("error: %s", err)
}
if testError != unauthorizedError {
t.Fatalf("unexpected error: %T (%s)", testError, testError)
}
request, err = http.NewRequest("POST", fmt.Sprintf("%s/webhook", testServer.URL), nil)
if err != nil {
t.Fatalf("error: %s", err)
}
_, err = c.Do(request)
if err != nil {
t.Fatalf("error: %s", err)
}
if testError != unauthorizedError {
t.Fatalf("unexpected error: %T (%s)", testError, testError)
}
trackerBody, err := readTestTrackerFile(TestTrackerCodes[2])
if err != nil {
t.Fatalf("error reading tracking: %s", err)
}
event := Event{
Object: RecordTypeEvent,
Result: trackerBody,
}
b, err := json.Marshal(event)
if err != nil {
t.Fatalf("error: %s", err)
}
request, err = http.NewRequest("POST", fmt.Sprintf("%s/webhook", testServer.URL), bytes.NewReader(b))
if err != nil {
t.Fatalf("error: %s", err)
}
request.SetBasicAuth(username, secret)
_, err = c.Do(request)
if err != nil {
t.Fatalf("error: %s", err)
}
if testError != nil {
t.Fatalf("error: %s", err)
}
if testEvent == nil {
t.Fatal("missing event")
}
easyPostRecord, err := testEvent.GetResult()
if err != nil {
t.Fatalf("error: %s", err)
}
tracker, ok := easyPostRecord.(*Tracker)
if !ok {
t.Fatalf("unexpected record: %T", easyPostRecord)
}
expectedTracker := Tracker{}
if err := json.Unmarshal(trackerBody, &expectedTracker); err != nil {
t.Fatalf("error: %s", err)
}
if !reflect.DeepEqual(*tracker, expectedTracker) {
t.Fatalf("trackers: \nexpected %+v\n got %+v", expectedTracker, *tracker)
}
}