1package negroni
2
3import (
4	"net/http"
5	"net/http/httptest"
6	"reflect"
7	"testing"
8)
9
10/* Test Helpers */
11func expect(t *testing.T, a interface{}, b interface{}) {
12	if a != b {
13		t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
14	}
15}
16
17func refute(t *testing.T, a interface{}, b interface{}) {
18	if a == b {
19		t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
20	}
21}
22
23func TestNegroniRun(t *testing.T) {
24	// just test that Run doesn't bomb
25	go New().Run(":3000")
26}
27
28func TestNegroniServeHTTP(t *testing.T) {
29	result := ""
30	response := httptest.NewRecorder()
31
32	n := New()
33	n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
34		result += "foo"
35		next(rw, r)
36		result += "ban"
37	}))
38	n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
39		result += "bar"
40		next(rw, r)
41		result += "baz"
42	}))
43	n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
44		result += "bat"
45		rw.WriteHeader(http.StatusBadRequest)
46	}))
47
48	n.ServeHTTP(response, (*http.Request)(nil))
49
50	expect(t, result, "foobarbatbazban")
51	expect(t, response.Code, http.StatusBadRequest)
52}
53
54// Ensures that a Negroni middleware chain
55// can correctly return all of its handlers.
56func TestHandlers(t *testing.T) {
57	response := httptest.NewRecorder()
58	n := New()
59	handlers := n.Handlers()
60	expect(t, 0, len(handlers))
61
62	n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
63		rw.WriteHeader(http.StatusOK)
64	}))
65
66	// Expects the length of handlers to be exactly 1
67	// after adding exactly one handler to the middleware chain
68	handlers = n.Handlers()
69	expect(t, 1, len(handlers))
70
71	// Ensures that the first handler that is in sequence behaves
72	// exactly the same as the one that was registered earlier
73	handlers[0].ServeHTTP(response, (*http.Request)(nil), nil)
74	expect(t, response.Code, http.StatusOK)
75}