add a test and fix a small issue on the macro/handler#MakeHandler

Former-commit-id: 0bb24999fbd3f54e582fb9a86f55333facfbc338
This commit is contained in:
Gerasimos (Makis) Maropoulos 2018-09-29 19:32:32 +03:00
parent 7568da3283
commit 4431a65a56
2 changed files with 47 additions and 7 deletions

View File

@ -11,10 +11,9 @@ import (
// If the template does not contain any dynamic attributes and a special handler is NOT required // If the template does not contain any dynamic attributes and a special handler is NOT required
// then it returns a nil handler and false as its second output value, // then it returns a nil handler and false as its second output value,
// the caller should check those two values before any further action. // the caller should check those two values before any further action.
func MakeHandler(tmpl *macro.Template) (context.Handler, bool) { func MakeHandler(tmpl *macro.Template) (handler context.Handler, needsMacroHandler bool) {
needsMacroHandler := len(tmpl.Params) > 0 if len(tmpl.Params) == 0 {
if !needsMacroHandler { return
return nil, false
} }
// check if we have params like: {name:string} or {name} or {anything:path} without else keyword or any functions used inside these params. // check if we have params like: {name:string} or {name} or {anything:path} without else keyword or any functions used inside these params.
@ -29,10 +28,10 @@ func MakeHandler(tmpl *macro.Template) (context.Handler, bool) {
} }
if !needsMacroHandler { if !needsMacroHandler {
return nil, false return
} }
handler := func(ctx context.Context) { handler = func(ctx context.Context) {
for _, p := range tmpl.Params { for _, p := range tmpl.Params {
if !p.CanEval() { if !p.CanEval() {
continue // allow. continue // allow.
@ -48,5 +47,5 @@ func MakeHandler(tmpl *macro.Template) (context.Handler, bool) {
ctx.Next() ctx.Next()
} }
return handler, true return
} }

View File

@ -0,0 +1,41 @@
package handler
import (
"testing"
"github.com/kataras/iris/macro"
)
func TestMakeHandlerNeeds(t *testing.T) {
tests := []struct {
src string
needsHandler bool
}{
{"/static/static", false},
{"/{myparam}", false},
{"/{myparam min(1)}", true},
{"/{myparam else 500}", true},
{"/{myparam else 404}", false},
{"/{myparam:string}/static", false},
{"/{myparam:int}", true},
{"/static/{myparam:int}/static", true},
{"/{myparam:path}", false},
{"/{myparam:path min(1) else 404}", true},
}
availableMacros := *macro.Defaults
for i, tt := range tests {
tmpl, err := macro.Parse(tt.src, availableMacros)
if err != nil {
t.Fatalf("[%d] '%s' failed to be parsed: %v", i, tt.src, err)
}
if _, got := MakeHandler(tmpl); got != tt.needsHandler {
if tt.needsHandler {
t.Fatalf("[%d] '%s' expected to be able to generate an evaluator handler instead of a nil one", i, tt.src)
} else {
t.Fatalf("[%d] '%s' should not need an evaluator handler", i, tt.src)
}
}
}
}