Debian Codegraph @

helpers/tdhttp/example_test.go

raw
1 // Copyright (c) 2020, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package tdhttp_test
8
9 import (
10 "encoding/json"
11 "encoding/xml"
12 "fmt"
13 "io"
14 "net/http"
15 "net/url"
16 "strconv"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21
22 "github.com/maxatome/go-testdeep/helpers/tdhttp"
23 "github.com/maxatome/go-testdeep/td"
24 )
25
26 func Example() {
27 t := &testing.T{}
28
29 // Our API handle Persons with 3 routes:
30 // - POST /person
31 // - GET /person/{personID}
32 // - DELETE /person/{personID}
33
34 // Person describes a person.
35 type Person struct {
36 ID int64 `json:"id,omitempty" xml:"ID,omitempty"`
37 Name string `json:"name" xml:"Name"`
38 Age int `json:"age" xml:"Age"`
39 CreatedAt *time.Time `json:"created_at,omitempty" xml:"CreatedAt,omitempty"`
40 }
41
42 // Error is returned to the client in case of error.
43 type Error struct {
44 Mesg string `json:"message" xml:"Message"`
45 Code int `json:"code" xml:"Code"`
46 }
47
48 // Our µDB :)
49 var mu sync.Mutex
50 personByID := map[int64]*Person{}
51 personByName := map[string]*Person{}
52 var lastID int64
53
54 // reply is a helper to send responses.
55 reply := func(w http.ResponseWriter, status int, contentType string, body any) {
56 if body == nil {
57 w.WriteHeader(status)
58 return
59 }
60
61 w.Header().Set("Content-Type", contentType)
62 w.WriteHeader(status)
63 switch contentType {
64 case "application/json":
65 json.NewEncoder(w).Encode(body) //nolint: errcheck
66 case "application/xml":
67 xml.NewEncoder(w).Encode(body) //nolint: errcheck
68 default: // text/plain
69 fmt.Fprintf(w, "%+v", body) //nolint: errcheck
70 }
71 }
72
73 // Our API
74 mux := http.NewServeMux()
75
76 // POST /person
77 mux.HandleFunc("/person", func(w http.ResponseWriter, req *http.Request) {
78 if req.Method != http.MethodPost {
79 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
80 return
81 }
82
83 if req.Body == nil {
84 http.Error(w, "Bad request", http.StatusBadRequest)
85 return
86 }
87 defer req.Body.Close() //nolint: errcheck
88
89 var in Person
90 var contentType string
91
92 switch req.Header.Get("Content-Type") {
93 case "application/json":
94 err := json.NewDecoder(req.Body).Decode(&in)
95 if err != nil {
96 http.Error(w, "Bad request", http.StatusBadRequest)
97 return
98 }
99 case "application/xml":
100 err := xml.NewDecoder(req.Body).Decode(&in)
101 if err != nil {
102 http.Error(w, "Bad request", http.StatusBadRequest)
103 return
104 }
105 case "application/x-www-form-urlencoded":
106 b, err := io.ReadAll(req.Body)
107 if err != nil {
108 http.Error(w, "Bad request", http.StatusBadRequest)
109 return
110 }
111 v, err := url.ParseQuery(string(b))
112 if err != nil {
113 http.Error(w, "Bad request", http.StatusBadRequest)
114 return
115 }
116 in.Name = v.Get("name")
117 in.Age, err = strconv.Atoi(v.Get("age"))
118 if err != nil {
119 http.Error(w, "Bad request", http.StatusBadRequest)
120 return
121 }
122 default:
123 http.Error(w, "Unsupported media type", http.StatusUnsupportedMediaType)
124 return
125 }
126
127 contentType = req.Header.Get("Accept")
128
129 if in.Name == "" || in.Age <= 0 {
130 reply(w, http.StatusBadRequest, contentType, Error{
131 Mesg: "Empty name or bad age",
132 Code: http.StatusBadRequest,
133 })
134 return
135 }
136
137 mu.Lock()
138 defer mu.Unlock()
139 if personByName[in.Name] != nil {
140 reply(w, http.StatusConflict, contentType, Error{
141 Mesg: "Person already exists",
142 Code: http.StatusConflict,
143 })
144 return
145 }
146 lastID++
147 in.ID = lastID
148 now := time.Now()
149 in.CreatedAt = &now
150 personByID[in.ID] = &in
151 personByName[in.Name] = &in
152 reply(w, http.StatusCreated, contentType, in)
153 })
154
155 // GET /person/{id}
156 // DELETE /person/{id}
157 mux.HandleFunc("/person/", func(w http.ResponseWriter, req *http.Request) {
158 id, err := strconv.ParseInt(strings.TrimPrefix(req.URL.Path, "/person/"), 10, 64)
159 if err != nil {
160 http.Error(w, "Bad request", http.StatusBadRequest)
161 return
162 }
163
164 accept := req.Header.Get("Accept")
165
166 mu.Lock()
167 defer mu.Unlock()
168 if personByID[id] == nil {
169 reply(w, http.StatusNotFound, accept, Error{
170 Mesg: "Person does not exist",
171 Code: http.StatusNotFound,
172 })
173 return
174 }
175
176 switch req.Method {
177 case http.MethodGet:
178 reply(w, http.StatusOK, accept, personByID[id])
179 case http.MethodDelete:
180 delete(personByID, id)
181 reply(w, http.StatusNoContent, "", nil)
182 default:
183 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
184 }
185 })
186
187 //
188 // Let's test our API
189 //
190 ta := tdhttp.NewTestAPI(t, mux)
191
192 // Re-usable custom operator to check Content-Type header
193 contentTypeIs := func(ct string) td.TestDeep {
194 return td.SuperMapOf(http.Header{"Content-Type": []string{ct}}, nil)
195 }
196
197 //
198 // Person not found
199 //
200 ta.Get("/person/42", "Accept", "application/json").
201 Name("GET /person/42 - JSON").
202 CmpStatus(404).
203 CmpHeader(contentTypeIs("application/json")).
204 CmpJSONBody(Error{
205 Mesg: "Person does not exist",
206 Code: 404,
207 })
208 fmt.Println("GET /person/42 - JSON:", !ta.Failed())
209
210 ta.Get("/person/42", "Accept", "application/xml").
211 Name("GET /person/42 - XML").
212 CmpStatus(404).
213 CmpHeader(contentTypeIs("application/xml")).
214 CmpXMLBody(Error{
215 Mesg: "Person does not exist",
216 Code: 404,
217 })
218 fmt.Println("GET /person/42 - XML:", !ta.Failed())
219
220 ta.Get("/person/42", "Accept", "text/plain").
221 Name("GET /person/42 - raw").
222 CmpStatus(404).
223 CmpHeader(contentTypeIs("text/plain")).
224 CmpBody("{Mesg:Person does not exist Code:404}")
225 fmt.Println("GET /person/42 - raw:", !ta.Failed())
226
227 //
228 // Create a Person
229 //
230 var bobID int64
231 ta.PostXML("/person", Person{Name: "Bob", Age: 32},
232 "Accept", "application/xml").
233 Name("POST /person - XML").
234 CmpStatus(201).
235 CmpHeader(contentTypeIs("application/xml")).
236 CmpXMLBody(Person{ // using operator anchoring directly in literal
237 ID: ta.A(td.Catch(&bobID, td.NotZero()), int64(0)).(int64),
238 Name: "Bob",
239 Age: 32,
240 CreatedAt: ta.A(td.Ptr(td.Between(ta.SentAt(), time.Now()))).(*time.Time),
241 })
242 fmt.Printf("POST /person - XML: %t → Bob ID=%d\n", !ta.Failed(), bobID)
243
244 var aliceID int64
245 ta.PostJSON("/person", Person{Name: "Alice", Age: 35},
246 "Accept", "application/json").
247 Name("POST /person - JSON").
248 CmpStatus(201).
249 CmpHeader(contentTypeIs("application/json")).
250 CmpJSONBody(td.JSON(` // using JSON operator (yes comment allowed in JSON!)
251 {
252 "id": $1,
253 "name": "Alice",
254 "age": 35,
255 "created_at": $2
256 }`,
257 td.Catch(&aliceID, td.NotZero()),
258 td.Smuggle(func(date string) (time.Time, error) {
259 return time.Parse(time.RFC3339Nano, date)
260 }, td.Between(ta.SentAt(), time.Now()))))
261 fmt.Printf("POST /person - JSON: %t → Alice ID=%d\n", !ta.Failed(), aliceID)
262
263 var brittID int64
264 ta.PostForm("/person",
265 url.Values{
266 "name": []string{"Britt"},
267 "age": []string{"29"},
268 },
269 "Accept", "text/plain").
270 Name("POST /person - raw").
271 CmpStatus(201).
272 CmpHeader(contentTypeIs("text/plain")).
273 // using Re (= Regexp) operator
274 CmpBody(td.Re(`\{ID:(\d+) Name:Britt Age:29 CreatedAt:.*\}\z`,
275 td.Smuggle(func(groups []string) (int64, error) {
276 return strconv.ParseInt(groups[0], 10, 64)
277 }, td.Catch(&brittID, td.NotZero()))))
278 fmt.Printf("POST /person - raw: %t → Britt ID=%d\n", !ta.Failed(), brittID)
279
280 //
281 // Get a Person
282 //
283 ta.Get(fmt.Sprintf("/person/%d", aliceID), "Accept", "application/xml").
284 Name("GET Alice - XML (ID #%d)", aliceID).
285 CmpStatus(200).
286 CmpHeader(contentTypeIs("application/xml")).
287 CmpXMLBody(td.SStruct( // using SStruct operator
288 Person{
289 ID: aliceID,
290 Name: "Alice",
291 Age: 35,
292 },
293 td.StructFields{
294 "CreatedAt": td.Ptr(td.NotZero()),
295 },
296 ))
297 fmt.Println("GET XML Alice:", !ta.Failed())
298
299 ta.Get(fmt.Sprintf("/person/%d", aliceID), "Accept", "application/json").
300 Name("GET Alice - JSON (ID #%d)", aliceID).
301 CmpStatus(200).
302 CmpHeader(contentTypeIs("application/json")).
303 CmpJSONBody(td.JSON(` // using JSON operator (yes comment allowed in JSON!)
304 {
305 "id": $1,
306 "name": "Alice",
307 "age": 35,
308 "created_at": $2
309 }`,
310 aliceID,
311 td.Not(td.Re(`^0001-01-01`)), // time is not 0001-01-01… aka zero time.Time
312 ))
313 fmt.Println("GET JSON Alice:", !ta.Failed())
314
315 //
316 // Delete a Person
317 //
318 ta.Delete(fmt.Sprintf("/person/%d", aliceID), nil).
319 Name("DELETE Alice (ID #%d)", aliceID).
320 CmpStatus(204).
321 CmpHeader(td.Not(td.ContainsKey("Content-Type"))).
322 NoBody()
323 fmt.Println("DELETE Alice:", !ta.Failed())
324
325 // Check Alice is deleted
326 ta.Get(fmt.Sprintf("/person/%d", aliceID), "Accept", "application/json").
327 Name("GET (deleted) Alice - JSON (ID #%d)", aliceID).
328 CmpStatus(404).
329 CmpHeader(contentTypeIs("application/json")).
330 CmpJSONBody(td.JSON(`
331 {
332 "message": "Person does not exist",
333 "code": 404
334 }`))
335 fmt.Println("Alice is not found anymore:", !ta.Failed())
336
337 // Output:
338 // GET /person/42 - JSON: true
339 // GET /person/42 - XML: true
340 // GET /person/42 - raw: true
341 // POST /person - XML: true → Bob ID=1
342 // POST /person - JSON: true → Alice ID=2
343 // POST /person - raw: true → Britt ID=3
344 // GET XML Alice: true
345 // GET JSON Alice: true
346 // DELETE Alice: true
347 // Alice is not found anymore: true
348 }