traefik/middlewares/stripPrefixRegex_test.go

90 lines
2.3 KiB
Go
Raw Normal View History

2017-03-24 11:07:59 +00:00
package middlewares
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
2017-03-24 11:07:59 +00:00
)
func TestStripPrefixRegex(t *testing.T) {
testPrefixRegex := []string{"/a/api/", "/b/{regex}/", "/c/{category}/{id:[0-9]+}/"}
2017-03-24 11:07:59 +00:00
tests := []struct {
path string
expectedStatusCode int
expectedPath string
expectedHeader string
2017-03-24 11:07:59 +00:00
}{
{
path: "/a/test",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusNotFound,
},
{
path: "/a/api/test",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusOK,
expectedPath: "test",
expectedHeader: "/a/api/",
},
{
path: "/b/api/",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusOK,
expectedHeader: "/b/api/",
},
{
path: "/b/api/test1",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusOK,
expectedPath: "test1",
expectedHeader: "/b/api/",
},
{
path: "/b/api2/test2",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusOK,
expectedPath: "test2",
expectedHeader: "/b/api2/",
},
{
path: "/c/api/123/",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusOK,
expectedHeader: "/c/api/123/",
},
{
path: "/c/api/123/test3",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusOK,
expectedPath: "test3",
expectedHeader: "/c/api/123/",
},
{
path: "/c/api/abc/test4",
2017-06-01 20:09:36 +00:00
expectedStatusCode: http.StatusNotFound,
},
2017-03-24 11:07:59 +00:00
}
for _, test := range tests {
test := test
t.Run(test.path, func(t *testing.T) {
t.Parallel()
var actualPath, actualHeader string
handlerPath := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualPath = r.URL.Path
actualHeader = r.Header.Get(ForwardedPrefixHeader)
})
handler := NewStripPrefixRegex(handlerPath, testPrefixRegex)
2017-06-01 20:09:36 +00:00
req, err := http.NewRequest(http.MethodGet, "http://localhost"+test.path, nil)
require.NoError(t, err, "%s: unexpected error.", test.path)
2017-06-01 20:09:36 +00:00
resp := &httptest.ResponseRecorder{Code: http.StatusOK}
handler.ServeHTTP(resp, req)
assert.Equal(t, test.expectedStatusCode, resp.Code, "Unexpected status code.")
assert.Equal(t, test.expectedPath, actualPath, "Unexpected path.")
assert.Equal(t, test.expectedHeader, actualHeader, "Unexpected '%s' header.", ForwardedPrefixHeader)
})
2017-03-24 11:07:59 +00:00
}
}