-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_server.go
99 lines (93 loc) · 2.55 KB
/
test_server.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
package goxios
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
)
type testServer struct {
*httptest.Server
}
type testMethods struct {
method string
url string
body []byte
expectedStatus int
}
func (ts *testServer) Methods(b []byte) []testMethods {
testMethods := []testMethods{
{http.MethodGet, ts.URL + "/get", nil, http.StatusOK},
{http.MethodPost, ts.URL + "/post", b, http.StatusCreated},
{http.MethodPut, ts.URL + "/put", b, http.StatusOK},
{http.MethodPatch, ts.URL + "/patch", b, http.StatusOK},
{http.MethodDelete, ts.URL + "/delete", b, http.StatusNoContent},
}
return testMethods
}
func getTestServer(t *testing.T) *testServer {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.WriteHeader(http.StatusOK)
w.Write([]byte("{'message':'Welcome'}"))
case http.MethodPost, http.MethodPut, http.MethodPatch:
defer r.Body.Close()
b, err := io.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
var msg string
switch r.Method {
case http.MethodPost:
msg = fmt.Sprintf("{'message':'%s created'}", string(b))
w.WriteHeader(http.StatusCreated)
case http.MethodPut, http.MethodPatch:
msg = fmt.Sprintf("{'message':'%s updated'}", string(b))
w.WriteHeader(http.StatusOK)
}
w.Write([]byte(msg))
case http.MethodDelete:
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}))
return &testServer{ts}
}
func getTestServerWithTimeout(t *testing.T, timeout time.Duration) *testServer {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
time.Sleep(timeout)
w.WriteHeader(http.StatusOK)
w.Write([]byte("{'message':'Welcome'}"))
case http.MethodPost, http.MethodPut, http.MethodPatch:
defer r.Body.Close()
b, err := io.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
var msg string
switch r.Method {
case http.MethodPost:
time.Sleep(timeout)
msg = fmt.Sprintf("{'message':'%s created'}", string(b))
w.WriteHeader(http.StatusCreated)
case http.MethodPut, http.MethodPatch:
time.Sleep(timeout)
msg = fmt.Sprintf("{'message':'%s updated'}", string(b))
w.WriteHeader(http.StatusOK)
}
w.Write([]byte(msg))
case http.MethodDelete:
time.Sleep(timeout)
w.WriteHeader(http.StatusNoContent)
default:
time.Sleep(timeout)
w.WriteHeader(http.StatusMethodNotAllowed)
}
}))
return &testServer{ts}
}