Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created August 28, 2020 12:28
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 podhmo/70af0c514fa2e67c56f1fadbbee3a31f to your computer and use it in GitHub Desktop.
Save podhmo/70af0c514fa2e67c56f1fadbbee3a31f to your computer and use it in GitHub Desktop.
{"message": "hello"}
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type Client struct {
BaseURL string
HTTPClient *http.Client
}
func (c *Client) Hello() (*http.Response, error) {
hc := c.HTTPClient
if hc == nil {
hc = http.DefaultClient
}
return hc.Get(strings.TrimSuffix(c.BaseURL, "/") + "/hello")
}
type HandlerRoundTripper struct {
Before func(*http.Request)
Handler http.Handler
After func(*http.Response, *http.Request)
}
func (t *HandlerRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
if t.Before != nil {
t.Before(r)
}
w := httptest.NewRecorder()
t.Handler.ServeHTTP(w, r)
res := w.Result()
if t.After != nil {
t.After(res, r)
}
return res, nil
}
func TestIt(t *testing.T) {
c := &Client{
HTTPClient: &http.Client{
Timeout: 100 * time.Millisecond,
Transport: &HandlerRoundTripper{
Before: func(r *http.Request) {
// /hello -> testdata/hello.json
r.URL.Path = fmt.Sprintf("%s.json", strings.TrimSuffix(r.URL.Path, "/"))
},
Handler: http.FileServer(http.Dir("testdata")),
},
},
}
res, err := c.Hello()
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
var b bytes.Buffer
io.Copy(&b, res.Body)
if res.StatusCode != 200 {
t.Errorf("unexpected: %s", res.Status)
}
if strings.TrimSpace(b.String()) != strings.TrimSpace(`{"message": "hello"}`) {
t.Errorf("unmatch: %s", b.String())
}
}
# test log
open testdata/hello.json
open /etc/mime.types
open /etc/apache2/mime.types
open /etc/apache/mime.types
@podhmo
Copy link
Author

podhmo commented Aug 28, 2020

$ tree
.
├── hello_test.go
├── testdata
│   └── hello.json
└── x.log

1 directory, 3 files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment