Created
May 25, 2020 18:29
-
-
Save maxatome/225cb2b9279b321c6f644539df820f13 to your computer and use it in GitHub Desktop.
go mod init httpmocktest && go test -v
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package httpmocktest_test | |
import ( | |
"context" | |
"net/http" | |
"testing" | |
"time" | |
"github.com/jarcoal/httpmock" | |
) | |
func TestTimeout(t *testing.T) { | |
httpmock.Activate() | |
defer httpmock.DeactivateAndReset() | |
httpmock.RegisterResponder("POST", "https://example.com/", | |
func(req *http.Request) (*http.Response, error) { | |
resp, err := httpmock.NewJsonResponse(200, nil) | |
if err != nil { | |
return httpmock.NewStringResponse(400, ""), nil | |
} | |
time.Sleep(1000 * time.Millisecond) | |
return resp, nil | |
}, | |
) | |
req, err := http.NewRequest("POST", "https://example.com/", nil) | |
if err != nil { | |
t.Fatal(err) | |
} | |
client := &http.Client{Timeout: 1 * time.Millisecond} | |
_, err = client.Do(req) | |
if err == nil { | |
t.Fatal("Want a timeout exceeded error but got none.") | |
} else { | |
t.Logf("An error occurred: %s", err) | |
} | |
} | |
func TestTimeout2(t *testing.T) { | |
httpmock.Activate() | |
defer httpmock.DeactivateAndReset() | |
httpmock.RegisterResponder("POST", "https://example.com/", | |
func(req *http.Request) (*http.Response, error) { | |
resp, err := httpmock.NewJsonResponse(200, nil) | |
if err != nil { | |
return httpmock.NewStringResponse(400, ""), nil | |
} | |
time.Sleep(1000 * time.Millisecond) | |
return resp, nil | |
}, | |
) | |
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) | |
defer cancel() | |
req, err := http.NewRequestWithContext(ctx, "POST", "https://example.com/", nil) | |
if err != nil { | |
t.Fatal(err) | |
} | |
client := &http.Client{} | |
_, err = client.Do(req) | |
if err == nil { | |
t.Fatal("Want a timeout exceeded error but got none.") | |
} else { | |
t.Logf("An error occurred: %s", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment