diff --git a/functional_tests/simple_get_gorutines_test.go b/functional_tests/simple_get_gorutines_test.go new file mode 100644 index 0000000..272b592 --- /dev/null +++ b/functional_tests/simple_get_gorutines_test.go @@ -0,0 +1,54 @@ +// nolint dupl +package functional_tests + +import ( + "io/ioutil" + "net/http" + "sync" + "testing" + + "github.com/maxcnunes/httpfake" +) + +// TestSimpleGetWithRutines tests a fake server handling a GET request +func TestSimpleGetWithRutines(t *testing.T) { + numOfRequests := 3 + fakeService := httpfake.New() + defer fakeService.Server.Close() + + // register a handler for our fake service + fakeService.NewHandler(). + Get("/users"). + Reply(200). + BodyString(`[{"username": "dreamer"}]`) + + var wg sync.WaitGroup + wg.Add(numOfRequests) + for i := 0; i < numOfRequests; i++ { + go func(wg *sync.WaitGroup) { + res, err := http.Get(fakeService.ResolveURL("/users")) + 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) + } + + wg.Done() + }(&wg) + } + + wg.Wait() +} diff --git a/httpfake.go b/httpfake.go index fa4d48b..a1db898 100644 --- a/httpfake.go +++ b/httpfake.go @@ -72,7 +72,9 @@ func New(opts ...ServerOption) *HTTPFake { return } + rh.Lock() rh.called++ + rh.Unlock() if rh.assertions != nil { if fake.t == nil { diff --git a/request.go b/request.go index db5cc20..1ecf3e5 100644 --- a/request.go +++ b/request.go @@ -4,6 +4,7 @@ import ( "net/http" "net/url" "strings" + "sync" "testing" ) @@ -11,6 +12,7 @@ import ( // Such as how to match this handler for the incoming requests // And how this request will respond back type Request struct { + sync.Mutex Method string URL *url.URL Response *Response