Skip to content

Commit 9a59353

Browse files
committed
test: add context cancellation unit test
Signed-off-by: Umegbewe Nwebedu <[email protected]>
1 parent 155998a commit 9a59353

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

api/client_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"net/http/httptest"
2222
"net/url"
2323
"testing"
24+
"time"
2425
)
2526

2627
func TestConfig(t *testing.T) {
@@ -116,6 +117,52 @@ func TestClientURL(t *testing.T) {
116117
}
117118
}
118119

120+
func TestDoContextCancellation(t *testing.T) {
121+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
122+
_, _ = w.Write([]byte("partial"))
123+
if f, ok := w.(http.Flusher); ok {
124+
f.Flush()
125+
}
126+
127+
<-r.Context().Done()
128+
}))
129+
130+
defer ts.Close()
131+
132+
client, err := NewClient(Config{
133+
Address: ts.URL,
134+
})
135+
if err != nil {
136+
t.Fatalf("failed to create client: %v", err)
137+
}
138+
139+
req, err := http.NewRequest("GET", ts.URL, nil)
140+
if err != nil {
141+
t.Fatalf("failed to create request: %v", err)
142+
}
143+
144+
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
145+
defer cancel()
146+
147+
start := time.Now()
148+
resp, body, err := client.Do(ctx, req)
149+
elapsed := time.Since(start)
150+
151+
if err != context.DeadlineExceeded {
152+
t.Errorf("expected error %v, got: %v", context.DeadlineExceeded, err)
153+
}
154+
if body != nil {
155+
t.Errorf("expected no body due to cancellation, got: %q", string(body))
156+
}
157+
if elapsed > 200*time.Millisecond {
158+
t.Errorf("Do did not return promptly on cancellation: took %v", elapsed)
159+
}
160+
161+
if resp != nil && resp.Body != nil {
162+
resp.Body.Close()
163+
}
164+
}
165+
119166
// Serve any http request with a response of N KB of spaces.
120167
type serveSpaces struct {
121168
sizeKB int

0 commit comments

Comments
 (0)