import (
"bufio"
"bytes"
+ "context"
"crypto/tls"
"io"
"net/http"
"strings"
)
-// NewRequest returns a new incoming server Request, suitable
+// NewRequest wraps NewRequestWithContext using context.Background.
+func NewRequest(method, target string, body io.Reader) *http.Request {
+ return NewRequestWithContext(context.Background(), method, target, body)
+}
+
+// NewRequestWithContext returns a new incoming server Request, suitable
// for passing to an [http.Handler] for testing.
//
// The target is the RFC 7230 "request-target": it may be either a
//
// To generate a client HTTP request instead of a server request, see
// the NewRequest function in the net/http package.
-func NewRequest(method, target string, body io.Reader) *http.Request {
+func NewRequestWithContext(ctx context.Context, method, target string, body io.Reader) *http.Request {
if method == "" {
method = "GET"
}
if err != nil {
panic("invalid NewRequest arguments; " + err.Error())
}
+ req = req.WithContext(ctx)
// HTTP/1.0 was used above to avoid needing a Host field. Change it to 1.1 here.
req.Proto = "HTTP/1.1"
package httptest
import (
+ "context"
"crypto/tls"
"io"
"net/http"
)
func TestNewRequest(t *testing.T) {
+ got := NewRequest("GET", "/", nil)
+ want := &http.Request{
+ Method: "GET",
+ Host: "example.com",
+ URL: &url.URL{Path: "/"},
+ Header: http.Header{},
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ RemoteAddr: "192.0.2.1:1234",
+ RequestURI: "/",
+ }
+ got.Body = nil // before DeepEqual
+ want = want.WithContext(context.Background())
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("Request mismatch:\n got: %#v\nwant: %#v", got, want)
+ }
+}
+
+func TestNewRequestWithContext(t *testing.T) {
for _, tt := range [...]struct {
name string
},
} {
t.Run(tt.name, func(t *testing.T) {
- got := NewRequest(tt.method, tt.uri, tt.body)
+ got := NewRequestWithContext(context.Background(), tt.method, tt.uri, tt.body)
slurp, err := io.ReadAll(got.Body)
if err != nil {
t.Errorf("ReadAll: %v", err)
if string(slurp) != tt.wantBody {
t.Errorf("Body = %q; want %q", slurp, tt.wantBody)
}
+ tt.want = tt.want.WithContext(context.Background())
got.Body = nil // before DeepEqual
if !reflect.DeepEqual(got.URL, tt.want.URL) {
t.Errorf("Request.URL mismatch:\n got: %#v\nwant: %#v", got.URL, tt.want.URL)