Skip to content

Commit

Permalink
fixed race reported in #45 + filled out missing test
Browse files Browse the repository at this point in the history
  • Loading branch information
dselans committed Aug 13, 2018
1 parent 67b4fbf commit 9d50332
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
45 changes: 45 additions & 0 deletions checkers/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"
"time"

"fmt"
. "github.com/onsi/gomega"
)

Expand Down Expand Up @@ -254,6 +255,50 @@ func TestHTTPStatus(t *testing.T) {
})

t.Run("Should return error if response body is not readable", func(t *testing.T) {
httpClient := &http.Client{
Transport: newTransport(),
}

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("foo"))
}))
defer ts.Close()

testURL, err := url.Parse(ts.URL)
Expect(err).ToNot(HaveOccurred())

cfg := &HTTPConfig{
URL: testURL,
Expect: "foo",
Client: httpClient,
}

checker, err := NewHTTP(cfg)
Expect(err).ToNot(HaveOccurred())

data, err := checker.Status()

Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Unable to read response body to perform content expectancy check"))
Expect(data).To(BeNil())
})
}

type CustomTransport struct{}

func newTransport() *CustomTransport {
return &CustomTransport{}
}

func (c *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: &mockReader{},
}, nil
}

type mockReader struct{}

func (m *mockReader) Read(p []byte) (n int, err error) { return 0, fmt.Errorf("foo") }
func (m *mockReader) Close() error { return nil }
10 changes: 9 additions & 1 deletion health.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,15 @@ func (h *Health) safeUpdateState(stateEntry *State) {
func (h *Health) safeGetStates() map[string]State {
h.statesLock.Lock()
defer h.statesLock.Unlock()
return h.states

// deep copy h.states to avoid race
statesCopy := make(map[string]State, 0)

for k, v := range h.states {
statesCopy[k] = v
}

return statesCopy
}

// if a status listener is attached
Expand Down
1 change: 0 additions & 1 deletion health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,6 @@ func TestStop(t *testing.T) {
// 3rd and 4th message should indicate goroutine exit
msgs := testLogger.Bytes()
Expect(msgs).To(ContainSubstring("Stopping checker name=" + cfg.Name))

Expect(msgs).To(ContainSubstring("Checker exiting name=" + cfg.Name))
}

Expand Down

0 comments on commit 9d50332

Please sign in to comment.