Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Created July 26, 2019 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/874b410fb4da43c6aa35e58de4035d47 to your computer and use it in GitHub Desktop.
Save ziadoz/874b410fb4da43c6aa35e58de4035d47 to your computer and use it in GitHub Desktop.
Test Golang API Client Using httptest Package
package gists
import (
"encoding/json"
"fmt"
"net/http"
)
type Api struct {
client *http.Client
headers map[string]string
BaseURL string
}
type Gist struct {
Id string `json:"id,omitempty"`
Url string `json:"url,omitempty"`
}
func NewApi() *Api {
return &Api{
client: &http.Client{},
headers: map[string]string{"Accept": "application/vnd.github.v3+json"},
BaseURL: "https://api.github.com",
}
}
func (api *Api) GetUserGists(username string) ([]Gist, error) {
request, err := http.NewRequest("GET", fmt.Sprintf("%s/users/%s/gists", api.BaseURL, username), nil)
if err != nil {
return []Gist{}, err
}
for k, v := range api.headers {
request.Header.Set(k, v)
}
response, err := api.client.Do(request)
if err != nil {
return []Gist{}, err
}
defer response.Body.Close()
gists := []Gist{}
err = json.NewDecoder(response.Body).Decode(&gists)
if err != nil {
return []Gist{}, err
}
return gists, nil
}
package gists
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestGetUserRepos(t *testing.T) {
id := "repo1"
url := "http://gists.github.com/repo1"
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`[{"id":"` + id + `","url":"` + url + `"}]`))
})
client := httptest.NewServer(handler)
api := NewApi()
api.BaseURL = client.URL
gists, _ := api.GetUserGists("foobar")
if len(gists) != 1 {
t.Error("returned more than one gist")
}
if gists[0].Id != id {
t.Errorf("gist.Id is not %s", id)
}
if gists[0].Url != url {
t.Errorf("gist.Url is not %s", url)
}
}
package main
import (
"fmt"
"log"
"github.com/ziadoz/gists/http-client-testing/pkg/gists"
)
func main() {
gists, err := gists.NewApi().GetUserGists("ziadoz")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", gists)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment