context: refactorize assert functions

This commit is contained in:
vinchent 2024-09-21 20:26:22 +02:00
parent 0b181ccf0f
commit c0db9ab22b

View File

@ -11,6 +11,7 @@ import (
type SpyStore struct { type SpyStore struct {
response string response string
cancelled bool cancelled bool
t *testing.T
} }
func (s *SpyStore) Fetch() string { func (s *SpyStore) Fetch() string {
@ -22,10 +23,24 @@ func (s *SpyStore) Cancel() {
s.cancelled = true s.cancelled = true
} }
func (s *SpyStore) assertWasCancelled() {
s.t.Helper()
if !s.cancelled {
s.t.Error("store was not told to cancel")
}
}
func (s *SpyStore) assertWasNotCancelled() {
s.t.Helper()
if s.cancelled {
s.t.Error("it should not have cancelled the store")
}
}
func TestServer(t *testing.T) { func TestServer(t *testing.T) {
t.Run("basic get store", func(t *testing.T) { t.Run("basic get store", func(t *testing.T) {
data := "hello, world" data := "hello, world"
store := &SpyStore{response: data} store := &SpyStore{response: data, t: t}
srv := Server(store) srv := Server(store)
request := httptest.NewRequest(http.MethodGet, "/", nil) request := httptest.NewRequest(http.MethodGet, "/", nil)
@ -37,14 +52,12 @@ func TestServer(t *testing.T) {
t.Errorf(`got "%s", want "%s"`, response.Body.String(), data) t.Errorf(`got "%s", want "%s"`, response.Body.String(), data)
} }
if store.cancelled { store.assertWasNotCancelled()
t.Error("it should not have cancelled the store")
}
}) })
t.Run("tells store to cancel work if request is cancelled", func(t *testing.T) { t.Run("tells store to cancel work if request is cancelled", func(t *testing.T) {
data := "hello, world" data := "hello, world"
store := &SpyStore{response: data} store := &SpyStore{response: data, t: t}
srv := Server(store) srv := Server(store)
request := httptest.NewRequest(http.MethodGet, "/", nil) request := httptest.NewRequest(http.MethodGet, "/", nil)
@ -59,8 +72,6 @@ func TestServer(t *testing.T) {
srv.ServeHTTP(response, request) srv.ServeHTTP(response, request)
if !store.cancelled { store.assertWasCancelled()
t.Error("store was not told to cancel")
}
}) })
} }