1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
|
package restful
import (
"bytes"
"compress/gzip"
"io"
"net/http"
"reflect"
"sort"
"testing"
)
//
// Step 1 tests
//
var paths = []struct {
// url with path (1) is handled by service with root (2) and last capturing group has value final (3)
path, root, final string
params map[string]string
}{
{"/", "/", "/", map[string]string{}},
{"/p", "/p", "", map[string]string{}},
{"/p/x", "/p/{q}", "", map[string]string{"q": "x"}},
{"/q/x", "/q", "/x", map[string]string{}},
{"/p/x/", "/p/{q}", "/", map[string]string{"q": "x"}},
{"/p/x/y", "/p/{q}", "/y", map[string]string{"q": "x"}},
{"/q/x/y", "/q", "/x/y", map[string]string{}},
{"/z/q", "/{p}/q", "", map[string]string{"p": "z"}},
{"/a/b/c/q", "/", "/a/b/c/q", map[string]string{}},
}
func TestDetectDispatcher(t *testing.T) {
ws1 := new(WebService).Path("/")
ws2 := new(WebService).Path("/p")
ws3 := new(WebService).Path("/q")
ws4 := new(WebService).Path("/p/q")
ws5 := new(WebService).Path("/p/{q}")
ws6 := new(WebService).Path("/p/{q}/")
ws7 := new(WebService).Path("/{p}/q")
var dispatchers = []*WebService{ws1, ws2, ws3, ws4, ws5, ws6, ws7}
wc := NewContainer()
for _, each := range dispatchers {
each.Route(each.GET("").To(dummy))
wc.Add(each)
}
router := RouterJSR311{}
ok := true
for i, fixture := range paths {
who, final, err := router.detectDispatcher(fixture.path, dispatchers)
if err != nil {
t.Logf("error in detection:%v", err)
ok = false
}
if who.RootPath() != fixture.root {
t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath())
ok = false
}
if final != fixture.final {
t.Logf("[line:%v] Unexpected final, expected:%v, actual:%v", i, fixture.final, final)
ok = false
}
params := router.ExtractParameters(&who.Routes()[0], who, fixture.path)
if !reflect.DeepEqual(params, fixture.params) {
t.Logf("[line:%v] Unexpected params, expected:%v, actual:%v", i, fixture.params, params)
ok = false
}
}
if !ok {
t.Fail()
}
}
//
// Step 2 tests
//
// go test -v -test.run TestISSUE_179 ...restful
func TestISSUE_179(t *testing.T) {
ws1 := new(WebService)
ws1.Route(ws1.GET("/v1/category/{param:*}").To(dummy))
routes := RouterJSR311{}.selectRoutes(ws1, "/v1/category/sub/sub")
t.Logf("%v", routes)
}
// go test -v -test.run TestISSUE_30 ...restful
func TestISSUE_30(t *testing.T) {
ws1 := new(WebService).Path("/users")
ws1.Route(ws1.GET("/{id}").To(dummy))
ws1.Route(ws1.POST("/login").To(dummy))
routes := RouterJSR311{}.selectRoutes(ws1, "/login")
if len(routes) != 2 {
t.Fatal("expected 2 routes")
}
if routes[0].Path != "/users/login" {
t.Error("first is", routes[0].Path)
t.Logf("routes:%v", routes)
}
}
// go test -v -test.run TestISSUE_34 ...restful
func TestISSUE_34(t *testing.T) {
ws1 := new(WebService).Path("/")
ws1.Route(ws1.GET("/{type}/{id}").To(dummy))
ws1.Route(ws1.GET("/network/{id}").To(dummy))
routes := RouterJSR311{}.selectRoutes(ws1, "/network/12")
if len(routes) != 2 {
t.Fatal("expected 2 routes")
}
if routes[0].Path != "/network/{id}" {
t.Error("first is", routes[0].Path)
t.Logf("routes:%v", routes)
}
}
// go test -v -test.run TestISSUE_34_2 ...restful
func TestISSUE_34_2(t *testing.T) {
ws1 := new(WebService).Path("/")
// change the registration order
ws1.Route(ws1.GET("/network/{id}").To(dummy))
ws1.Route(ws1.GET("/{type}/{id}").To(dummy))
routes := RouterJSR311{}.selectRoutes(ws1, "/network/12")
if len(routes) != 2 {
t.Fatal("expected 2 routes")
}
if routes[0].Path != "/network/{id}" {
t.Error("first is", routes[0].Path)
}
}
// go test -v -test.run TestISSUE_137 ...restful
func TestISSUE_137(t *testing.T) {
ws1 := new(WebService)
ws1.Route(ws1.GET("/hello").To(dummy))
routes := RouterJSR311{}.selectRoutes(ws1, "/")
t.Log(routes)
if len(routes) > 0 {
t.Error("no route expected")
}
}
func TestSelectRoutesSlash(t *testing.T) {
ws1 := new(WebService).Path("/")
ws1.Route(ws1.GET("").To(dummy))
ws1.Route(ws1.GET("/").To(dummy))
ws1.Route(ws1.GET("/u").To(dummy))
ws1.Route(ws1.POST("/u").To(dummy))
ws1.Route(ws1.POST("/u/v").To(dummy))
ws1.Route(ws1.POST("/u/{w}").To(dummy))
ws1.Route(ws1.POST("/u/{w}/z").To(dummy))
routes := RouterJSR311{}.selectRoutes(ws1, "/u")
checkRoutesContains(routes, "/u", t)
checkRoutesContainsNo(routes, "/u/v", t)
checkRoutesContainsNo(routes, "/", t)
checkRoutesContainsNo(routes, "/u/{w}/z", t)
}
func TestSelectRoutesU(t *testing.T) {
ws1 := new(WebService).Path("/u")
ws1.Route(ws1.GET("").To(dummy))
ws1.Route(ws1.GET("/").To(dummy))
ws1.Route(ws1.GET("/v").To(dummy))
ws1.Route(ws1.POST("/{w}").To(dummy))
ws1.Route(ws1.POST("/{w}/z").To(dummy)) // so full path = /u/{w}/z
routes := RouterJSR311{}.selectRoutes(ws1, "/v") // test against /u/v
checkRoutesContains(routes, "/u/{w}", t)
}
func TestSelectRoutesUsers1(t *testing.T) {
ws1 := new(WebService).Path("/users")
ws1.Route(ws1.POST("").To(dummy))
ws1.Route(ws1.POST("/").To(dummy))
ws1.Route(ws1.PUT("/{id}").To(dummy))
routes := RouterJSR311{}.selectRoutes(ws1, "/1")
checkRoutesContains(routes, "/users/{id}", t)
}
func checkRoutesContains(routes []Route, path string, t *testing.T) {
if !containsRoutePath(routes, path, t) {
for _, r := range routes {
t.Logf("route %v %v", r.Method, r.Path)
}
t.Fatalf("routes should include [%v]:", path)
}
}
func checkRoutesContainsNo(routes []Route, path string, t *testing.T) {
if containsRoutePath(routes, path, t) {
for _, r := range routes {
t.Logf("route %v %v", r.Method, r.Path)
}
t.Fatalf("routes should not include [%v]:", path)
}
}
func containsRoutePath(routes []Route, path string, t *testing.T) bool {
for _, each := range routes {
if each.Path == path {
return true
}
}
return false
}
// go test -v -test.run TestSortableRouteCandidates ...restful
func TestSortableRouteCandidates(t *testing.T) {
fixture := &sortableRouteCandidates{}
r1 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 0}
r2 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 1}
r3 := routeCandidate{matchesCount: 0, literalCount: 1, nonDefaultCount: 1}
r4 := routeCandidate{matchesCount: 1, literalCount: 1, nonDefaultCount: 0}
r5 := routeCandidate{matchesCount: 1, literalCount: 0, nonDefaultCount: 0}
fixture.candidates = append(fixture.candidates, r5, r4, r3, r2, r1)
sort.Sort(sort.Reverse(fixture))
first := fixture.candidates[0]
if first.matchesCount != 1 && first.literalCount != 1 && first.nonDefaultCount != 0 {
t.Fatal("expected r4")
}
last := fixture.candidates[len(fixture.candidates)-1]
if last.matchesCount != 0 && last.literalCount != 0 && last.nonDefaultCount != 0 {
t.Fatal("expected r1")
}
}
func TestDetectRouteReturns404IfNoRoutePassesConditions(t *testing.T) {
called := false
shouldNotBeCalledButWas := false
routes := []Route{
new(RouteBuilder).To(dummy).
If(func(req *http.Request) bool { return false }).
Build(),
// check that condition functions are called in order
new(RouteBuilder).
To(dummy).
If(func(req *http.Request) bool { return true }).
If(func(req *http.Request) bool { called = true; return false }).
Build(),
// check that condition functions short circuit
new(RouteBuilder).
To(dummy).
If(func(req *http.Request) bool { return false }).
If(func(req *http.Request) bool { shouldNotBeCalledButWas = true; return false }).
Build(),
}
_, err := RouterJSR311{}.detectRoute(routes, (*http.Request)(nil))
if se := err.(ServiceError); se.Code != 404 {
t.Fatalf("expected 404, got %d", se.Code)
}
if !called {
t.Fatal("expected condition function to get called, but it wasn't")
}
if shouldNotBeCalledButWas {
t.Fatal("expected condition function to not be called, but it was")
}
}
var extractParams = []struct {
name string
routePath string
urlPath string
expectedParams map[string]string
}{
{"wildcardLastPart", "/fixed/{var:*}", "/fixed/remainder", map[string]string{"var": "remainder"}},
{"wildcardMultipleParts", "/fixed/{var:*}", "/fixed/remain/der", map[string]string{"var": "remain/der"}},
{"wildcardManyParts", "/fixed/{var:*}", "/fixed/test/sub/hi.html", map[string]string{"var": "test/sub/hi.html"}},
{"wildcardInMiddle", "/fixed/{var:*}/morefixed", "/fixed/middle/stuff/morefixed", map[string]string{"var": "middle/stuff"}},
{"wildcardFollowedByVar", "/fixed/{var:*}/morefixed/{otherVar}", "/fixed/middle/stuff/morefixed/end", map[string]string{"var": "middle/stuff", "otherVar": "end"}},
{"singleParam", "/fixed/{var}", "/fixed/remainder", map[string]string{"var": "remainder"}},
{"slash", "/", "/", map[string]string{}},
{"NoVars", "/fixed", "/fixed", map[string]string{}},
{"TwoVars", "/from/{source}/to/{destination}", "/from/LHR/to/AMS", map[string]string{"source": "LHR", "destination": "AMS"}},
{"VarOnFront", "/{what}/from/{source}", "/who/from/SOS", map[string]string{"what": "who", "source": "SOS"}},
}
func TestExtractParams(t *testing.T) {
for _, testCase := range extractParams {
t.Run(testCase.name, func(t *testing.T) {
ws1 := new(WebService).Path("/")
ws1.Route(ws1.GET(testCase.routePath).To(dummy))
router := RouterJSR311{}
req, _ := http.NewRequest(http.MethodGet, testCase.urlPath, nil)
params := router.ExtractParameters(&ws1.Routes()[0], ws1, req.URL.Path)
if len(params) != len(testCase.expectedParams) {
t.Fatalf("Wrong length of params on selected route, expected: %v, got: %v", testCase.expectedParams, params)
}
for expectedParamKey, expectedParamValue := range testCase.expectedParams {
if expectedParamValue != params[expectedParamKey] {
t.Errorf("Wrong parameter for key '%v', expected: %v, got: %v", expectedParamKey, expectedParamValue, params[expectedParamKey])
}
}
})
}
}
func TestSelectRouteInvalidMethod(t *testing.T) {
ws1 := new(WebService).Path("/")
ws1.Route(ws1.GET("/simple").To(dummy))
router := RouterJSR311{}
req, _ := http.NewRequest(http.MethodPost, "/simple", nil)
_, _, err := router.SelectRoute([]*WebService{ws1}, req)
if err == nil {
t.Fatal("Expected an error as the wrong method is used but was nil")
}
}
func TestParameterInWebService(t *testing.T) {
for _, testCase := range extractParams {
t.Run(testCase.name, func(t *testing.T) {
ws1 := new(WebService).Path("/{wsParam}")
ws1.Route(ws1.GET(testCase.routePath).To(dummy))
router := RouterJSR311{}
req, _ := http.NewRequest(http.MethodGet, "/wsValue"+testCase.urlPath, nil)
params := router.ExtractParameters(&ws1.Routes()[0], ws1, req.URL.Path)
expectedParams := map[string]string{"wsParam": "wsValue"}
for key, value := range testCase.expectedParams {
expectedParams[key] = value
}
if len(params) != len(expectedParams) {
t.Fatalf("Wrong length of params on selected route, expected: %v, got: %v", testCase.expectedParams, params)
}
for expectedParamKey, expectedParamValue := range testCase.expectedParams {
if expectedParamValue != params[expectedParamKey] {
t.Errorf("Wrong parameter for key '%v', expected: %v, got: %v", expectedParamKey, expectedParamValue, params[expectedParamKey])
}
}
})
}
}
func dummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "dummy") }
func gzippedDummy() []byte {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
zw.Write([]byte("dummy"))
zw.Flush()
zw.Close()
return buf.Bytes()
}
|