Skip to content

Commit fbf2267

Browse files
authored
Merge pull request #128 from roboslone/v1
Fix concurrent map writes to oldClients
2 parents 70189fd + da037fb commit fbf2267

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

race_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package httpmock_test
2+
3+
import (
4+
"net/http"
5+
"testing"
6+
7+
. "github.com/jarcoal/httpmock"
8+
)
9+
10+
func TestActivateNonDefaultRace(t *testing.T) {
11+
for i := 0; i < 10; i++ {
12+
go ActivateNonDefault(&http.Client{})
13+
}
14+
}

transport.go

+7
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,9 @@ var InitialTransport = http.DefaultTransport
777777
// than http.DefaultClient).
778778
var oldClients = map[*http.Client]http.RoundTripper{}
779779

780+
// oldClientsLock protects oldClients from concurrent writes.
781+
var oldClientsLock sync.Mutex
782+
780783
// Activate starts the mock environment. This should be called before
781784
// your tests run. Under the hood this replaces the Transport on the
782785
// http.DefaultClient with httpmock.DefaultTransport.
@@ -826,6 +829,8 @@ func ActivateNonDefault(client *http.Client) {
826829
}
827830

828831
// save the custom client & it's RoundTripper
832+
oldClientsLock.Lock()
833+
defer oldClientsLock.Unlock()
829834
if _, ok := oldClients[client]; !ok {
830835
oldClients[client] = client.Transport
831836
}
@@ -887,6 +892,8 @@ func Deactivate() {
887892
http.DefaultTransport = InitialTransport
888893

889894
// reset the custom clients to use their original RoundTripper
895+
oldClientsLock.Lock()
896+
defer oldClientsLock.Unlock()
890897
for oldClient, oldTransport := range oldClients {
891898
oldClient.Transport = oldTransport
892899
delete(oldClients, oldClient)

0 commit comments

Comments
 (0)