2020-05-28 15:20:58 +02:00
|
|
|
package requestid_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/kataras/iris/v12"
|
|
|
|
"github.com/kataras/iris/v12/context"
|
|
|
|
"github.com/kataras/iris/v12/httptest"
|
|
|
|
"github.com/kataras/iris/v12/middleware/requestid"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestRequestID(t *testing.T) {
|
|
|
|
app := iris.New()
|
|
|
|
h := func(ctx iris.Context) {
|
|
|
|
ctx.WriteString(requestid.Get(ctx))
|
|
|
|
}
|
|
|
|
|
|
|
|
def := app.Party("/default")
|
|
|
|
{
|
2020-06-07 14:26:06 +02:00
|
|
|
def.Use(requestid.New())
|
2020-05-28 15:20:58 +02:00
|
|
|
def.Get("/", h)
|
|
|
|
}
|
|
|
|
|
|
|
|
const expectedCustomID = "my_id"
|
|
|
|
custom := app.Party("/custom")
|
|
|
|
{
|
2020-07-10 22:21:09 +02:00
|
|
|
customGen := func(ctx *context.Context) string {
|
2020-05-28 15:20:58 +02:00
|
|
|
return expectedCustomID
|
|
|
|
}
|
|
|
|
|
|
|
|
custom.Use(requestid.New(customGen))
|
|
|
|
custom.Get("/", h)
|
|
|
|
}
|
|
|
|
|
|
|
|
const expectedErrMsg = "no id"
|
|
|
|
customWithErr := app.Party("/custom_err")
|
|
|
|
{
|
2020-07-10 22:21:09 +02:00
|
|
|
customGen := func(ctx *context.Context) string {
|
2020-05-28 15:20:58 +02:00
|
|
|
ctx.StopWithText(iris.StatusUnauthorized, expectedErrMsg)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
customWithErr.Use(requestid.New(customGen))
|
|
|
|
customWithErr.Get("/", h)
|
|
|
|
}
|
|
|
|
|
|
|
|
const expectedCustomIDFromOtherMiddleware = "my custom id"
|
|
|
|
changeID := app.Party("/custom_change_id")
|
|
|
|
{
|
|
|
|
changeID.Use(func(ctx iris.Context) {
|
|
|
|
ctx.SetID(expectedCustomIDFromOtherMiddleware)
|
|
|
|
ctx.Next()
|
|
|
|
})
|
2020-06-07 14:26:06 +02:00
|
|
|
changeID.Use(requestid.New())
|
2020-05-28 15:20:58 +02:00
|
|
|
changeID.Get("/", h)
|
|
|
|
}
|
|
|
|
|
|
|
|
e := httptest.New(t, app)
|
|
|
|
e.GET("/default").Expect().Status(httptest.StatusOK).Body().NotEmpty()
|
|
|
|
e.GET("/custom").Expect().Status(httptest.StatusOK).Body().Equal(expectedCustomID)
|
|
|
|
e.GET("/custom_err").Expect().Status(httptest.StatusUnauthorized).Body().Equal(expectedErrMsg)
|
|
|
|
e.GET("/custom_change_id").Expect().Status(httptest.StatusOK).Body().Equal(expectedCustomIDFromOtherMiddleware)
|
|
|
|
}
|