httpClient_context_test.go 766 B

123456789101112131415161718192021222324252627282930
  1. package httpClient
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "testing"
  7. "time"
  8. )
  9. func TestRequestContextStopsCanceledCall(t *testing.T) {
  10. client := &HttpClient{}
  11. for _, method := range []string{http.MethodGet, http.MethodPost} {
  12. t.Run(method, func(t *testing.T) {
  13. ctx, cancel := context.WithCancel(context.Background())
  14. cancel()
  15. seconds := time.Duration(5)
  16. options := &HttpClientOptions{Context: ctx, Timeout: &seconds}
  17. var err error
  18. if method == http.MethodGet {
  19. _, err = client.HttpGet("http://example.invalid", nil, options)
  20. } else {
  21. _, err = client.HttpPost("http://example.invalid", "body", options)
  22. }
  23. if !errors.Is(err, context.Canceled) {
  24. t.Fatalf("request error = %v, want context canceled", err)
  25. }
  26. })
  27. }
  28. }