Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lock to fake handler to avoid races. #1822

Merged
merged 1 commit into from
Oct 16, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 22 additions & 1 deletion pkg/util/fake_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ import (
"net/http"
"net/url"
"reflect"
"sync"
)

// TestInterface is a simple interface providing Errorf, to make injection for
// testing easier (insert 'yo dawg' meme here).
type TestInterface interface {
Errorf(format string, args ...interface{})
Logf(format string, args ...interface{})
}

// LogInterface is a simple interface to allow injection of Logf to report serving errors.
Expand All @@ -45,9 +47,21 @@ type FakeHandler struct {
// For logging - you can use a *testing.T
// This will keep log messages associated with the test.
T LogInterface

// Enforce "only one use" constraint.
lock sync.Mutex
requestCount int
hasBeenChecked bool
}

func (f *FakeHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
f.lock.Lock()
defer f.lock.Unlock()
f.requestCount++
if f.hasBeenChecked {
panic("got request after having been validated")
}

f.RequestReceived = request
response.WriteHeader(f.StatusCode)
response.Write([]byte(f.ResponseBody))
Expand All @@ -60,7 +74,14 @@ func (f *FakeHandler) ServeHTTP(response http.ResponseWriter, request *http.Requ
}

// ValidateRequest verifies that FakeHandler received a request with expected path, method, and body.
func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) {
func (f *FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) {
f.lock.Lock()
defer f.lock.Unlock()
if f.requestCount != 1 {
t.Logf("Expected 1 call, but got %v. Only the last call is recorded and checked.", f.requestCount)
}
f.hasBeenChecked = true

expectURL, err := url.Parse(expectedPath)
if err != nil {
t.Errorf("Couldn't parse %v as a URL.", expectedPath)
Expand Down
2 changes: 2 additions & 0 deletions pkg/util/fake_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ func (f *fakeError) Errorf(format string, args ...interface{}) {
f.errors = append(f.errors, format)
}

func (f *fakeError) Logf(format string, args ...interface{}) {}

func TestFakeHandlerWrongPath(t *testing.T) {
handler := FakeHandler{}
server := httptest.NewServer(&handler)
Expand Down