v / vlib / net / http / http_httpbin_test.v
96 lines · 89 sloc · 2.2 KB · 811d486733db72b7f56216cc46ccd6608e26768b
Raw
1// vtest retry: 3
2module http
3
4// internal tests have access to *everything in the module*
5import json
6
7struct HttpbinResponseBody {
8 args map[string]string
9 data string
10 files map[string]string
11 form map[string]string
12 headers map[string]string
13 json map[string]string
14 origin string
15 url string
16}
17
18fn http_fetch_mock(_methods []string, _config FetchConfig) ![]Response {
19 url := 'https://url4e.com/httpbin/'
20 methods := if _methods.len == 0 { ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'] } else { _methods }
21 mut config := _config
22 mut result := []Response{}
23 // Note: httpbin doesn't support head
24 for method in methods {
25 lmethod := method.to_lower()
26 config.method = method_from_str(method)
27 res := fetch(FetchConfig{ ...config, url: url + lmethod })!
28 // TODO
29 // body := json.decode(HttpbinResponseBody,res.body)!
30 result << res
31 }
32 return result
33}
34
35fn test_http_fetch_bare() {
36 $if !network ? {
37 return
38 }
39 responses := http_fetch_mock([], FetchConfig{}) or { panic(err) }
40 for response in responses {
41 assert response.status() == .ok
42 }
43}
44
45fn test_http_fetch_with_data() {
46 $if !network ? {
47 return
48 }
49 responses := http_fetch_mock(['POST', 'PUT', 'PATCH', 'DELETE'],
50 data: 'hello world'
51 ) or { panic(err) }
52 for response in responses {
53 payload := json.decode(HttpbinResponseBody, response.body) or { panic(err) }
54 assert payload.data == 'hello world'
55 }
56}
57
58fn test_http_fetch_with_params() {
59 $if !network ? {
60 return
61 }
62 responses := http_fetch_mock([],
63 params: {
64 'a': 'b'
65 'c': 'd'
66 }
67 ) or { panic(err) }
68 for response in responses {
69 // payload := json.decode(HttpbinResponseBody,response.body) or {
70 // panic(err)
71 // }
72 assert response.status() == .ok
73 // TODO
74 // assert payload.args['a'] == 'b'
75 // assert payload.args['c'] == 'd'
76 }
77}
78
79fn test_http_fetch_with_headers() ! {
80 $if !network ? {
81 return
82 }
83 mut header := new_header()
84 header.add_custom('Test-Header', 'hello world')!
85 responses := http_fetch_mock([],
86 header: header
87 ) or { panic(err) }
88 for response in responses {
89 // payload := json.decode(HttpbinResponseBody,response.body) or {
90 // panic(err)
91 // }
92 assert response.status() == .ok
93 // TODO
94 // assert payload.headers['Test-Header'] == 'hello world'
95 }
96}
97