File: pat_test.go

package info (click to toggle)
golang-github-gorilla-pat 0.0~git20160413.0.cf955c3-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 84 kB
  • sloc: makefile: 2
file content (64 lines) | stat: -rw-r--r-- 2,060 bytes parent folder | download | duplicates (2)
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
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package pat

import (
	"net/http"
	"testing"

	"github.com/gorilla/mux"
)

func myHandler(w http.ResponseWriter, r *http.Request) {
}

func testMatch(t *testing.T, meth, pat, path string, ok bool, vars map[string]string) {
	r := New()
	switch meth {
	case "OPTIONS":
		r.Options(pat, myHandler)
	case "DELETE":
		r.Delete(pat, myHandler)
	case "HEAD":
		r.Head(pat, myHandler)
	case "GET":
		r.Get(pat, myHandler)
	case "POST":
		r.Post(pat, myHandler)
	case "PUT":
		r.Put(pat, myHandler)
	case "PATCH":
		r.Patch(pat, myHandler)
	}
	req, _ := http.NewRequest(meth, "http://localhost"+path, nil)
	m := mux.RouteMatch{}
	if r.Match(req, &m) != ok {
		if ok {
			t.Errorf("Expected request to %q to match %q", path, pat)
		} else {
			t.Errorf("Expected request to %q to not match %q", path, pat)
		}
	} else if ok && vars != nil {
		registerVars(req, m.Vars)
		q := req.URL.Query()
		for k, v := range vars {
			if q.Get(k) != v {
				t.Errorf("Variable missing: %q (value: %q)", k, q.Get(k))
			}
		}
	}
}

func TestPatMatch(t *testing.T) {
	testMatch(t, "OPTIONS", "/foo/{name}", "/foo/bar", true, map[string]string{":name": "bar"})
	testMatch(t, "DELETE", "/foo/{name}", "/foo/bar", true, map[string]string{":name": "bar"})
	testMatch(t, "HEAD", "/foo/{name}", "/foo/bar", true, map[string]string{":name": "bar"})
	testMatch(t, "GET", "/foo/{name}", "/foo/bar/baz", true, map[string]string{":name": "bar"})
	testMatch(t, "POST", "/foo/{name}/baz", "/foo/bar/baz", true, map[string]string{":name": "bar"})
	testMatch(t, "PUT", "/foo/{name}/baz", "/foo/bar/baz/ding", true, map[string]string{":name": "bar"})
	testMatch(t, "GET", "/foo/x{name}", "/foo/xbar", true, map[string]string{":name": "bar"})
	testMatch(t, "GET", "/foo/x{name}", "/foo/xbar/baz", true, map[string]string{":name": "bar"})
	testMatch(t, "PATCH", "/foo/x{name}", "/foo/xbar/baz", true, map[string]string{":name": "bar"})
}