Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix concurrent map writes to oldClients #128

Merged
merged 1 commit into from May 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions race_test.go
@@ -0,0 +1,14 @@
package httpmock_test

import (
"net/http"
"testing"

. "github.com/jarcoal/httpmock"
)

func TestActivateNonDefaultRace(t *testing.T) {
for i := 0; i < 10; i++ {
go ActivateNonDefault(&http.Client{})
}
}
7 changes: 7 additions & 0 deletions transport.go
Expand Up @@ -777,6 +777,9 @@ var InitialTransport = http.DefaultTransport
// than http.DefaultClient).
var oldClients = map[*http.Client]http.RoundTripper{}

// oldClientsLock protects oldClients from concurrent writes.
var oldClientsLock sync.Mutex

// Activate starts the mock environment. This should be called before
// your tests run. Under the hood this replaces the Transport on the
// http.DefaultClient with httpmock.DefaultTransport.
Expand Down Expand Up @@ -826,6 +829,8 @@ func ActivateNonDefault(client *http.Client) {
}

// save the custom client & it's RoundTripper
oldClientsLock.Lock()
defer oldClientsLock.Unlock()
if _, ok := oldClients[client]; !ok {
oldClients[client] = client.Transport
}
Expand Down Expand Up @@ -887,6 +892,8 @@ func Deactivate() {
http.DefaultTransport = InitialTransport

// reset the custom clients to use their original RoundTripper
oldClientsLock.Lock()
defer oldClientsLock.Unlock()
for oldClient, oldTransport := range oldClients {
oldClient.Transport = oldTransport
delete(oldClients, oldClient)
Expand Down