Skip to content

Commit

Permalink
Merge pull request #1 from maxcnunes/not-found-logs
Browse files Browse the repository at this point in the history
Not found logs and BodyStruct register
  • Loading branch information
maxcnunes authored Oct 28, 2019
2 parents e90b23b + 34dbcef commit c07c10a
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 12 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
language: go

go:
- 1.7.x
- 1.8.x
- 1.12.x
- 1.13.x
- master

script:
Expand Down
51 changes: 51 additions & 0 deletions functional_tests/response_set_reponse_bodystruct_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// nolint dupl
package functional_tests

import (
"io/ioutil"
"net/http"
"testing"

"github.com/maxcnunes/httpfake"
)

// TestResponseBodyStruct tests a fake server handling a GET request
// and responding with a provided struct data
func TestResponseBodyStruct(t *testing.T) {
fakeService := httpfake.New()
defer fakeService.Server.Close()

type user struct {
UserName string `json:"username"`
}
// register a handler for our fake service
fakeService.NewHandler().
Get("/users").
Reply(200).
BodyStruct(&user{UserName: "dreamer"})

req, err := http.NewRequest("GET", fakeService.ResolveURL("/users"), nil)
if err != nil {
t.Fatal(err)
}

res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close() // nolint errcheck

// Check the status code is what we expect
if status := res.StatusCode; status != 200 {
t.Errorf("request returned wrong status code: got %v want %v",
status, 200)
}

// Check the response body is what we expect
expected := `{"username":"dreamer"}`
body, _ := ioutil.ReadAll(res.Body)
if bodyString := string(body); bodyString != expected {
t.Errorf("request returned unexpected body: got %v want %v",
bodyString, expected)
}
}
37 changes: 31 additions & 6 deletions httpfake.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,31 @@ func New() *HTTPFake {
}

fake.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rh := fake.findHandler(r)
rh, err := fake.findHandler(r)
if err != nil {
printError(fmt.Sprintf("error finding handler: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}

if rh == nil {
errMsg := fmt.Sprintf(
"not found request handler for [%s: %s]; registered handlers are:\n",
r.Method, r.URL,
)
for _, frh := range fake.RequestHandlers {
errMsg += fmt.Sprintf("* [%s: %s]\n", frh.Method, frh.URL.Path)
}
printError(errMsg)
w.WriteHeader(http.StatusNotFound)
return
}

if rh.CustomHandle != nil {
rh.CustomHandle(w, r, rh)
return
}

Respond(w, r, rh)
}))

Expand All @@ -61,7 +77,7 @@ func (f *HTTPFake) Reset() *HTTPFake {
return f
}

func (f *HTTPFake) findHandler(r *http.Request) *Request {
func (f *HTTPFake) findHandler(r *http.Request) (*Request, error) {
founds := []*Request{}
url := r.URL.String()
path := getURLPath(url)
Expand All @@ -70,9 +86,13 @@ func (f *HTTPFake) findHandler(r *http.Request) *Request {
continue
}

rhURL, _ := netURL.QueryUnescape(rh.URL.String())
rhURL, err := netURL.QueryUnescape(rh.URL.String())
if err != nil {
return nil, err
}

if rhURL == url {
return rh
return rh, nil
}

// fallback if the income request has query strings
Expand All @@ -83,11 +103,16 @@ func (f *HTTPFake) findHandler(r *http.Request) *Request {
}
// only use the fallback if could find only one match
if len(founds) == 1 {
return founds[0]
return founds[0], nil
}
return nil

return nil, nil
}

func getURLPath(url string) string {
return strings.Split(url, "?")[0]
}

func printError(msg string) {
fmt.Println("\033[0;31mhttpfake: " + msg + "\033[0m")
}
32 changes: 28 additions & 4 deletions response.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package httpfake

import "net/http"
import (
"encoding/json"
"fmt"
"net/http"
)

// Response stores the settings defined by the request handler
// of how it will respond the request back
Expand Down Expand Up @@ -35,8 +39,28 @@ func (r *Response) AddHeader(key, value string) *Response {
return r
}

// BodyString sets the response body
func (r *Response) BodyString(body string) *Response {
r.BodyBuffer = []byte(body)
// Body sets the response body from a byte array
func (r *Response) Body(body []byte) *Response {
r.BodyBuffer = body
return r
}

// BodyString sets the response body from a string
// Example:
// BodyString(`[{"username": "dreamer"}]`)
func (r *Response) BodyString(body string) *Response {
return r.Body([]byte(body))
}

// BodyStruct sets the response body from a struct.
// The provided struct will be marsheled to json internally.
// Example:
// BodyStruct(&entity.User{UserName: "dreamer"})
func (r *Response) BodyStruct(body interface{}) *Response {
b, err := json.Marshal(body)
if err != nil {
printError(fmt.Sprintf("marshalling body %#v failed with %v", body, err))
}

return r.Body(b)
}

0 comments on commit c07c10a

Please sign in to comment.