feat: make the request test helper public

This commit is contained in:
Muyao CHEN 2024-10-12 17:07:24 +02:00
parent a3c2ade9fb
commit 9b6282a101
2 changed files with 36 additions and 22 deletions

View File

@ -24,33 +24,14 @@ package middleware
import ( import (
"net/http" "net/http"
"net/http/httptest"
"testing" "testing"
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/test"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
type header struct {
Key string
Value string
}
func performRequest(
r http.Handler,
method, path string,
headers ...header,
) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, nil)
for _, h := range headers {
req.Header.Add(h.Key, h.Value)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestRequestID(t *testing.T) { func TestRequestID(t *testing.T) {
r := gin.New() r := gin.New()
r.Use(RequestID()) r.Use(RequestID())
@ -68,10 +49,16 @@ func TestRequestID(t *testing.T) {
}) })
// Test with Request ID // Test with Request ID
_ = performRequest(r, "GET", "/example?a=100", header{XRequestID, wanted}) _ = test.PerformRequest(
r,
"GET",
"/example?a=100",
nil,
test.Header{Key: XRequestID, Value: wanted},
)
assert.Equal(t, "123", got) assert.Equal(t, "123", got)
res := performRequest(r, "GET", "/example?a=100") res := test.PerformRequest(r, "GET", "/example?a=100", nil)
assert.NotEqual(t, "", got) assert.NotEqual(t, "", got)
assert.NoError(t, uuid.Validate(got)) assert.NoError(t, uuid.Validate(got))
assert.Equal(t, res.Header()[XRequestID][0], got) assert.Equal(t, res.Header()[XRequestID][0], got)

View File

@ -0,0 +1,27 @@
package test
import (
"io"
"net/http"
"net/http/httptest"
)
type Header struct {
Key string
Value string
}
func PerformRequest(
r http.Handler,
method, path string,
body io.Reader,
headers ...Header,
) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, body)
for _, h := range headers {
req.Header.Add(h.Key, h.Value)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}