summaryrefslogtreecommitdiff
path: root/engine_test.go
blob: 12ec2c69da8d3f6f19edab316f3cfa6c9fa75895 (plain)
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
package growel

import (
	"net/http/httptest"
	"strings"
	"testing"
)

func setupEngine() *Engine {
	e := New()

	e.GET("/", func(c *Context) {
		c.Plain(200, "home")
	})

	e.GET("/hello", func(c *Context) {
		c.JSON(200, map[string]string{"msg": "hi"})
	})

	e.GET("/user/:id", func(c *Context) {
		c.JSON(200, map[string]string{"id": c.Params["id"]})
	})

	e.GET("/error", func(c *Context) {
		c.BadRequest("bad")
	})

	return e
}

func TestEngineStaticRoute(t *testing.T) {
	e := setupEngine()

	req := httptest.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()
	e.ServeHTTP(w, req)

	if w.Code != 200 {
		t.Fatalf("expected 200, got %d", w.Code)
	}

	if w.Body.String() != "home" {
		t.Fatalf("expected body 'home', got %q", w.Body.String())
	}
}

func TestEngineJSONRoute(t *testing.T) {
	e := setupEngine()

	req := httptest.NewRequest("GET", "/hello", nil)
	w := httptest.NewRecorder()
	e.ServeHTTP(w, req)

	if w.Code != 200 {
		t.Fatalf("expected 200, got %d", w.Code)
	}

	if !strings.Contains(w.Body.String(), `"msg":"hi"`) {
		t.Fatalf("unexpected json: %s", w.Body.String())
	}
}

func TestEngineParamRoute(t *testing.T) {
	e := setupEngine()

	req := httptest.NewRequest("GET", "/user/99", nil)
	w := httptest.NewRecorder()
	e.ServeHTTP(w, req)

	if w.Code != 200 {
		t.Fatalf("expected 200, got %d", w.Code)
	}

	if !strings.Contains(w.Body.String(), `"id":"99"`) {
		t.Fatalf("unexpected json: %s", w.Body.String())
	}
}

func TestEngineNotFound(t *testing.T) {
	e := setupEngine()

	req := httptest.NewRequest("GET", "/doesnotexist", nil)
	w := httptest.NewRecorder()
	e.ServeHTTP(w, req)

	if w.Code != 404 {
		t.Fatalf("expected 404, got %d", w.Code)
	}
}

func TestEngineErrorResponse(t *testing.T) {
	e := setupEngine()

	req := httptest.NewRequest("GET", "/error", nil)
	w := httptest.NewRecorder()
	e.ServeHTTP(w, req)

	if w.Code != 400 {
		t.Fatalf("expected 400, got %d", w.Code)
	}

	body := w.Body.String()
	if !strings.Contains(body, `"error":"Bad Request"`) {
		t.Fatalf("missing error text: %s", body)
	}

	if !strings.Contains(body, `"message":"bad"`) {
		t.Fatalf("missing message: %s", body)
	}

	if !strings.Contains(body, `"status":"400"`) {
		t.Fatalf("missing status code: %s", body)
	}
}