简体   繁体   中英

How to test http requests in go

I have a go package that is basically a wrapper for a python API. I'm not sure how to test the errors for http.NewRequest, client.Do, and ioutil.ReadAll. I know that httptest exists but I'm pretty new to go and I could not get it to work. Any help would be appreciated!

func DeleteApp(platform string, hostname string, header string) error {

if platform == "" || hostname == "" {
    fmt.Printf("[DELETE APP] Platform and hostname can not be empty strings")
    return errors.New("[DELETE APP] Platform and hostname can not be empty strings")
}
url := fmt.Sprintf(baseURL+"delete-app/%s/%s", platform, hostname)

// Create client & set timeout
client := &http.Client{}
client.Timeout = time.Second * 15

// Create request
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
    fmt.Printf("[DELETE APP] Could not create request : %v", err)
    return err
}

//check for optional header
if header != "" {
    req.Header.Add("X-Fields", header)
}

// Fetch Request
resp, err := client.Do(req)
if err != nil {
    fmt.Printf("[DELETE APP] Could not fetch request : %v", err)
    return err
}
defer resp.Body.Close()

//Read Response Body
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
    fmt.Printf("[DELETE APP] Could not read response body : %v", err)
    return err
}

fmt.Println("response Status : ", resp.Status)
fmt.Println("response Headers : ", resp.Header)
fmt.Println("response Body : ", string(respBody))

return nil

}

You could use httptest.NewServer

func TestDeleteApp(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, client")
    }))
    defer ts.Close()

    baseURL = ts.URL + "/"

    DeleteApp("platform", "hostname", "header")

}

This rewrites your global baseURL , so it can't be a const (you might want to just pass it as a parameter). You can write test assertions in the http.HandlerFunc or based on the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM