main
 1package test
 2
 3import (
 4	"bytes"
 5	"context"
 6	"io"
 7	"net/http"
 8	"net/http/httptest"
 9
10	xcontext "github.com/xlgmokha/x/pkg/context"
11	"github.com/xlgmokha/x/pkg/serde"
12	"github.com/xlgmokha/x/pkg/x"
13)
14
15func Request(method, target string, options ...x.Option[*http.Request]) *http.Request {
16	request := httptest.NewRequest(method, target, nil)
17	for _, option := range options {
18		request = option(request)
19	}
20	return request
21}
22
23func RequestResponse(method, target string, options ...x.Option[*http.Request]) (*http.Request, *httptest.ResponseRecorder) {
24	return Request(method, target, options...), httptest.NewRecorder()
25}
26
27func WithAcceptHeader(value serde.MediaType) x.Option[*http.Request] {
28	return WithRequestHeader("Accept", value.String())
29}
30
31func WithRequestHeader(key, value string) x.Option[*http.Request] {
32	return func(r *http.Request) *http.Request {
33		r.Header.Set(key, value)
34		return r
35	}
36}
37
38func WithContentType[T any](item T, mediaType serde.MediaType) x.Option[*http.Request] {
39	body := bytes.NewBuffer(nil)
40	x.Check(serde.To[T](body, item, mediaType))
41	return WithRequestBody(io.NopCloser(body))
42}
43
44func WithRequestBody(body io.ReadCloser) x.Option[*http.Request] {
45	return func(r *http.Request) *http.Request {
46		r.Body = body
47		return r
48	}
49}
50
51func WithContext(ctx context.Context) x.Option[*http.Request] {
52	return func(r *http.Request) *http.Request {
53		return r.WithContext(ctx)
54	}
55}
56
57func WithContextKeyValue[T any](ctx context.Context, key xcontext.Key[T], item T) x.Option[*http.Request] {
58	return WithContext(key.With(ctx, item))
59}
60
61func WithCookie(cookie *http.Cookie) x.Option[*http.Request] {
62	return func(r *http.Request) *http.Request {
63		r.AddCookie(cookie)
64		return r
65	}
66}