context: implement a spy response writer to check if anything is written

This commit is contained in:
vinchent 2024-09-21 20:46:07 +02:00
parent c5582275e7
commit 7a32f26bd5
2 changed files with 46 additions and 18 deletions

View File

@ -3,6 +3,7 @@ package context
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"net/http" "net/http"
) )
@ -12,7 +13,11 @@ type Store interface {
func Server(store Store) http.HandlerFunc { func Server(store Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
data, _ := store.Fetch(r.Context()) data, err := store.Fetch(r.Context())
if err != nil {
log.Println(err)
return
}
fmt.Fprint(w, data) fmt.Fprint(w, data)
} }
} }

View File

@ -2,6 +2,7 @@ package context
import ( import (
"context" "context"
"errors"
"log" "log"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -39,6 +40,24 @@ func (s *SpyStore) Fetch(ctx context.Context) (string, error) {
} }
} }
type SpyResponseWriter struct {
written bool
}
func (s *SpyResponseWriter) Header() http.Header {
s.written = true
return nil
}
func (s *SpyResponseWriter) Write([]byte) (int, error) {
s.written = true
return 0, errors.New("not implemented")
}
func (s *SpyResponseWriter) WriteHeader(statusCode int) {
s.written = true
}
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"
@ -55,21 +74,25 @@ func TestServer(t *testing.T) {
} }
}) })
// 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, t: t} store := &SpyStore{response: data, t: t}
// srv := Server(store) srv := Server(store)
//
// request := httptest.NewRequest(http.MethodGet, "/", nil) request := httptest.NewRequest(http.MethodGet, "/", nil)
//
// cancellingCtx, cancel := context.WithCancel(request.Context()) cancellingCtx, cancel := context.WithCancel(request.Context())
// // Wait 5ms to call cancel // Wait 5ms to call cancel
// time.AfterFunc(5*time.Millisecond, cancel) time.AfterFunc(5*time.Millisecond, cancel)
//
// request = request.WithContext(cancellingCtx) request = request.WithContext(cancellingCtx)
//
// response := httptest.NewRecorder() response := &SpyResponseWriter{}
//
// srv.ServeHTTP(response, request) srv.ServeHTTP(response, request)
// })
if response.written {
t.Error("a response should not have been written")
}
})
} }