traefik/pkg/middlewares/replacepath/replace_path_test.go

106 lines
2.6 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package replacepath
2017-04-25 18:13:39 +00:00
import (
2018-11-14 09:18:03 +00:00
"context"
2017-04-25 18:13:39 +00:00
"net/http"
"net/http/httptest"
2017-04-25 18:13:39 +00:00
"testing"
"github.com/stretchr/testify/assert"
2018-11-14 09:18:03 +00:00
"github.com/stretchr/testify/require"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/config/dynamic"
2017-04-25 18:13:39 +00:00
)
func TestReplacePath(t *testing.T) {
testCases := []struct {
desc string
path string
config dynamic.ReplacePath
expectedPath string
expectedRawPath string
expectedHeader string
}{
{
desc: "simple path",
path: "/example",
config: dynamic.ReplacePath{
Path: "/replacement-path",
},
expectedPath: "/replacement-path",
expectedRawPath: "",
expectedHeader: "/example",
},
{
desc: "long path",
path: "/some/really/long/path",
config: dynamic.ReplacePath{
Path: "/replacement-path",
},
expectedPath: "/replacement-path",
expectedRawPath: "",
expectedHeader: "/some/really/long/path",
},
{
desc: "path with escaped value",
path: "/foo%2Fbar",
config: dynamic.ReplacePath{
Path: "/replacement-path",
},
expectedPath: "/replacement-path",
expectedRawPath: "",
expectedHeader: "/foo%2Fbar",
},
{
desc: "replacement with escaped value",
path: "/path",
config: dynamic.ReplacePath{
Path: "/foo%2Fbar",
},
expectedPath: "/foo/bar",
expectedRawPath: "/foo%2Fbar",
expectedHeader: "/path",
},
{
desc: "replacement with percent encoded backspace char",
path: "/path/%08bar",
config: dynamic.ReplacePath{
Path: "/path/%08bar",
},
expectedPath: "/path/\bbar",
expectedRawPath: "/path/%08bar",
expectedHeader: "/path/%08bar",
},
2018-11-14 09:18:03 +00:00
}
2017-04-25 18:13:39 +00:00
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
var actualPath, actualRawPath, actualHeader, requestURI string
2018-11-14 09:18:03 +00:00
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualPath = r.URL.Path
actualRawPath = r.URL.RawPath
2018-11-14 09:18:03 +00:00
actualHeader = r.Header.Get(ReplacedPathHeader)
requestURI = r.RequestURI
})
handler, err := New(context.Background(), next, test.config, "foo-replace-path")
2018-11-14 09:18:03 +00:00
require.NoError(t, err)
2017-04-25 18:13:39 +00:00
server := httptest.NewServer(handler)
defer server.Close()
resp, err := http.Get(server.URL + test.path)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
2017-04-25 18:13:39 +00:00
assert.Equal(t, test.expectedPath, actualPath, "Unexpected path.")
assert.Equal(t, test.expectedHeader, actualHeader, "Unexpected '%s' header.", ReplacedPathHeader)
2017-04-25 18:13:39 +00:00
if actualRawPath == "" {
assert.Equal(t, actualPath, requestURI, "Unexpected request URI.")
} else {
assert.Equal(t, actualRawPath, requestURI, "Unexpected request URI.")
}
2017-04-25 18:13:39 +00:00
})
}
}