Skip to content

Commit d63c5a0

Browse files
committed
test: Use round tripper for mocking http client responses
1 parent a5977f4 commit d63c5a0

File tree

4 files changed

+134
-164
lines changed

4 files changed

+134
-164
lines changed

client.go

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,17 @@ import (
55
"time"
66
)
77

8-
var client HttpClient
9-
10-
type HttpClient interface {
11-
Do(req *http.Request) (*http.Response, error)
12-
}
8+
var httpClient *http.Client
139

1410
// getHTTPClient returns the shared HTTP client
15-
func getHTTPClient() HttpClient {
16-
if client == nil {
11+
func getHTTPClient() *http.Client {
12+
if httpClient == nil {
1713
tr := http.DefaultTransport.(*http.Transport).Clone()
1814
tr.MaxIdleConnsPerHost = 50
19-
client = &http.Client{
15+
httpClient = &http.Client{
2016
Timeout: time.Second * 10,
2117
Transport: tr,
2218
}
2319
}
24-
return client
20+
return httpClient
2521
}

client_test.go

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,15 @@ import (
77
)
88

99
func TestValidateClient(t *testing.T) {
10-
oldRef := getHTTPClient()
11-
defer func() {
12-
client = oldRef
13-
}()
14-
client = nil
10+
httpClient = nil
1511
client := getHTTPClient()
1612
if client == nil {
1713
t.Error("client should not be nil")
1814
}
19-
cl := client.(*http.Client)
20-
if cl.Timeout != 10*time.Second {
15+
if client.Timeout != 10*time.Second {
2116
t.Error("default timeout should be 10 seconds")
2217
}
23-
tr := cl.Transport.(*http.Transport)
18+
tr := client.Transport.(*http.Transport)
2419
if tr.MaxIdleConnsPerHost != 50 {
2520
t.Error("default max conns idle conns per host should be 150")
2621
}

0 commit comments

Comments
 (0)