context: add basic context test

This commit is contained in:
vinchent 2024-09-21 20:07:09 +02:00
parent 436bcad0e1
commit d49f952035
2 changed files with 45 additions and 0 deletions

16
context/context.go Normal file
View File

@ -0,0 +1,16 @@
package context
import (
"fmt"
"net/http"
)
type Store interface {
Fetch() string
}
func Server(store Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, store.Fetch())
}
}

29
context/context_test.go Normal file
View File

@ -0,0 +1,29 @@
package context
import (
"net/http"
"net/http/httptest"
"testing"
)
type SpyStore struct {
response string
}
func (s *SpyStore) Fetch() string {
return s.response
}
func TestServer(t *testing.T) {
data := "hello, world"
srv := Server(&SpyStore{data})
request := httptest.NewRequest(http.MethodGet, "/", nil)
response := httptest.NewRecorder()
srv.ServeHTTP(response, request)
if response.Body.String() != data {
t.Errorf(`got "%s", want "%s"`, response.Body.String(), data)
}
}