Easy way to test HTTP APIs with more readable and less verbose code.
With standard library | With ApiTest |
---|---|
post_body := map[string]interface{}{
"hello": "World!",
}
post_json, _ := json.Marshal(post_body)
// TODO: handle post_json error
post_bytes := bytes.NewBuffer(post_json)
request, _ := http.NewRequest("POST",
"https://httpbin.org/post", post_bytes)
request.Header.Set("X-My-Header", "hello")
// TODO: handle request error
response, _ := http.DefaultClient.Do(request)
// TODO: handle response error
response_body := map[string]interface{}{}
_ = json.NewDecoder(response.Body).
Decode(&response_body)
// TODO: handle response error
fmt.Println("Check response:", response_body)
|
a := apitest.NewWithBase("https://httpbin.org")
r := a.Request("POST", "/post").
WithHeader("X-My-Header", "hello").
WithBodyJson(map[string]interface{}{
"hello": "World!",
}).Do()
response_body := r.BodyJson()
fmt.Println("Check response:", response_body)
|
my_api := golax.NewApi()
// build `my_api`...
testserver := apitest.New(my_api)
r := testserver.Request("POST", "/users/23/items").
WithHeader("Content-Type", "application/json").
WithCookie("sess_id", "123123213213213"),
WithBodyString(`
{
"name": "pencil",
"description": "Blah blah..."
}
`).
Do()
r.StatusCode // Check this
r.BodyString() // Check this
r := testserver.Request("POST", "/users/23/items").
WithBodyJson(map[string]interface{}{
"name": "pencil",
"description": "Blah blah",
}).
Do()
r := testserver.Request("GET", "/users/23").
Do()
body := r.BodyJson()
func Test_Example(t *testing.T) {
a := golax.NewApi()
a.Root.Node("users").Method("GET", func(c *golax.Context) {
fmt.Fprint(c.Response, "John")
})
s := apitest.New(a)
w := &sync.WaitGroup{}
for i := 0; i < 10; i++ {
w.Add(1)
n := i
go s.Request("GET", "/users").DoAsync(func(r *apitest.Response) {
if http.StatusOK != r.StatusCode {
t.Error("Expected status code is 200")
}
fmt.Println(r.BodyString(), n)
w.Done()
})
}
w.Wait()
}