-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
113 lines (103 loc) · 2.45 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
// Copyright 2022 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 (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path"
"strings"
)
var (
testServer *httptest.Server
testClient = NewClient("")
)
func setup() {
m := http.NewServeMux()
m.HandleFunc("/trackers", getTestTrackers)
m.HandleFunc("/addresses", validateTestAddress)
testServer = httptest.NewServer(m)
apiURL = testServer.URL
}
func readTestTrackerFile(trackingCode string) ([]byte, error) {
f, err := os.Open(path.Join("./test/trackers", fmt.Sprintf("%s.json", strings.ToUpper(trackingCode))))
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
}
func getTestTrackers(w http.ResponseWriter, r *http.Request) {
trackingCode := r.FormValue("tracker[tracking_code]")
switch trackingCode {
case paymentError.Error():
w.WriteHeader(http.StatusPaymentRequired)
return
case unauthorizedError.Error():
w.WriteHeader(http.StatusUnauthorized)
return
}
b, err := readTestTrackerFile(trackingCode)
if err != nil {
if os.IsNotExist(err) {
b, err := json.Marshal([]FieldError{
{
Field: "tracking_code",
Message: "not found",
},
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusUnprocessableEntity)
json.NewEncoder(w).Encode(ErrorResponse{
Error: errorMessage{
Message: "not found",
FieldErrors: b,
},
})
} else {
w.WriteHeader(http.StatusInternalServerError)
}
return
}
w.WriteHeader(http.StatusCreated)
w.Write(b)
}
func validateTestAddress(w http.ResponseWriter, r *http.Request) {
var (
addressFileName string
responseCode int
)
streetOne := r.FormValue("address[street1]")
switch streetOne {
case "Valid Street Name":
addressFileName = "valid_address.json"
responseCode = http.StatusOK
default:
addressFileName = "invalid_address.json"
responseCode = http.StatusUnprocessableEntity
}
f, err := os.Open(path.Join("./test/addresses", addressFileName))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(responseCode)
w.Write(b)
}