Skip to content

Commit

Permalink
Merge pull request #9 from carlware/gorutines-support
Browse files Browse the repository at this point in the history
gorutines support
  • Loading branch information
maxcnunes authored Oct 19, 2021
2 parents 1e7e58f + 4332021 commit 824787d
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
54 changes: 54 additions & 0 deletions functional_tests/simple_get_gorutines_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
2 changes: 2 additions & 0 deletions httpfake.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ func New(opts ...ServerOption) *HTTPFake {
return
}

rh.Lock()
rh.called++
rh.Unlock()

if rh.assertions != nil {
if fake.t == nil {
Expand Down
2 changes: 2 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import (
"net/http"
"net/url"
"strings"
"sync"
"testing"
)

// Request stores the settings for a request handler
// 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
Expand Down

0 comments on commit 824787d

Please sign in to comment.