Added UT for request-id middleware
@@ -6,6 +6,10 @@ import (
"net/http/httptest"
"testing"
+ "github.com/go-openapi/swag"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+
"github.com/stretchr/testify/mock"
)
@@ -65,3 +69,60 @@ func TestTransport(t *testing.T) {
})
}
}
+
+func TestMiddleware(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name string
+ requestID *string
+ }{
+ {
+ name: "RequestID exist",
+ requestID: swag.String("1234"),
+ },
+ {
+ name: "no request in context",
+ requestID: nil,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // create a handler to use as "next" which will verify the request
+ nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ val := r.Context().Value(ctxKey)
+ assert.NotNil(t, val)
+ valStr, ok := val.(string)
+ if !ok {
+ t.Error("not string")
+ }
+
+ if tt.requestID != nil {
+ // if request-id passed in header, that should be in the context
+ assert.Equal(t, valStr, *tt.requestID)
+ } else {
+ // if no request-id passed in header, valid uuid should be generated by middleware
+ assert.True(t, IsValidUUID(valStr))
+ }
+
+ })
+
+ // create the handler to test, using our custom "next" handler
+ h := Middleware(nextHandler)
+
+ // create a mock request to use
+ req := httptest.NewRequest("GET", "http://testing", nil)
+ if tt.requestID != nil {
+ req.Header.Set(headerKey, *tt.requestID)
+ }
+
+ // call the handler using a mock response recorder (we'll not use that anyway)
+ h.ServeHTTP(httptest.NewRecorder(), req)
+ })
+ }
+}
+
+func IsValidUUID(u string) bool {
+ _, err := uuid.Parse(u)
+ return err == nil
+}
