diff options
| author | mo khan <mo@mokhan.ca> | 2025-04-14 14:15:58 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-04-14 14:15:58 -0600 |
| commit | d9e9dfde454cc26f4d9a64dbdad6c6db425b6271 (patch) | |
| tree | ca9a8a63e54f8985e76524a4b65aefd775c9535a /pkg/test/http.go | |
| parent | 52aeb516b1d2ed5f6c900a8568c75cdef3f35187 (diff) | |
test: rename test.go to http.go
Diffstat (limited to 'pkg/test/http.go')
| -rw-r--r-- | pkg/test/http.go | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/pkg/test/http.go b/pkg/test/http.go new file mode 100644 index 0000000..54712f1 --- /dev/null +++ b/pkg/test/http.go @@ -0,0 +1,63 @@ +package test + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + + "github.com/xlgmokha/x/pkg/serde" + "github.com/xlgmokha/x/pkg/x" +) + +type RequestOption func(*http.Request) *http.Request + +func Request(method, target string, options ...RequestOption) *http.Request { + request := httptest.NewRequest(method, target, nil) + for _, option := range options { + request = option(request) + } + return request +} + +func RequestResponse(method, target string, options ...RequestOption) (*http.Request, *httptest.ResponseRecorder) { + return Request(method, target, options...), httptest.NewRecorder() +} + +func WithAcceptHeader(value serde.MediaType) RequestOption { + return WithRequestHeader("Accept", string(value)) +} + +func WithRequestHeader(key, value string) RequestOption { + return func(r *http.Request) *http.Request { + r.Header.Set(key, value) + return r + } +} + +func WithContentType[T any](item T, mediaType serde.MediaType) RequestOption { + body := bytes.NewBuffer(nil) + x.Check(serde.To[T](body, item, mediaType)) + return WithRequestBody(io.NopCloser(body)) +} + +func WithRequestBody(body io.ReadCloser) RequestOption { + return func(r *http.Request) *http.Request { + r.Body = body + return r + } +} + +func WithContext(ctx context.Context) RequestOption { + return func(r *http.Request) *http.Request { + return r.WithContext(ctx) + } +} + +func WithCookie(cookie *http.Cookie) RequestOption { + return func(r *http.Request) *http.Request { + r.AddCookie(cookie) + return r + } +} |
