Skip to content

Commit aab7e1f

Browse files
committed
Add Unit Test for Any kind of Response on The Error Case
1 parent 1e1ccfb commit aab7e1f

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

19. Context/learn_context.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,12 @@ type Store interface {
2929

3030
func Server(store Store) http.HandlerFunc {
3131
return func(writer http.ResponseWriter, request *http.Request) {
32-
data, _ := store.Fetch(request.Context())
32+
data, err := store.Fetch(request.Context())
33+
34+
if err != nil {
35+
return // todo: log error however you like
36+
}
37+
3338
fmt.Fprint(writer, data)
3439
}
3540
}

19. Context/learn_context_test.go

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,35 @@ package main
22

33
import (
44
"context"
5+
"errors"
56
"net/http"
67
"net/http/httptest"
78
"testing"
89
"time"
910
)
1011

11-
type SpyStore struct {
12-
response string
13-
t *testing.T
12+
type (
13+
SpyStore struct {
14+
response string
15+
t *testing.T
16+
}
17+
SpyResponseWriter struct {
18+
written bool
19+
}
20+
)
21+
22+
func (s *SpyResponseWriter) Header() http.Header {
23+
s.written = true
24+
return nil
25+
}
26+
27+
func (s *SpyResponseWriter) Write([]byte) (int, error) {
28+
s.written = true
29+
return 0, errors.New("not implemented")
30+
}
31+
32+
func (s *SpyResponseWriter) WriteHeader(statusCode int) {
33+
s.written = true
1434
}
1535

1636
func (s *SpyStore) Fetch(ctx context.Context) (string, error) {
@@ -70,4 +90,24 @@ func TestServer(t *testing.T) {
7090

7191
svr.ServeHTTP(response, request)
7292
})
93+
94+
t.Run("tells store to cancel work if request cancelled", func(t *testing.T) {
95+
data := "hello, world"
96+
store := &SpyStore{response: data, t: t}
97+
svr := Server(store)
98+
99+
request := httptest.NewRequest(http.MethodGet, "/", nil)
100+
101+
cancellingCtx, cancel := context.WithCancel(request.Context())
102+
time.AfterFunc(5*time.Millisecond, cancel)
103+
request = request.WithContext(cancellingCtx)
104+
105+
response := &SpyResponseWriter{}
106+
107+
svr.ServeHTTP(response, request)
108+
109+
if response.written {
110+
t.Error("a response should not have been written")
111+
}
112+
})
73113
}

0 commit comments

Comments
 (0)