Skip to content

Commit 0bb55b6

Browse files
committed
#157 test case updates
1 parent 4d67c44 commit 0bb55b6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+2950
-2718
lines changed

aah_test.go

+503-165
Large diffs are not rendered by default.

access_log_test.go

+11-122
Original file line numberDiff line numberDiff line change
@@ -6,137 +6,26 @@ package aah
66

77
import (
88
"fmt"
9-
"net/http"
10-
"net/http/httptest"
119
"path/filepath"
1210
"testing"
13-
"time"
1411

15-
"aahframework.org/ahttp.v0"
1612
"aahframework.org/config.v0"
1713
"aahframework.org/essentials.v0"
1814
"aahframework.org/test.v0/assert"
1915
)
2016

21-
func TestAccessLogFormatter(t *testing.T) {
22-
al := createTestAccessLog()
17+
func TestAccessLogInitAbsPath(t *testing.T) {
18+
logPath := filepath.Join(testdataBaseDir(), "sample-test-access.log")
19+
defer ess.DeleteFiles(logPath)
2320

24-
// Since we are not bootstrapping the framework's engine,
25-
// We need to manually set this
26-
al.Request.Path = "/oops"
27-
al.Request.Header.Set(ahttp.HeaderXRequestID, "5946ed129bf23409520736de")
28-
29-
// Testing for the default access log pattern first
30-
expectedDefaultFormat := fmt.Sprintf("%v - %v %v %v %v %v %v %v %v",
31-
"[::1]", al.StartTime.Format(time.RFC3339),
32-
al.Request.Method, al.Request.Path, al.Request.Raw.Proto, al.ResStatus,
33-
al.ResBytes, fmt.Sprintf("%.4f", al.ElapsedDuration.Seconds()*1e3), "-")
34-
35-
testFormatter(t, al, appDefaultAccessLogPattern, expectedDefaultFormat)
36-
37-
// Testing custom access log pattern
38-
al = createTestAccessLog()
39-
al.ResHdr.Add("content-type", "application/json")
40-
pattern := "%reqtime:2016-05-16 %reqhdr %querystr %reshdr:content-type"
41-
expected := fmt.Sprintf(`%s %s "%s" "%s"`, al.StartTime.Format("2016-05-16"), "-", "me=human", al.ResHdr.Get("Content-Type"))
42-
43-
testFormatter(t, al, pattern, expected)
44-
45-
// Testing all available access log pattern
46-
al = createTestAccessLog()
47-
al.Request.Header = al.Request.Raw.Header
48-
al.Request.Header.Add(ahttp.HeaderAccept, "text/html")
49-
al.Request.Header.Set(ahttp.HeaderXRequestID, "5946ed129bf23409520736de")
50-
al.RequestID = "5946ed129bf23409520736de"
51-
al.Request.ClientIP = "127.0.0.1"
52-
al.ResHdr.Add("content-type", "application/json")
53-
allAvailablePatterns := "%clientip %reqid %reqtime %restime %resstatus %ressize %reqmethod %requrl %reqhdr:accept %querystr %reshdr"
54-
expectedForAllAvailablePatterns := fmt.Sprintf(`%s %s %s %v %d %d %s %s "%s" "%s" %s`,
55-
al.Request.ClientIP, al.Request.Header.Get(ahttp.HeaderXRequestID),
56-
al.StartTime.Format(time.RFC3339), fmt.Sprintf("%.4f", al.ElapsedDuration.Seconds()*1e3),
57-
al.ResStatus, al.ResBytes, al.Request.Method,
58-
al.Request.Path, "text/html", "me=human", "-")
59-
60-
testFormatter(t, al, allAvailablePatterns, expectedForAllAvailablePatterns)
61-
}
62-
63-
func TestAccessLogFormatterInvalidPattern(t *testing.T) {
64-
_, err := ess.ParseFmtFlag("%oops", accessLogFmtFlags)
65-
66-
assert.NotNil(t, err)
67-
}
68-
69-
func TestAccessLogInitDefault(t *testing.T) {
70-
testAccessInit(t, `
71-
server {
72-
access_log {
73-
# Default value is false
74-
enable = true
75-
}
76-
}
77-
`)
78-
79-
testAccessInit(t, `
80-
server {
81-
access_log {
82-
# Default value is false
83-
enable = true
84-
85-
file = "testdata/test-access.log"
86-
}
87-
}
88-
`)
89-
90-
testAccessInit(t, `
91-
server {
92-
access_log {
93-
# Default value is false
94-
enable = true
95-
96-
file = "/tmp/test-access.log"
97-
}
98-
}
99-
`)
100-
}
101-
102-
func testFormatter(t *testing.T, al *accessLog, pattern, expected string) {
103-
var err error
104-
appAccessLogFmtFlags, err = ess.ParseFmtFlag(pattern, accessLogFmtFlags)
21+
a := newApp()
22+
cfg, _ := config.ParseString(fmt.Sprintf(`server {
23+
access_log {
24+
file = "%s"
25+
}
26+
}`, logPath))
27+
a.cfg = cfg
10528

29+
err := a.initAccessLog()
10630
assert.Nil(t, err)
107-
assert.Equal(t, expected, accessLogFormatter(al))
108-
}
109-
110-
func testAccessInit(t *testing.T, cfgStr string) {
111-
buildTime := time.Now().Format(time.RFC3339)
112-
SetAppBuildInfo(&BuildInfo{
113-
BinaryName: "testapp",
114-
Date: buildTime,
115-
Version: "1.0.0",
116-
})
117-
118-
cfg, _ := config.ParseString(cfgStr)
119-
logsDir := filepath.Join(getTestdataPath(), appLogsDir())
120-
err := initAccessLog(logsDir, cfg)
121-
122-
assert.Nil(t, err)
123-
assert.NotNil(t, appAccessLog)
124-
}
125-
126-
func createTestAccessLog() *accessLog {
127-
startTime := time.Now()
128-
req := httptest.NewRequest("GET", "/oops?me=human", nil)
129-
req.Header = http.Header{}
130-
131-
w := httptest.NewRecorder()
132-
133-
al := acquireAccessLog()
134-
al.StartTime = startTime
135-
al.ElapsedDuration = time.Now().Add(2 * time.Second).Sub(startTime)
136-
al.Request = &ahttp.Request{Raw: req, Header: req.Header, ClientIP: "[::1]"}
137-
al.ResStatus = 200
138-
al.ResBytes = 63
139-
al.ResHdr = w.HeaderMap
140-
141-
return al
14231
}

bind_test.go

+51-154
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package aah
66

77
import (
8+
"io/ioutil"
89
"net/http"
910
"net/http/httptest"
1011
"net/url"
@@ -16,173 +17,46 @@ import (
1617
"aahframework.org/ahttp.v0"
1718
"aahframework.org/config.v0"
1819
"aahframework.org/essentials.v0"
19-
"aahframework.org/i18n.v0"
20-
"aahframework.org/router.v0"
21-
"aahframework.org/security.v0"
20+
"aahframework.org/log.v0"
2221
"aahframework.org/test.v0/assert"
2322
)
2423

25-
func TestBindParamTemplateFuncs(t *testing.T) {
26-
form := url.Values{}
27-
form.Add("names", "Test1")
28-
form.Add("names", "Test 2 value")
29-
form.Add("username", "welcome")
30-
form.Add("email", "[email protected]")
31-
req1, _ := http.NewRequest("POST", "http://localhost:8080/user/registration?_ref=true&locale=en-CA", strings.NewReader(form.Encode()))
32-
req1.Header.Add(ahttp.HeaderContentType, ahttp.ContentTypeForm.Raw())
33-
_ = req1.ParseForm()
34-
35-
aahReq1 := ahttp.ParseRequest(req1, &ahttp.Request{})
36-
aahReq1.Params.Form = req1.Form
37-
aahReq1.Params.Path = make(map[string]string)
38-
aahReq1.Params.Path["userId"] = "100001"
39-
40-
viewArgs := map[string]interface{}{}
41-
viewArgs[KeyViewArgRequestParams] = aahReq1.Params
42-
43-
v1 := tmplQueryParam(viewArgs, "_ref")
44-
assert.Equal(t, "true", v1)
45-
46-
v2 := tmplFormParam(viewArgs, "email")
47-
assert.Equal(t, "[email protected]", v2)
48-
49-
v3 := tmplPathParam(viewArgs, "userId")
50-
assert.Equal(t, "100001", v3)
51-
}
52-
53-
func TestBindParse(t *testing.T) {
54-
defer ess.DeleteFiles("testapp.pid")
55-
requestParsers[ahttp.ContentTypeMultipartForm.Mime] = multipartFormParser
56-
requestParsers[ahttp.ContentTypeForm.Mime] = formParser
57-
58-
// Request Query String
59-
r1 := httptest.NewRequest("GET", "http://localhost:8080/index.html?lang=en-CA", nil)
60-
ctx1 := &Context{
61-
Req: ahttp.AcquireRequest(r1),
62-
Res: ahttp.AcquireResponseWriter(httptest.NewRecorder()),
63-
subject: security.AcquireSubject(),
64-
route: &router.Route{MaxBodySize: 5 << 20},
65-
values: make(map[string]interface{}),
66-
viewArgs: make(map[string]interface{}),
67-
}
68-
69-
appI18n = i18n.New()
70-
71-
assert.Nil(t, ctx1.Req.Locale)
72-
BindMiddleware(ctx1, &Middleware{})
73-
assert.NotNil(t, ctx1.Req.Locale)
74-
assert.Equal(t, "en", ctx1.Req.Locale.Language)
75-
assert.Equal(t, "CA", ctx1.Req.Locale.Region)
76-
assert.Equal(t, "en-CA", ctx1.Req.Locale.String())
77-
78-
// Request Form Values
79-
form := url.Values{}
80-
form.Add("names", "Test1")
81-
form.Add("names", "Test 2 value")
82-
form.Add("username", "welcome")
83-
form.Add("email", "[email protected]")
84-
r2, _ := http.NewRequest("POST", "http://localhost:8080/user/registration", strings.NewReader(form.Encode()))
85-
r2.Header.Set(ahttp.HeaderContentType, ahttp.ContentTypeForm.String())
86-
ctx2 := &Context{
87-
Req: ahttp.AcquireRequest(r2),
88-
Res: ahttp.AcquireResponseWriter(httptest.NewRecorder()),
89-
subject: security.AcquireSubject(),
90-
values: make(map[string]interface{}),
91-
viewArgs: make(map[string]interface{}),
92-
route: &router.Route{MaxBodySize: 5 << 20},
93-
}
94-
95-
BindMiddleware(ctx2, &Middleware{})
96-
assert.NotNil(t, ctx2.Req.Params.Form)
97-
assert.True(t, len(ctx2.Req.Params.Form) == 3)
98-
99-
// Request Form Multipart
100-
r3, _ := http.NewRequest("POST", "http://localhost:8080/user/registration", strings.NewReader(form.Encode()))
101-
r3.Header.Set(ahttp.HeaderContentType, ahttp.ContentTypeMultipartForm.String())
102-
ctx3 := &Context{
103-
Req: ahttp.AcquireRequest(r3),
104-
subject: security.AcquireSubject(),
105-
values: make(map[string]interface{}),
106-
viewArgs: make(map[string]interface{}),
107-
route: &router.Route{MaxBodySize: 5 << 20},
108-
}
109-
BindMiddleware(ctx3, &Middleware{})
110-
assert.Nil(t, ctx3.Req.Params.Form)
111-
assert.False(t, len(ctx3.Req.Params.Form) == 3)
112-
}
113-
114-
func TestBindParamParseLocaleFromAppConfiguration(t *testing.T) {
24+
func TestBindParamContentNegotiation(t *testing.T) {
11525
defer ess.DeleteFiles("testapp.pid")
11626

117-
cfg, err := config.ParseString(`
118-
i18n {
119-
param_name {
120-
query = "language"
121-
}
122-
}
123-
`)
124-
appConfig = cfg
125-
bindInitialize(&Event{})
126-
27+
a := newApp()
28+
cfg, _ := config.ParseString(`request {
29+
content_negotiation {
30+
enable = true
31+
accepted = ["application/json"]
32+
offered = ["application/json"]
33+
}
34+
}`)
35+
a.cfg = cfg
36+
err := a.initLog()
12737
assert.Nil(t, err)
12838

129-
r := httptest.NewRequest("GET", "http://localhost:8080/index.html?language=en-CA", nil)
130-
ctx1 := &Context{
131-
Req: ahttp.AcquireRequest(r),
132-
viewArgs: make(map[string]interface{}),
133-
values: make(map[string]interface{}),
134-
}
135-
136-
assert.Nil(t, ctx1.Req.Locale)
137-
BindMiddleware(ctx1, &Middleware{})
138-
assert.NotNil(t, ctx1.Req.Locale)
139-
assert.Equal(t, "en", ctx1.Req.Locale.Language)
140-
assert.Equal(t, "CA", ctx1.Req.Locale.Region)
141-
assert.Equal(t, "en-CA", ctx1.Req.Locale.String())
142-
}
143-
144-
func TestBindParamContentNegotiation(t *testing.T) {
145-
defer ess.DeleteFiles("testapp.pid")
39+
err = a.initBind()
40+
assert.Nil(t, err)
14641

147-
errorHandlerFunc = defaultErrorHandlerFunc
148-
isContentNegotiationEnabled = true
42+
a.Log().(*log.Logger).SetWriter(ioutil.Discard)
14943

15044
// Accepted
151-
acceptedContentTypes = []string{"application/json"}
15245
r1 := httptest.NewRequest("POST", "http://localhost:8080/v1/userinfo", nil)
15346
r1.Header.Set(ahttp.HeaderContentType, "application/xml")
154-
ctx1 := &Context{
155-
Req: ahttp.AcquireRequest(r1),
156-
reply: acquireReply(),
157-
subject: security.AcquireSubject(),
158-
}
47+
ctx1 := newContext(nil, r1)
48+
ctx1.a = a
15949
BindMiddleware(ctx1, &Middleware{})
16050
assert.Equal(t, http.StatusUnsupportedMediaType, ctx1.Reply().err.Code)
16151

16252
// Offered
163-
offeredContentTypes = []string{"application/json"}
16453
r2 := httptest.NewRequest("POST", "http://localhost:8080/v1/userinfo", nil)
16554
r2.Header.Set(ahttp.HeaderContentType, "application/json")
16655
r2.Header.Set(ahttp.HeaderAccept, "application/xml")
167-
ctx2 := &Context{
168-
Req: ahttp.AcquireRequest(r2),
169-
reply: acquireReply(),
170-
subject: security.AcquireSubject(),
171-
}
56+
ctx2 := newContext(nil, r2)
57+
ctx2.a = a
17258
BindMiddleware(ctx2, &Middleware{})
17359
assert.Equal(t, http.StatusNotAcceptable, ctx2.Reply().err.Code)
174-
175-
isContentNegotiationEnabled = false
176-
177-
appConfig, _ = config.ParseString(`
178-
request {
179-
content_negotiation {
180-
accepted = ["*/*"]
181-
offered = ["*/*"]
182-
}
183-
}`)
184-
bindInitialize(&Event{})
185-
appConfig = nil
18660
}
18761

18862
func TestBindAddValueParser(t *testing.T) {
@@ -193,14 +67,6 @@ func TestBindAddValueParser(t *testing.T) {
19367
assert.Equal(t, "valpar: value parser is already exists", err.Error())
19468
}
19569

196-
func TestBindFormBodyNil(t *testing.T) {
197-
// Request Body is nil
198-
r1, _ := http.NewRequest("POST", "http://localhost:8080/user/registration", nil)
199-
ctx1 := &Context{Req: ahttp.AcquireRequest(r1), subject: security.AcquireSubject()}
200-
result := formParser(ctx1)
201-
assert.Equal(t, flowCont, result)
202-
}
203-
20470
func TestBindValidatorWithValue(t *testing.T) {
20571
assert.NotNil(t, Validator())
20672

@@ -230,3 +96,34 @@ func TestBindValidatorWithValue(t *testing.T) {
23096
result = ValidateValue(numbers, "unique")
23197
assert.True(t, result)
23298
}
99+
100+
func TestBindParamTemplateFuncs(t *testing.T) {
101+
a := newApp()
102+
a.viewMgr = &viewManager{a: a}
103+
104+
form := url.Values{}
105+
form.Add("names", "Test1")
106+
form.Add("names", "Test 2 value")
107+
form.Add("username", "welcome")
108+
form.Add("email", "[email protected]")
109+
req1, _ := http.NewRequest("POST", "http://localhost:8080/user/registration?_ref=true&locale=en-CA", strings.NewReader(form.Encode()))
110+
req1.Header.Add(ahttp.HeaderContentType, ahttp.ContentTypeForm.Raw())
111+
_ = req1.ParseForm()
112+
113+
aahReq1 := ahttp.ParseRequest(req1, &ahttp.Request{})
114+
aahReq1.Params.Form = req1.Form
115+
aahReq1.Params.Path = make(map[string]string)
116+
aahReq1.Params.Path["userId"] = "100001"
117+
118+
viewArgs := map[string]interface{}{}
119+
viewArgs[KeyViewArgRequestParams] = aahReq1.Params
120+
121+
v1 := a.viewMgr.tmplQueryParam(viewArgs, "_ref")
122+
assert.Equal(t, "true", v1)
123+
124+
v2 := a.viewMgr.tmplFormParam(viewArgs, "email")
125+
assert.Equal(t, "[email protected]", v2)
126+
127+
v3 := a.viewMgr.tmplPathParam(viewArgs, "userId")
128+
assert.Equal(t, "100001", v3)
129+
}

0 commit comments

Comments
 (0)