Exemple #1
0
func TestHandlerToUse(t *testing.T) {
	for i, test := range handlerTests {
		t.Logf("test %d: %v", i, test.about)

		r := hroute.New()
		pats := make([]*hroute.Pattern, len(test.add))
		for i, p := range test.add {
			method, path := methodAndPath(p)
			pats[i] = r.Handle(method, path, pathHandler{method, path})
		}
		for _, ltest := range test.lookups {
			t.Logf("- lookup %q", ltest.path)
			method, path := methodAndPath(ltest.path)
			resultHandler, resultParams, resultPat := r.HandlerToUse(method, path)
			expectHandler := ltest.expectHandler
			if expectHandler == nil {
				expectHandler = pathHandler{
					method: method,
					path:   path,
				}
			}
			if !reflect.DeepEqual(resultHandler, expectHandler) {
				t.Fatalf("unexpected result handler; got %#v want %#v", resultHandler, expectHandler)
			}
			if len(resultParams) == 0 {
				resultParams = nil
			}
			if !reflect.DeepEqual(resultParams, ltest.expectParams) {
				t.Fatalf("unexpected result params; got %#v want %#v", resultParams, ltest.expectParams)
			}
			if ltest.matchIndex != -1 {
				// Check that the matched pattern can be used to recreate the path.
				pat := pats[ltest.matchIndex]
				if resultPat != pat {
					t.Fatalf("pattern from HandlerToUse isn't equal to pattern from Handle; got %p (%q) want %p(%q)", resultPat, resultPat, pat, pat)
				}
				vals := make([]string, len(resultParams))
				for i, p := range resultParams {
					vals[i] = p.Value
				}
				reversedPath, err := pat.Path(vals...)
				if err != nil {
					t.Fatalf("cannot reverse pattern path: %v", err)
				} else if reversedPath != path {
					t.Fatalf("pattern did not reverse; got %q want %q", reversedPath, path)
				}
			}
		}
	}
}
Exemple #2
0
func TestGithubRoutes(t *testing.T) {
	r := hroute.New()
	var (
		called       int
		calledParams hroute.Params
		calledMethod string
	)
	for i, p := range githubAPI {
		i, p := i, p
		method, path := methodAndPath(p)
		r.Handle(method, path, hroute.HandlerFunc(func(_ http.ResponseWriter, req *http.Request, p hroute.Params) {
			called = i
			calledMethod = req.Method
			calledParams = p
		}))
	}
	for i, p := range githubAPI {
		called, calledParams, calledMethod = -1, nil, ""
		method, path := methodAndPath(p)
		t.Logf("test %d %s %s", i, method, path)
		r.ServeHTTP(nil, mustNewRequest(method, path))
		if called != i {
			t.Errorf("unexpected called index, got %d want %d", called, i)
		}
		if calledMethod != method {
			t.Errorf("unexpected method, got %q want %q", calledMethod, method)
		}
		_, _, pat := r.Handler(method, path)
		if pat == nil {
			t.Fatalf("no handler found")
		}
		remade, err := pat.Path(paramsValues(calledParams)...)
		if err != nil {
			t.Fatalf("cannot remake path from %#v", calledParams)
		}
		if remade != path {
			t.Errorf("unexpected remade path, got %q want %q", remade, path)
		}
	}
}