Skip to content

fulldump/apitest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

595766e · Jan 31, 2025

History

16 Commits
Aug 18, 2020
Apr 13, 2024
May 1, 2018
Aug 20, 2020
Apr 13, 2024
Jan 31, 2025
Jan 31, 2025
Apr 13, 2024
Apr 13, 2024
Oct 3, 2017

Repository files navigation

Apitest

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)
			

Getting started

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

Sending body JSON

r := testserver.Request("POST", "/users/23/items").
    WithBodyJson(map[string]interface{}{
        "name": "pencil",
        "description": "Blah blah",
    }).
    Do()

Reading body JSON

r := testserver.Request("GET", "/users/23").
    Do()
    
body := r.BodyJson()

Asynchronous request

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()
}