File: router_test.go

package info (click to toggle)
golang-github-zenazn-goji 1.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 464 kB
  • sloc: makefile: 3
file content (326 lines) | stat: -rw-r--r-- 7,814 bytes parent folder | download | duplicates (3)
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
package web

import (
	"net/http"
	"net/http/httptest"
	"reflect"
	"regexp"
	"testing"
	"time"
)

// These tests can probably be DRY'd up a bunch

func chHandler(ch chan string, s string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ch <- s
	})
}

var methods = []string{"CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH",
	"POST", "PUT", "TRACE", "OTHER"}

func TestMethods(t *testing.T) {
	t.Parallel()
	m := New()
	ch := make(chan string, 1)

	m.Connect("/", chHandler(ch, "CONNECT"))
	m.Delete("/", chHandler(ch, "DELETE"))
	m.Head("/", chHandler(ch, "HEAD"))
	m.Get("/", chHandler(ch, "GET"))
	m.Options("/", chHandler(ch, "OPTIONS"))
	m.Patch("/", chHandler(ch, "PATCH"))
	m.Post("/", chHandler(ch, "POST"))
	m.Put("/", chHandler(ch, "PUT"))
	m.Trace("/", chHandler(ch, "TRACE"))
	m.Handle("/", chHandler(ch, "OTHER"))

	for _, method := range methods {
		r, _ := http.NewRequest(method, "/", nil)
		w := httptest.NewRecorder()
		m.ServeHTTP(w, r)
		select {
		case val := <-ch:
			if val != method {
				t.Errorf("Got %q, expected %q", val, method)
			}
		case <-time.After(5 * time.Millisecond):
			t.Errorf("Timeout waiting for method %q", method)
		}
	}
}

type testPattern struct{}

func (t testPattern) Prefix() string {
	return ""
}

func (t testPattern) Match(r *http.Request, c *C) bool {
	return true
}
func (t testPattern) Run(r *http.Request, c *C) {
}

var _ Pattern = testPattern{}

func TestPatternTypes(t *testing.T) {
	t.Parallel()
	m := New()

	m.Get("/hello/carl", http.NotFound)
	m.Get("/hello/:name", http.NotFound)
	m.Get(regexp.MustCompile(`^/hello/(?P<name>.+)$`), http.NotFound)
	m.Get(testPattern{}, http.NotFound)
}

type testHandler chan string

func (t testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	t <- "http"
}
func (t testHandler) ServeHTTPC(c C, w http.ResponseWriter, r *http.Request) {
	t <- "httpc"
}

var testHandlerTable = map[string]string{
	"/a": "http fn",
	"/b": "http handler",
	"/c": "web fn",
	"/d": "web handler",
	"/e": "httpc",
}

func TestHandlerTypes(t *testing.T) {
	t.Parallel()
	m := New()
	ch := make(chan string, 1)

	m.Get("/a", func(w http.ResponseWriter, r *http.Request) {
		ch <- "http fn"
	})
	m.Get("/b", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ch <- "http handler"
	}))
	m.Get("/c", func(c C, w http.ResponseWriter, r *http.Request) {
		ch <- "web fn"
	})
	m.Get("/d", HandlerFunc(func(c C, w http.ResponseWriter, r *http.Request) {
		ch <- "web handler"
	}))
	m.Get("/e", testHandler(ch))

	for route, response := range testHandlerTable {
		r, _ := http.NewRequest("GET", route, nil)
		w := httptest.NewRecorder()
		m.ServeHTTP(w, r)
		select {
		case resp := <-ch:
			if resp != response {
				t.Errorf("Got %q, expected %q", resp, response)
			}
		case <-time.After(5 * time.Millisecond):
			t.Errorf("Timeout waiting for path %q", route)
		}

	}
}

// The idea behind this test is to comprehensively test if routes are being
// applied in the right order. We define a special pattern type that always
// matches so long as it's greater than or equal to the global test index. By
// incrementing this index, we can invalidate all routes up to some point, and
// therefore test the routing guarantee that Goji provides: for any path P, if
// both A and B match P, and if A was inserted before B, then Goji will route to
// A before it routes to B.
var rsRoutes = []string{
	"/",
	"/a",
	"/a",
	"/b",
	"/ab",
	"/",
	"/ba",
	"/b",
	"/a",
}

var rsTests = []struct {
	key     string
	results []int
}{
	{"/", []int{0, 5, 5, 5, 5, 5, -1, -1, -1, -1}},
	{"/a", []int{0, 1, 2, 5, 5, 5, 8, 8, 8, -1}},
	{"/b", []int{0, 3, 3, 3, 5, 5, 7, 7, -1, -1}},
	{"/ab", []int{0, 1, 2, 4, 4, 5, 8, 8, 8, -1}},
	{"/ba", []int{0, 3, 3, 3, 5, 5, 6, 7, -1, -1}},
	{"/c", []int{0, 5, 5, 5, 5, 5, -1, -1, -1, -1}},
	{"nope", []int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}},
}

type rsPattern struct {
	i       int
	counter *int
	prefix  string
	ichan   chan int
}

func (rs rsPattern) Prefix() string {
	return rs.prefix
}
func (rs rsPattern) Match(_ *http.Request, _ *C) bool {
	return rs.i >= *rs.counter
}
func (rs rsPattern) Run(_ *http.Request, _ *C) {
}

func (rs rsPattern) ServeHTTP(_ http.ResponseWriter, _ *http.Request) {
	rs.ichan <- rs.i
}

var _ Pattern = rsPattern{}
var _ http.Handler = rsPattern{}

func TestRouteSelection(t *testing.T) {
	t.Parallel()
	m := New()
	counter := 0
	ichan := make(chan int, 1)
	m.NotFound(func(w http.ResponseWriter, r *http.Request) {
		ichan <- -1
	})

	for i, s := range rsRoutes {
		pat := rsPattern{
			i:       i,
			counter: &counter,
			prefix:  s,
			ichan:   ichan,
		}
		m.Get(pat, pat)
	}

	for _, test := range rsTests {
		var n int
		for counter, n = range test.results {
			r, _ := http.NewRequest("GET", test.key, nil)
			w := httptest.NewRecorder()
			m.ServeHTTP(w, r)
			actual := <-ichan
			if n != actual {
				t.Errorf("Expected %q @ %d to be %d, got %d",
					test.key, counter, n, actual)
			}
		}
	}
}

func TestNotFound(t *testing.T) {
	t.Parallel()
	m := New()

	r, _ := http.NewRequest("post", "/", nil)
	w := httptest.NewRecorder()
	m.ServeHTTP(w, r)
	if w.Code != 404 {
		t.Errorf("Expected 404, got %d", w.Code)
	}

	m.NotFound(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "I'm a teapot!", http.StatusTeapot)
	})

	r, _ = http.NewRequest("POST", "/", nil)
	w = httptest.NewRecorder()
	m.ServeHTTP(w, r)
	if w.Code != http.StatusTeapot {
		t.Errorf("Expected a teapot, got %d", w.Code)
	}
}

func TestPrefix(t *testing.T) {
	t.Parallel()
	m := New()
	ch := make(chan string, 1)

	m.Handle("/hello/*", func(w http.ResponseWriter, r *http.Request) {
		ch <- r.URL.Path
	})

	r, _ := http.NewRequest("GET", "/hello/world", nil)
	w := httptest.NewRecorder()
	m.ServeHTTP(w, r)
	select {
	case val := <-ch:
		if val != "/hello/world" {
			t.Errorf("Got %q, expected /hello/world", val)
		}
	case <-time.After(5 * time.Millisecond):
		t.Errorf("Timeout waiting for hello")
	}
}

var validMethodsTable = map[string][]string{
	"/hello/carl":       {"DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"},
	"/hello/bob":        {"DELETE", "GET", "HEAD", "PATCH", "PUT"},
	"/hola/carl":        {"DELETE", "GET", "HEAD", "PUT"},
	"/hola/bob":         {"DELETE"},
	"/does/not/compute": {},
}

func TestValidMethods(t *testing.T) {
	t.Parallel()
	m := New()
	ch := make(chan []string, 1)

	m.NotFound(func(c C, w http.ResponseWriter, r *http.Request) {
		if c.Env == nil {
			ch <- []string{}
			return
		}
		methods, ok := c.Env[ValidMethodsKey]
		if !ok {
			ch <- []string{}
			return
		}
		ch <- methods.([]string)
	})

	m.Get("/hello/carl", http.NotFound)
	m.Post("/hello/carl", http.NotFound)
	m.Head("/hello/bob", http.NotFound)
	m.Get("/hello/:name", http.NotFound)
	m.Put("/hello/:name", http.NotFound)
	m.Patch("/hello/:name", http.NotFound)
	m.Get("/:greet/carl", http.NotFound)
	m.Put("/:greet/carl", http.NotFound)
	m.Delete("/:greet/:anyone", http.NotFound)

	for path, eMethods := range validMethodsTable {
		r, _ := http.NewRequest("BOGUS", path, nil)
		m.ServeHTTP(httptest.NewRecorder(), r)
		aMethods := <-ch
		if !reflect.DeepEqual(eMethods, aMethods) {
			t.Errorf("For %q, expected %v, got %v", path, eMethods,
				aMethods)
		}
	}

	// This should also work when c.Env has already been initalized
	m.Use(func(c *C, h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			c.Env = make(map[interface{}]interface{})
			h.ServeHTTP(w, r)
		})
	})
	for path, eMethods := range validMethodsTable {
		r, _ := http.NewRequest("BOGUS", path, nil)
		m.ServeHTTP(httptest.NewRecorder(), r)
		aMethods := <-ch
		if !reflect.DeepEqual(eMethods, aMethods) {
			t.Errorf("For %q, expected %v, got %v", path, eMethods,
				aMethods)
		}
	}
}