Skip to content

Commit

Permalink
refactor code in context_test.go
Browse files Browse the repository at this point in the history
  • Loading branch information
neftales committed Jun 8, 2024
1 parent bbb886c commit 0bca670
Showing 1 changed file with 34 additions and 22 deletions.
56 changes: 34 additions & 22 deletions context/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
type SpyStore struct {
response string
cancelled bool
t *testing.T
}

func (s *SpyStore) Fetch() string {
Expand All @@ -22,30 +23,25 @@ func (s *SpyStore) Cancel() {
s.cancelled = true
}

func TestServer(t *testing.T) {
t.Run("tells store to cancel work if request is cancelled", func(t *testing.T) {
data := "hello, world"
store := &SpyStore{response: data}
svr := Server(store)

request := httptest.NewRequest(http.MethodGet, "/", nil)

cancellingCtx, cancel := context.WithCancel(request.Context())
time.AfterFunc(5*time.Millisecond, cancel)
request = request.WithContext(cancellingCtx)

response := httptest.NewRecorder()
func (s *SpyStore) assertWasCancelled() {
s.t.Helper()

svr.ServeHTTP(response, request)
if !s.cancelled {
s.t.Error("store was not told to cancel")
}
}

if !store.cancelled {
t.Error("store was not told to cancel")
}
})
func (s *SpyStore) assertWasNotCancelled() {
s.t.Helper()
if s.cancelled {
s.t.Error("store was told to cancel")
}
}

func TestServer(t *testing.T) {
t.Run("returns data from store", func(t *testing.T) {
data := "hello, world"
store := &SpyStore{response: data}
store := &SpyStore{response: data, t: t}
srv := Server(store)

request := httptest.NewRequest(http.MethodGet, "/", nil)
Expand All @@ -57,8 +53,24 @@ func TestServer(t *testing.T) {
t.Errorf("got %v, want %v", response.Body.String(), data)
}

if store.cancelled {
t.Errorf("it should not have cancelled the store")
}
store.assertWasNotCancelled()
})

t.Run("tells store to cancel work if request is cancelled", func(t *testing.T) {
data := "hello, world"
store := &SpyStore{response: data, t: t}
svr := Server(store)

request := httptest.NewRequest(http.MethodGet, "/", nil)

cancellingCtx, cancel := context.WithCancel(request.Context())
time.AfterFunc(5*time.Millisecond, cancel)
request = request.WithContext(cancellingCtx)

response := httptest.NewRecorder()

svr.ServeHTTP(response, request)

store.assertWasCancelled()
})
}

0 comments on commit 0bca670

Please sign in to comment.