forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 55
/
validation_test.go
76 lines (67 loc) · 2.15 KB
/
validation_test.go
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
package revel
import (
"net/http"
"net/http/httptest"
"testing"
)
// getRecordedCookie returns the recorded cookie from a ResponseRecorder with
// the given name. It utilizes the cookie reader found in the standard library.
func getRecordedCookie(recorder *httptest.ResponseRecorder, name string) (*http.Cookie, error) {
r := &http.Response{Header: recorder.HeaderMap}
for _, cookie := range r.Cookies() {
if cookie.Name == name {
return cookie, nil
}
}
return nil, http.ErrNoCookie
}
func validationTester(req *Request, fn func(c *Controller)) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
c := NewController(req, NewResponse(recorder))
ValidationFilter(c, []Filter{func(c *Controller, _ []Filter) {
fn(c)
}})
return recorder
}
// Test that errors are encoded into the _ERRORS cookie.
func TestValidationWithError(t *testing.T) {
recorder := validationTester(buildEmptyRequest(), func(c *Controller) {
c.Validation.Required("")
if !c.Validation.HasErrors() {
t.Fatal("errors should be present")
}
c.Validation.Keep()
})
if cookie, err := getRecordedCookie(recorder, "REVEL_ERRORS"); err != nil {
t.Fatal(err)
} else if cookie.MaxAge < 0 {
t.Fatalf("cookie should not expire")
}
}
// Test that no cookie is sent if errors are found, but Keep() is not called.
func TestValidationNoKeep(t *testing.T) {
recorder := validationTester(buildEmptyRequest(), func(c *Controller) {
c.Validation.Required("")
if !c.Validation.HasErrors() {
t.Fatal("errors should not be present")
}
})
if _, err := getRecordedCookie(recorder, "REVEL_ERRORS"); err != http.ErrNoCookie {
t.Fatal(err)
}
}
// Test that a previously set _ERRORS cookie is deleted if no errors are found.
func TestValidationNoKeepCookiePreviouslySet(t *testing.T) {
req := buildRequestWithCookie("REVEL_ERRORS", "invalid")
recorder := validationTester(req, func(c *Controller) {
c.Validation.Required("success")
if c.Validation.HasErrors() {
t.Fatal("errors should not be present")
}
})
if cookie, err := getRecordedCookie(recorder, "REVEL_ERRORS"); err != nil {
t.Fatal(err)
} else if cookie.MaxAge >= 0 {
t.Fatalf("cookie should be deleted")
}
}