-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
106 lines (86 loc) · 2.49 KB
/
example_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
package httpsling_test
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"time"
. "github.com/theopenlane/httpsling"
"github.com/theopenlane/httpsling/httpclient"
"github.com/theopenlane/httpsling/httptestutil"
)
func Example() {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write([]byte(`{"color":"red"}`))
}))
defer s.Close()
var out map[string]string
resp, _ := Receive(
out,
Get(s.URL),
)
fmt.Println(resp.StatusCode)
fmt.Printf("%s", out)
}
func Example_receive() {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write([]byte(`{"color":"red"}`))
}))
defer s.Close()
r := struct {
Color string `json:"color"`
}{}
Receive(&r, Get(s.URL))
fmt.Println(r.Color)
}
func Example_everything() {
type Resource struct {
ID string `json:"id"`
Color string `json:"color"`
}
s := httptest.NewServer(MockHandler(201,
JSON(true),
Body(&Resource{Color: "red", ID: "123"}),
))
defer s.Close()
r := httptestutil.Requester(s,
Post("/resources?size=big"),
BearerAuth("atoken"),
JSON(true),
Body(&Resource{Color: "red"}),
ExpectCode(201),
Header("X-Request-Id", "5"),
QueryParam("flavor", "vanilla"),
QueryParams(&struct {
Type string `url:"type"`
}{Type: "upload"}),
Client(
httpclient.SkipVerify(true),
httpclient.Timeout(5*time.Second),
httpclient.MaxRedirects(3),
),
)
r.MustApply(DumpToStderr())
httptestutil.Dump(s, os.Stderr)
serverInspector := httptestutil.Inspect(s)
clientInspector := Inspect(r)
var resource Resource
resp, err := r.Receive(&resource)
if err != nil {
panic(err)
}
fmt.Println("client-side request url path:", clientInspector.Request.URL.Path)
fmt.Println("client-side request query:", clientInspector.Request.URL.RawQuery)
fmt.Println("client-side request body:", clientInspector.RequestBody.String())
ex := serverInspector.LastExchange()
fmt.Println("server-side request authorization header:", ex.Request.Header.Get("Authorization"))
fmt.Println("server-side request request body:", ex.RequestBody.String())
fmt.Println("server-side request response body:", ex.ResponseBody.String())
fmt.Println("client-side response body:", clientInspector.ResponseBody.String())
fmt.Println("response status code:", resp.StatusCode)
fmt.Println("unmarshaled response body:", resource)
}