Ejemplo n.º 1
0
func TestApplication_ServeHTTP_withPOST(t *testing.T) {
	// plain.
	func() {
		values := url.Values{}
		values.Set("name", "naoina")
		values.Add("type", "human")
		req, err := http.NewRequest("POST", "/post_test", bytes.NewBufferString(values.Encode()))
		if err != nil {
			t.Fatal(err)
		}
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		app := kocha.NewTestApp()
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
		var actual interface{} = w.Code
		var expected interface{} = http.StatusOK
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("POST /post_test status => %#v, want %#v", actual, expected)
		}

		actual = w.Body.String()
		expected = "This is layout\nmap[params:map[]]\n\n"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("POST /post_test body => %#v, want %#v", actual, expected)
		}
	}()

	// with FormMiddleware.
	func() {
		values := url.Values{}
		values.Set("name", "naoina")
		values.Add("type", "human")
		req, err := http.NewRequest("POST", "/post_test", bytes.NewBufferString(values.Encode()))
		if err != nil {
			t.Fatal(err)
		}
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		app := kocha.NewTestApp()
		app.Config.Middlewares = []kocha.Middleware{&kocha.FormMiddleware{}, &kocha.DispatchMiddleware{}}
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
		var actual interface{} = w.Code
		var expect interface{} = http.StatusOK
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("POST /post_test status => %#v, want %#v", actual, expect)
		}

		actual = w.Body.String()
		expect = "This is layout\nmap[params:map[name:[naoina] type:[human]]]\n\n"
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("POST /post_test body => %#v, want %#v", actual, expect)
		}
	}()
}
Ejemplo n.º 2
0
func TestTemplate_FuncMap_in(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	var buf bytes.Buffer
	for _, v := range []struct {
		Arr    interface{}
		Sep    interface{}
		expect string
		err    error
	}{
		{[]string{"b", "a", "c"}, "a", "true", nil},
		{[]string{"ab", "b", "c"}, "a", "false", nil},
		{nil, "a", "", fmt.Errorf("valid types are slice, array and string, got `invalid'")},
	} {
		buf.Reset()
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{in .Arr .Sep}}`))
		err := tmpl.Execute(&buf, v)
		if !strings.HasSuffix(fmt.Sprint(err), fmt.Sprint(v.err)) {
			t.Errorf(`{{in %#v %#v}}; error has "%v"; want "%v"`, v.Arr, v.Sep, err, v.err)
		}
		actual := buf.String()
		expect := v.expect
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`{{in %#v %#v}} => %#v; want %#v`, v.Arr, v.Sep, actual, expect)
		}
	}
}
Ejemplo n.º 3
0
func TestTemplate_FuncMap_url(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)

	func() {
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "root"}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, nil); err != nil {
			panic(err)
		}
		actual := buf.String()
		expected := "/"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	func() {
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "user" 713}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, nil); err != nil {
			panic(err)
		}
		actual := buf.String()
		expected := "/user/713"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %v, but %v", expected, actual)
		}
	}()
}
Ejemplo n.º 4
0
func TestRouter_Reverse(t *testing.T) {
	app := kocha.NewTestApp()
	for _, v := range []struct {
		name   string
		args   []interface{}
		expect string
	}{
		{"root", []interface{}{}, "/"},
		{"user", []interface{}{77}, "/user/77"},
		{"date", []interface{}{2013, 10, 26, "naoina"}, "/2013/10/26/user/naoina"},
		{"static", []interface{}{"/hoge.png"}, "/static/hoge.png"},
		{"static", []interface{}{"hoge.png"}, "/static/hoge.png"},
	} {
		r, err := app.Router.Reverse(v.name, v.args...)
		if err != nil {
			t.Errorf(`Router.Reverse(%#v, %#v) => (_, %#v); want (_, %#v)`, v.name, v.args, err, err)
			continue
		}
		actual := r
		expect := v.expect
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`Router.Reverse(%#v, %#v) => (%#v, %#v); want (%#v, %#v)`, v.name, v.args, actual, err, expect, err)
		}
	}
}
Ejemplo n.º 5
0
func TestTemplateFuncMap_join(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{join .Arr .Sep}}`))
	var buf bytes.Buffer
	for _, v := range []struct {
		Arr    interface{}
		Sep    string
		expect string
	}{
		{[]int{1, 2, 3}, "&", "1&2&3"},
		{[2]uint{12, 34}, " and ", "12 and 34"},
		{[]string{"alice", "bob", "carol"}, ", ", "alice, bob, carol"},
		{[]string(nil), "|", ""},
		{[]bool{}, " or ", ""},
		{[]interface{}{"1", 2, "three", uint32(4)}, "-", "1-2-three-4"},
		{[]string{"あ", "い", "う", "え", "お"}, "_", "あ_い_う_え_お"},
		{[]string{"a", "b", "c"}, "∧", "a∧b∧c"},
	} {
		buf.Reset()
		if err := tmpl.Execute(&buf, v); err != nil {
			t.Error(err)
			continue
		}
		actual := buf.String()
		expect := v.expect
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`{{join %#v %#v}} => %#v; want %#v`, v.Arr, v.Sep, actual, expect)
		}
	}
}
Ejemplo n.º 6
0
func TestTemplate_FuncMap_in_withInvalidType(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{in 1 1}}`))
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, nil); err == nil {
		t.Errorf("Expect errors, but no errors")
	}
}
Ejemplo n.º 7
0
func BenchmarkNew(b *testing.B) {
	app := kocha.NewTestApp()
	config := app.Config
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if _, err := kocha.New(config); err != nil {
			b.Fatal(err)
		}
	}
}
Ejemplo n.º 8
0
func TestRouter_Reverse_withUnknownRouteName(t *testing.T) {
	app := kocha.NewTestApp()
	name := "unknown"
	_, err := app.Router.Reverse(name)
	actual := err
	expect := fmt.Errorf("kocha: no match route found: %s ()", name)
	if !reflect.DeepEqual(actual, expect) {
		t.Errorf("Router.Reverse(%#v) => (_, %#v); want (_, %#v)", name, actual, expect)
	}
}
Ejemplo n.º 9
0
func TestRouter_Reverse_withFewArguments(t *testing.T) {
	app := kocha.NewTestApp()
	name := "user"
	_, err := app.Router.Reverse(name)
	actual := err
	expect := fmt.Errorf("kocha: too few arguments: %s (controller is %T)", name, &kocha.FixtureUserTestCtrl{})
	if !reflect.DeepEqual(actual, expect) {
		t.Errorf(`Router.Reverse(%#v) => (_, %#v); want (_, %#v)`, name, actual, expect)
	}
}
Ejemplo n.º 10
0
func TestRouter_Reverse_withManyArguments(t *testing.T) {
	app := kocha.NewTestApp()
	name := "user"
	args := []interface{}{77, 100}
	_, err := app.Router.Reverse(name, args...)
	actual := err
	expect := fmt.Errorf("kocha: too many arguments: %s (controller is %T)", name, &kocha.FixtureUserTestCtrl{})
	if !reflect.DeepEqual(actual, expect) {
		t.Errorf(`Router.Reverse(%#v, %#v) => (_, %#v); want (_, %#v)`, name, args, actual, expect)
	}
}
Ejemplo n.º 11
0
func BenchmarkServeHTTP_WithParams(b *testing.B) {
	app := kocha.NewTestApp()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		req, err := http.NewRequest("GET", "/user/123", nil)
		if err != nil {
			b.Fatal(err)
		}
		w := newNullResponseWriter()
		app.ServeHTTP(w, req)
	}
}
Ejemplo n.º 12
0
func TestTemplate_FuncMap_nl2br(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{nl2br "a\nb\nc\n"}}`))
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, nil); err != nil {
		panic(err)
	}
	actual := buf.String()
	expected := "a<br>b<br>c<br>"
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %q, but %q", expected, actual)
	}
}
Ejemplo n.º 13
0
func TestFlashMiddleware(t *testing.T) {
	app := kocha.NewTestApp()
	m := &kocha.FlashMiddleware{}
	c := &kocha.Context{Session: make(kocha.Session)}
	if err := m.Process(app, c, func() error {
		actual := c.Flash.Len()
		expect := 0
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`FlashMiddleware.Process(app, c, func); c.Flash.Len() => %#v; want %#v`, actual, expect)
		}
		c.Flash.Set("test_param", "abc")
		return nil
	}); err != nil {
		t.Error(err)
	}

	c.Flash = nil
	if err := m.Process(app, c, func() error {
		var actual interface{} = c.Flash.Len()
		var expected interface{} = 1
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`FlashMiddleware.Process(app, c, func) then Process(app, c, func); c.Flash.Len() => %#v; want %#v`, actual, expected)
		}
		actual = c.Flash.Get("test_param")
		expected = "abc"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`FlashMiddleware.Process(app, c, func) then Process(app, c, func); c.Flash.Get("test_param") => %#v; want %#v`, actual, expected)
		}
		return nil
	}); err != nil {
		t.Error(err)
	}

	c.Flash = nil
	if err := m.Process(app, c, func() error {
		var actual interface{} = c.Flash.Len()
		var expected interface{} = 0
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`FlashMiddleware.Process(app, c, func) then Process(app, c, func); emulated redirect; c.Flash.Len() => %#v; want %#v`, actual, expected)
		}
		actual = c.Flash.Get("test_param")
		expected = ""
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`FlashMiddleware.Process(app, c, func) then Process(app, c, func); emulated redirect; c.Flash.Get("test_param") => %#v; want %#v`, actual, expected)
		}
		return nil
	}); err != nil {
		t.Error(err)
	}
}
Ejemplo n.º 14
0
func TestFormMiddleware(t *testing.T) {
	doTest := func(body io.Reader, contentType string) {
		app := kocha.NewTestApp()
		r, err := http.NewRequest("POST", "/?q=test&t=jp", body)
		if err != nil {
			t.Fatal(err)
		}
		r.Header.Set("Content-Type", contentType)
		req, res := &kocha.Request{Request: r}, &kocha.Response{ResponseWriter: httptest.NewRecorder()}
		c := &kocha.Context{
			Request:  req,
			Response: res,
		}
		m := &kocha.FormMiddleware{}
		if err := m.Process(app, c, func() error {
			var actual interface{} = c.Params.Encode()
			var expect interface{} = "f=bob&n=alice&q=test&t=jp"
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf(`FormMiddleware.Process(app, c, func); c.Params => %#v; want %#v`, actual, expect)
			}
			return nil
		}); err != nil {
			t.Fatal(err)
		}
	}

	// test with x-www-form-urlencoded
	func() {
		doTest(bytes.NewBufferString("n=alice&f=bob"), "application/x-www-form-urlencoded")
	}()

	// test with multipart/form-data
	func() {
		var body bytes.Buffer
		w := multipart.NewWriter(&body)
		for _, v := range [][2]string{
			{"n", "alice"},
			{"f", "bob"},
		} {
			if err := w.WriteField(v[0], v[1]); err != nil {
				t.Fatal(err)
			}
		}
		w.Close()
		doTest(&body, w.FormDataContentType())
	}()
}
Ejemplo n.º 15
0
func TestTemplate_Get(t *testing.T) {
	app := kocha.NewTestApp()
	func() {
		for _, v := range []struct {
			appName   string
			layout    string
			ctrlrName string
			format    string
		}{
			{"appname", "application", "testctrlr", "html"},
			{"appname", "", "testctrlr", "js"},
			{"appname", "another_layout", "testctrlr", "html"},
		} {
			tmpl, err := app.Template.Get(v.appName, v.layout, v.ctrlrName, v.format)
			var actual interface{} = err
			var expect interface{} = nil
			if !reflect.DeepEqual(actual, expect) {
				t.Fatalf(`Template.Get(%#v, %#v, %#v, %#v) => %T, %#v, want *template.Template, %#v`, v.appName, v.layout, v.ctrlrName, v.format, tmpl, actual, expect)
			}
		}
	}()

	func() {
		for _, v := range []struct {
			appName   string
			layout    string
			ctrlrName string
			format    string
			expectErr error
		}{
			{"unknownAppName", "app", "test_tmpl1", "html", fmt.Errorf("kocha: template not found: unknownAppName:%s", filepath.Join("layout", "app.html"))},
			{"testAppName", "app", "unknown_tmpl1", "html", fmt.Errorf("kocha: template not found: testAppName:%s", filepath.Join("layout", "app.html"))},
			{"testAppName", "app", "test_tmpl1", "xml", fmt.Errorf("kocha: template not found: testAppName:%s", filepath.Join("layout", "app.xml"))},
			{"testAppName", "", "test_tmpl1", "xml", fmt.Errorf("kocha: template not found: testAppName:test_tmpl1.xml")},
		} {
			tmpl, err := app.Template.Get(v.appName, v.layout, v.ctrlrName, v.format)
			actual := tmpl
			expect := (*template.Template)(nil)
			actualErr := err
			expectErr := v.expectErr
			if !reflect.DeepEqual(actual, expect) || !reflect.DeepEqual(actualErr, expectErr) {
				t.Errorf(`Template.Get(%#v, %#v, %#v, %#v) => %#v, %#v, ; want %#v, %#v`, v.appName, v.layout, v.ctrlrName, v.format, actual, actualErr, expect, expectErr)
			}
		}
	}()
}
Ejemplo n.º 16
0
func TestFlashMiddleware_Before_withNilSession(t *testing.T) {
	app := kocha.NewTestApp()
	m := &kocha.FlashMiddleware{}
	c := &kocha.Context{Session: nil}
	err := m.Process(app, c, func() error {
		actual := c.Flash
		expect := kocha.Flash(nil)
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`FlashMiddleware.Process(app, c, func) => %#v; want %#v`, actual, expect)
		}
		return fmt.Errorf("expected error")
	})
	var actual interface{} = err
	var expect interface{} = fmt.Errorf("expected error")
	if !reflect.DeepEqual(actual, expect) {
		t.Errorf(`kocha.FlashMiddleware.Process(app, c, func) => %#v; want %#v`, actual, expect)
	}
	actual = c.Flash
	expect = kocha.Flash(nil)
	if !reflect.DeepEqual(actual, expect) {
		t.Errorf(`FlashMiddleware.Process(app, c, func) => %#v; want %#v`, actual, expect)
	}
}
Ejemplo n.º 17
0
func TestPanicRecoverMiddleware(t *testing.T) {
	test := func(ident string, w *httptest.ResponseRecorder) {
		var actual interface{} = w.Code
		var expect interface{} = http.StatusInternalServerError
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`PanicRecoverMiddleware: %s; status => %#v; want %#v`, ident, actual, expect)
		}

		actual = w.Body.String()
		expect = "This is layout\n500 error\n\n"
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`PanicRecoverMiddleware: %s => %#v; want %#v`, ident, actual, expect)
		}

		actual = w.Header().Get("Content-Type")
		expect = "text/html"
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`PanicRecoverMiddleware: %s; Context-Type => %#v; want %#v`, ident, actual, expect)
		}
	}

	func() {
		req, err := http.NewRequest("GET", "/error", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		app.Config.Middlewares = []kocha.Middleware{
			&kocha.PanicRecoverMiddleware{},
			&kocha.DispatchMiddleware{},
		}
		var buf bytes.Buffer
		app.Logger = log.New(&buf, &log.LTSVFormatter{}, app.Config.Logger.Level)
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
		test(`GET "/error"`, w)

		actual := strings.SplitN(buf.String(), "\n", 2)[0]
		expect := "\tmessage:panic test"
		if !strings.Contains(actual, expect) {
			t.Errorf(`PanicRecoverMiddleware: GET "/error"; log => %#v; want contains => %#v`, actual, expect)
		}
	}()

	func() {
		req, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		app.Config.Middlewares = []kocha.Middleware{
			&kocha.PanicRecoverMiddleware{},
			&TestPanicInBeforeMiddleware{},
			&kocha.DispatchMiddleware{},
		}
		var buf bytes.Buffer
		app.Logger = log.New(&buf, &log.LTSVFormatter{}, app.Config.Logger.Level)
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
		test(`GET "/"`, w)

		actual := strings.SplitN(buf.String(), "\n", 2)[0]
		expect := "\tmessage:before"
		if !strings.Contains(actual, expect) {
			t.Errorf(`PanicRecoverMiddleware: GET "/error"; log => %#v; want contains => %#v`, actual, expect)
		}
	}()

	func() {
		req, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		app.Config.Middlewares = []kocha.Middleware{
			&kocha.PanicRecoverMiddleware{},
			&TestPanicInAfterMiddleware{},
			&kocha.DispatchMiddleware{},
		}
		var buf bytes.Buffer
		app.Logger = log.New(&buf, &log.LTSVFormatter{}, app.Config.Logger.Level)
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
		test(`GET "/"`, w)

		actual := strings.SplitN(buf.String(), "\n", 2)[0]
		expect := "\tmessage:after"
		if !strings.Contains(actual, expect) {
			t.Errorf(`PanicRecoverMiddleware: GET "/error"; log => %#v; want contains => %#v`, actual, expect)
		}
	}()

	func() {
		defer func() {
			actual := recover()
			expect := "before"
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf(`PanicRecoverMiddleware after panic middleware: GET "/" => %#v; want %#v`, actual, expect)
			}
		}()
		req, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		app.Config.Middlewares = []kocha.Middleware{
			&TestPanicInBeforeMiddleware{},
			&kocha.PanicRecoverMiddleware{},
			&kocha.DispatchMiddleware{},
		}
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
	}()

	func() {
		defer func() {
			actual := recover()
			expect := "after"
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf(`PanicRecoverMiddleware after panic middleware: GET "/" => %#v; want %#v`, actual, expect)
			}
		}()
		req, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		app.Config.Middlewares = []kocha.Middleware{
			&TestPanicInAfterMiddleware{},
			&kocha.PanicRecoverMiddleware{},
			&kocha.DispatchMiddleware{},
		}
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
	}()
}
Ejemplo n.º 18
0
func TestSessionMiddleware_Before(t *testing.T) {
	newRequestResponse := func(cookie *http.Cookie) (*kocha.Request, *kocha.Response) {
		r, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		req := &kocha.Request{Request: r}
		if cookie != nil {
			req.AddCookie(cookie)
		}
		res := &kocha.Response{ResponseWriter: httptest.NewRecorder()}
		return req, res
	}

	origNow := util.Now
	util.Now = func() time.Time { return time.Unix(1383820443, 0) }
	defer func() {
		util.Now = origNow
	}()

	// test new session
	func() {
		app := kocha.NewTestApp()
		req, res := newRequestResponse(nil)
		c := &kocha.Context{Request: req, Response: res}
		m := &kocha.SessionMiddleware{Store: &NullSessionStore{}}
		err := m.Process(app, c, func() error {
			actual := c.Session
			expected := make(kocha.Session)
			if !reflect.DeepEqual(actual, expected) {
				t.Errorf("Expect %v, but %v", expected, actual)
			}
			return fmt.Errorf("expected error")
		})
		var actual interface{} = err
		var expect interface{} = fmt.Errorf("expected error")
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`kocha.SessionMiddleware.Process(app, c, func) => %#v; want %#v`, actual, expect)
		}
		actual = c.Session
		expect = make(kocha.Session)
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Expect %v, but %v", expect, actual)
		}
	}()

	// test expires not found
	func() {
		app := kocha.NewTestApp()
		store := kocha.NewTestSessionCookieStore()
		sess := make(kocha.Session)
		value, err := store.Save(sess)
		if err != nil {
			t.Fatal(err)
		}
		m := newTestSessionMiddleware(store)
		cookie := &http.Cookie{
			Name:  m.Name,
			Value: value,
		}
		req, res := newRequestResponse(cookie)
		c := &kocha.Context{Request: req, Response: res}
		err = m.Process(app, c, func() error {
			actual := c.Session
			expected := make(kocha.Session)
			if !reflect.DeepEqual(actual, expected) {
				t.Errorf("Expect %v, but %v", expected, actual)
			}
			return fmt.Errorf("expected error")
		})
		var actual interface{} = err
		var expect interface{} = fmt.Errorf("expected error")
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`kocha.SessionMiddleware.Process(app, c, func) => %#v; want %#v`, actual, expect)
		}
		actual = c.Session
		expect = make(kocha.Session)
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Expect %v, but %v", expect, actual)
		}
	}()

	// test expires invalid time format
	func() {
		app := kocha.NewTestApp()
		store := kocha.NewTestSessionCookieStore()
		m := newTestSessionMiddleware(store)
		sess := make(kocha.Session)
		sess[m.ExpiresKey] = "invalid format"
		value, err := store.Save(sess)
		if err != nil {
			t.Fatal(err)
		}
		cookie := &http.Cookie{
			Name:  m.Name,
			Value: value,
		}
		req, res := newRequestResponse(cookie)
		c := &kocha.Context{Request: req, Response: res}
		err = m.Process(app, c, func() error {
			actual := c.Session
			expect := make(kocha.Session)
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf("Expect %v, but %v", expect, actual)
			}
			return fmt.Errorf("expected error")
		})
		var actual interface{} = err
		var expect interface{} = fmt.Errorf("expected error")
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`kocha.SessionMiddleware.Process(app, c, func) => %#v; want %#v`, actual, expect)
		}
		actual = c.Session
		expect = make(kocha.Session)
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Expect %v, but %v", expect, actual)
		}
	}()

	// test expired
	func() {
		app := kocha.NewTestApp()
		store := kocha.NewTestSessionCookieStore()
		m := newTestSessionMiddleware(store)
		sess := make(kocha.Session)
		sess[m.ExpiresKey] = "1383820442"
		value, err := store.Save(sess)
		if err != nil {
			t.Fatal(err)
		}
		cookie := &http.Cookie{
			Name:  m.Name,
			Value: value,
		}
		req, res := newRequestResponse(cookie)
		c := &kocha.Context{Request: req, Response: res}
		err = m.Process(app, c, func() error {
			actual := c.Session
			expected := make(kocha.Session)
			if !reflect.DeepEqual(actual, expected) {
				t.Errorf("Expect %v, but %v", expected, actual)
			}
			return fmt.Errorf("expected error")
		})
		var actual interface{} = err
		var expect interface{} = fmt.Errorf("expected error")
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`kocha.SessionMiddleware.Process(app, c, func) => %#v; want %#v`, actual, expect)
		}
		actual = c.Session
		expect = make(kocha.Session)
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Expect %v, but %v", expect, actual)
		}
	}()

	func() {
		app := kocha.NewTestApp()
		store := kocha.NewTestSessionCookieStore()
		m := newTestSessionMiddleware(store)
		sess := make(kocha.Session)
		sess[m.ExpiresKey] = "1383820443"
		sess["brown fox"] = "lazy dog"
		value, err := store.Save(sess)
		if err != nil {
			t.Fatal(err)
		}
		cookie := &http.Cookie{
			Name:  m.Name,
			Value: value,
		}
		req, res := newRequestResponse(cookie)
		c := &kocha.Context{Request: req, Response: res}
		err = m.Process(app, c, func() error {
			return fmt.Errorf("expected error")
		})
		var actual interface{} = err
		var expect interface{} = fmt.Errorf("expected error")
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`kocha.SessionMiddlware.Process(app, c, func) => %#v; want %#v`, actual, expect)
		}
		actual = c.Session
		expect = kocha.Session{
			m.ExpiresKey: "1383820443",
			"brown fox":  "lazy dog",
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Expect %v, but %v", expect, actual)
		}
	}()
}
Ejemplo n.º 19
0
func TestApplication_Invoke(t *testing.T) {
	// test that it invokes newFunc when ActiveIf returns true.
	func() {
		app := kocha.NewTestApp()
		unit := &testUnit{"test1", true, 0}
		called := false
		app.Invoke(unit, func() {
			called = true
		}, func() {
			t.Errorf("defaultFunc has been called")
		})
		actual := called
		expected := true
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	// test that it invokes defaultFunc when ActiveIf returns false.
	func() {
		app := kocha.NewTestApp()
		unit := &testUnit{"test2", false, 0}
		called := false
		app.Invoke(unit, func() {
			t.Errorf("newFunc has been called")
		}, func() {
			called = true
		})
		actual := called
		expected := true
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	// test that it invokes defaultFunc when any errors occurred in newFunc.
	func() {
		app := kocha.NewTestApp()
		unit := &testUnit{"test3", true, 0}
		called := false
		app.Invoke(unit, func() {
			panic("expected error")
		}, func() {
			called = true
		})
		actual := called
		expected := true
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	// test that it will be panic when panic occurred in defaultFunc.
	func() {
		defer func() {
			if err := recover(); err == nil {
				t.Errorf("panic doesn't occurred")
			} else if err != "expected error in defaultFunc" {
				t.Errorf("panic doesn't occurred in defaultFunc: %v", err)
			}
		}()
		app := kocha.NewTestApp()
		unit := &testUnit{"test4", false, 0}
		app.Invoke(unit, func() {
			t.Errorf("newFunc has been called")
		}, func() {
			panic("expected error in defaultFunc")
		})
	}()

	// test that it panic when panic occurred in both newFunc and defaultFunc.
	func() {
		defer func() {
			if err := recover(); err == nil {
				t.Errorf("panic doesn't occurred")
			} else if err != "expected error in defaultFunc" {
				t.Errorf("panic doesn't occurred in defaultFunc: %v", err)
			}
		}()
		app := kocha.NewTestApp()
		unit := &testUnit{"test5", true, 0}
		called := false
		app.Invoke(unit, func() {
			called = true
			panic("expected error")
		}, func() {
			panic("expected error in defaultFunc")
		})
		actual := called
		expected := true
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	func() {
		app := kocha.NewTestApp()
		unit := &testUnit{"test6", true, 0}
		app.Invoke(unit, func() {
			panic("expected error")
		}, func() {
			// do nothing.
		})
		var actual interface{} = unit.callCount
		var expected interface{} = 1
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}

		// again.
		app.Invoke(unit, func() {
			t.Errorf("newFunc has been called")
		}, func() {
			// do nothing.
		})
		actual = unit.callCount
		expected = 1
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}

		// same unit type.
		unit = &testUnit{"test7", true, 0}
		called := false
		app.Invoke(unit, func() {
			t.Errorf("newFunc has been called")
		}, func() {
			called = true
		})
		actual = called
		expected = true
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}

		// different unit type.
		unit2 := &testUnit2{}
		called = false
		app.Invoke(unit2, func() {
			called = true
		}, func() {
			t.Errorf("defaultFunc has been called")
		})
		actual = called
		expected = true
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()
}
Ejemplo n.º 20
0
func TestSessionMiddleware_After(t *testing.T) {
	app := kocha.NewTestApp()
	origNow := util.Now
	util.Now = func() time.Time { return time.Unix(1383820443, 0) }
	defer func() {
		util.Now = origNow
	}()
	r, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}
	w := httptest.NewRecorder()
	req, res := &kocha.Request{Request: r}, &kocha.Response{ResponseWriter: w}
	c := &kocha.Context{Request: req, Response: res}
	c.Session = make(kocha.Session)
	m := &kocha.SessionMiddleware{Store: &NullSessionStore{}}
	m.SessionExpires = time.Duration(1) * time.Second
	m.CookieExpires = time.Duration(2) * time.Second
	if err := m.Process(app, c, func() error {
		return nil
	}); err != nil {
		t.Error(err)
	}
	var (
		actual   interface{} = c.Session
		expected interface{} = kocha.Session{
			m.ExpiresKey: "1383820444", // + time.Duration(1) * time.Second
		}
	)
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}

	c.Session[m.ExpiresKey] = "1383820444"
	value, err := m.Store.Save(c.Session)
	if err != nil {
		t.Fatal(err)
	}
	c1 := res.Cookies()[0]
	c2 := &http.Cookie{
		Name:     m.Name,
		Value:    value,
		Path:     "/",
		Expires:  util.Now().UTC().Add(m.CookieExpires),
		MaxAge:   2,
		Secure:   false,
		HttpOnly: m.HttpOnly,
	}
	actual = c1.Name
	expected = c2.Name
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
	actual, err = m.Store.Load(c1.Value)
	if err != nil {
		t.Error(err)
	}
	expected, err = m.Store.Load(c2.Value)
	if err != nil {
		t.Error(err)
	}
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
	actual = c1.Path
	expected = c2.Path
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
	actual = c1.Expires
	expected = c2.Expires
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
	actual = c1.MaxAge
	expected = c2.MaxAge
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
	actual = c1.Secure
	expected = c2.Secure
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
	actual = c1.HttpOnly
	expected = c2.HttpOnly
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
}
Ejemplo n.º 21
0
func TestApplication_ServeHTTP(t *testing.T) {
	for _, v := range []struct {
		uri         string
		status      int
		body        string
		contentType string
	}{
		{"/", http.StatusOK, "This is layout\nThis is root\n\n", "text/html"},
		{"/user/7", http.StatusOK, "This is layout\nThis is user 7\n\n", "text/html"},
		{"/2013/07/19/user/naoina", http.StatusOK, "This is layout\nThis is date naoina: 2013-07-19\n\n", "text/html"},
		{"/missing", http.StatusNotFound, "This is layout\n404 template not found\n\n", "text/html"},
		{"/json", http.StatusOK, "{\n  \"layout\": \"application\",\n  {\"tmpl5\":\"json\"}\n\n}\n", "application/json"},
		{"/teapot", http.StatusTeapot, "This is layout\nI'm a tea pot\n\n", "text/html"},
		{"/panic_in_render", http.StatusInternalServerError, "Internal Server Error\n", "text/plain; charset=utf-8"},
		{"/static/robots.txt", http.StatusOK, "# User-Agent: *\n# Disallow: /\n", "text/plain; charset=utf-8"},
		// This returns 500 Internal Server Error (not 502 BadGateway) because the file 'error/502.html' not found.
		{"/error_controller_test", http.StatusInternalServerError, "Internal Server Error\n", "text/plain; charset=utf-8"},
	} {
		func() {
			defer func() {
				if err := recover(); err != nil {
					t.Errorf(`GET %#v is panicked; want no panic; %v`, v.uri, err)
				}
			}()
			w := httptest.NewRecorder()
			req, err := http.NewRequest("GET", v.uri, nil)
			if err != nil {
				t.Fatal(err)
			}
			app := kocha.NewTestApp()
			app.ServeHTTP(w, req)

			var actual interface{} = w.Code
			var expected interface{} = v.status
			if !reflect.DeepEqual(actual, expected) {
				t.Errorf(`GET %#v status => %#v; want %#v`, v.uri, actual, expected)
			}

			actual = w.Body.String()
			expected = v.body
			if !reflect.DeepEqual(actual, expected) {
				t.Errorf(`GET %#v => %#v; want %#v`, v.uri, actual, expected)
			}

			actual = w.Header().Get("Content-Type")
			expected = v.contentType
			if !reflect.DeepEqual(actual, expected) {
				t.Errorf(`GET %#v Content-Type => %#v; want %#v`, v.uri, actual, expected)
			}
		}()
	}

	// test for panic in handler
	func() {
		defer func() {
			actual := recover()
			expect := "panic test"
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf(`GET /error; recover() => %#v; want %#v`, actual, expect)
			}
		}()
		w := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/error", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		app.ServeHTTP(w, req)
	}()

	// middleware tests
	func() {
		req, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		var called []string
		m1 := &TestMiddleware{t: t, id: "A", called: &called}
		m2 := &TestMiddleware{t: t, id: "B", called: &called}
		app.Config.Middlewares = []kocha.Middleware{m1, m2, &kocha.DispatchMiddleware{}} // all default middlewares are override
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)

		var actual interface{} = called
		var expected interface{} = []string{"beforeA", "beforeB", "afterB", "afterA"}
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`GET "/" with middlewares calls => %#v; want %#v`, actual, expected)
		}

		actual = w.Code
		expected = http.StatusOK
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`GET "/" with middlewares status => %#v; want %#v`, actual, expected)
		}

		actual = w.Body.String()
		expected = "This is layout\nThis is root\n\n"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`GET "/" with middlewares => %#v; want %#v`, actual, expected)
		}

		actual = w.Header().Get("Content-Type")
		expected = "text/html"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf(`GET "/" with middlewares Context-Type => %#v; want %#v`, actual, expected)
		}
	}()

	func() {
		defer func() {
			actual := recover()
			expect := "before"
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf(`GET /; recover() => %#v; want %#v`, actual, expect)
			}
		}()
		req, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		m := &TestPanicInBeforeMiddleware{}
		app.Config.Middlewares = []kocha.Middleware{m, &kocha.DispatchMiddleware{}} // all default middlewares are override
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)
	}()

	func() {
		defer func() {
			actual := recover()
			expect := "after"
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf(`GET /; recover() => %#v; want %#v`, actual, expect)
			}
		}()
		w := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		m := &TestPanicInAfterMiddleware{}
		app.Config.Middlewares = []kocha.Middleware{m, &kocha.DispatchMiddleware{}} // all default middlewares are override
		app.ServeHTTP(w, req)
	}()

	// test for rewrite request url by middleware.
	func() {
		defer func() {
			if err := recover(); err != nil {
				t.Errorf("GET / with TestRewriteURLPathMiddleware has been panicked => %#v; want no panic", err)
			}
		}()
		w := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/error", nil)
		if err != nil {
			t.Fatal(err)
		}
		app := kocha.NewTestApp()
		m := &TestRewriteURLPathMiddleware{rewritePath: "/"}
		app.Config.Middlewares = []kocha.Middleware{m, &kocha.DispatchMiddleware{}}
		app.ServeHTTP(w, req)
		var actual interface{} = w.Code
		var expect interface{} = http.StatusOK
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`GET "/" with TestRewriteURLPathMiddleware status => %#v; want %#v`, actual, expect)
		}

		actual = w.Body.String()
		expect = "This is layout\nThis is root\n\n"
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`GET "/" with TestRewriteURLPathMiddleware => %#v; want %#v`, actual, expect)
		}

		actual = w.Header().Get("Content-Type")
		expect = "text/html"
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`GET "/" with TestRewriteURLPathMiddleware Context-Type => %#v; want %#v`, actual, expect)
		}
	}()
}
Ejemplo n.º 22
0
func TestTemplate_FuncMap_invokeTemplate(t *testing.T) {
	// test that if ActiveIf returns true.
	func() {
		app := kocha.NewTestApp()
		funcMap := template.FuncMap(app.Template.FuncMap)
		c := &kocha.Context{
			Data: map[interface{}]interface{}{
				"unit": &testUnit{"test1", true, 0},
				"ctx":  "testctx1",
			},
		}
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{invoke_template .Data.unit "test_tmpl1" "def_tmpl" $}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); err != nil {
			t.Error(err)
		}
		actual := buf.String()
		expected := "test_tmpl1: testctx1\n"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	// test that if ActiveIf returns false.
	func() {
		app := kocha.NewTestApp()
		funcMap := template.FuncMap(app.Template.FuncMap)
		c := &kocha.Context{
			Data: map[interface{}]interface{}{
				"unit": &testUnit{"test2", false, 0},
				"ctx":  "testctx2",
			},
		}
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{invoke_template .Data.unit "test_tmpl1" "def_tmpl" $}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); err != nil {
			t.Error(err)
		}
		actual := buf.String()
		expected := "def_tmpl: testctx2\n"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	// test that unknown template.
	func() {
		app := kocha.NewTestApp()
		funcMap := template.FuncMap(app.Template.FuncMap)
		c := &kocha.Context{
			Data: map[interface{}]interface{}{
				"unit": &testUnit{"test3", true, 0},
				"ctx":  "testctx3",
			},
		}
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{invoke_template .Data.unit "unknown_tmpl" "def_tmpl" $}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); err != nil {
			t.Error(err)
		}
		actual := buf.String()
		expected := "def_tmpl: testctx3\n"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	// test that unknown templates.
	func() {
		app := kocha.NewTestApp()
		funcMap := template.FuncMap(app.Template.FuncMap)
		c := &kocha.Context{
			Data: map[interface{}]interface{}{
				"unit": &testUnit{"test4", true, 0},
				"ctx":  "testctx4",
			},
		}
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{invoke_template .Data.unit "unknown_tmpl" "unknown_def_tmpl" $}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); !strings.HasSuffix(err.Error(), "template not found: appname:unknown_def_tmpl.html") {
			t.Error(err)
		}
	}()

	// test that unknown default template.
	func() {
		app := kocha.NewTestApp()
		funcMap := template.FuncMap(app.Template.FuncMap)
		c := &kocha.Context{
			Data: map[interface{}]interface{}{
				"unit": &testUnit{"test5", true, 0},
				"ctx":  "testctx5",
			},
		}
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{invoke_template .Data.unit "test_tmpl1" "unknown" $}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); err != nil {
			t.Error(err)
		}
	}()

	// test that single context.
	func() {
		app := kocha.NewTestApp()
		funcMap := template.FuncMap(app.Template.FuncMap)
		c := &kocha.Context{
			Data: map[interface{}]interface{}{
				"unit": &testUnit{"test6", true, 0},
				"ctx":  "testctx6",
			},
		}
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{invoke_template .Data.unit "test_tmpl1" "def_tmpl" $}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); err != nil {
			t.Error(err)
		}
		actual := buf.String()
		expected := "test_tmpl1: testctx6\n"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	// test that too many contexts.
	func() {
		app := kocha.NewTestApp()
		funcMap := template.FuncMap(app.Template.FuncMap)
		c := &kocha.Context{
			Data: map[interface{}]interface{}{
				"unit": &testUnit{"test7", true, 0},
				"ctx":  "testctx7",
			},
		}
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{invoke_template .Data.unit "test_tmpl1" "def_tmpl" $ $}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); !strings.HasSuffix(err.Error(), "number of context must be 0 or 1") {
			t.Error(err)
		}
	}()
}