Skip to content

Commit

Permalink
refactored test server, added func web.NewTestServer()
Browse files Browse the repository at this point in the history
  • Loading branch information
john-deng committed May 6, 2018
1 parent ddd324b commit 1f81bd6
Show file tree
Hide file tree
Showing 10 changed files with 108 additions and 83 deletions.
4 changes: 3 additions & 1 deletion examples/web/helloworld/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ import (
"testing"
"net/http"
"github.com/hidevopsio/hiboot/pkg/starter/web"
"github.com/stretchr/testify/assert"
)

func TestController(t *testing.T) {
e := web.NewApplication(&Controller{}).RunTestServer(t)
e, err := web.NewTestServer(t, &Controller{})
assert.Equal(t, nil, err)

e.Request("GET", "/").
Expect().Status(http.StatusOK)
Expand Down
5 changes: 5 additions & 0 deletions examples/web/jwt/controllers/bar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,13 @@ import (
"testing"
"net/http"
"github.com/hidevopsio/hiboot/pkg/starter/web"
"github.com/hidevopsio/hiboot/pkg/utils"
)

func init() {
utils.ChangeWorkDir("../")
}

func TestBarSayHello(t *testing.T) {
e := web.NewApplication(&BarController{}).RunTestServer(t)

Expand Down
5 changes: 3 additions & 2 deletions examples/web/jwt/controllers/foo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@
// Line 1: main package
package controllers


import (
"testing"
"net/http"
"github.com/hidevopsio/hiboot/pkg/starter/web"
"github.com/stretchr/testify/assert"
)

func TestFooSayHello(t *testing.T) {
e := web.NewApplication(&FooController{}).RunTestServer(t)
e, err := web.NewTestServer(t)
assert.Equal(t, nil, err)

e.Request("GET", "/foo/sayHello").
Expect().Status(http.StatusOK)
Expand Down
1 change: 0 additions & 1 deletion pkg/starter/web/config

This file was deleted.

2 changes: 0 additions & 2 deletions pkg/starter/web/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ func (ctx *Context) ResponseBody(message string, data interface{}) {
Data: data,
}

// just for debug now
ctx.JSON(response)
}

Expand All @@ -110,7 +109,6 @@ func (ctx *Context) ResponseError(message string, code int) {
Message: ctx.translate(message), //TODO: Handle i18n
}

// just for debug now
ctx.StatusCode(code)
ctx.JSON(response)
}
Expand Down
127 changes: 66 additions & 61 deletions pkg/starter/web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,39 +78,6 @@ var (
Controllers []interface{}
)


func (wa *Application) Init() {
log.Println("application init")

wa.workDir = utils.GetWorkingDir("")

log.Println("working dir: ", wa.workDir)

builder := &system.Builder{
Path: filepath.Join(wa.workDir, config),
Name: application,
FileType: yaml,
Profile: os.Getenv("APP_PROFILES_ACTIVE"),
ConfigType: system.Configuration{},
}
cp, err := builder.Build()
if err == nil {
wa.config = cp.(*system.Configuration)
log.SetLevel(wa.config.Logging.Level)
} else {
log.SetLevel(log.DebugLevel)
}


err = InitJwt(wa.workDir)
if err != nil {
wa.jwtEnabled = false
log.Warn(err.Error())
} else {
wa.jwtEnabled = true
}
}

func (wa *Application) Config() *system.Configuration {
return wa.config
}
Expand Down Expand Up @@ -150,10 +117,31 @@ func Add(controller interface{}) {
Controllers = append(Controllers, controller)
}

func newApplication(controllers []interface{}) (*Application, error) {
wa := &Application{}
func (wa *Application) Init(controllers []interface{}) error {

wa.Init()
builder := &system.Builder{
Path: filepath.Join(wa.workDir, config),
Name: application,
FileType: yaml,
Profile: os.Getenv("APP_PROFILES_ACTIVE"),
ConfigType: system.Configuration{},
}
cp, err := builder.Build()
if err == nil {
wa.config = cp.(*system.Configuration)
log.SetLevel(wa.config.Logging.Level)
} else {
log.SetLevel(log.DebugLevel)
}


err = InitJwt(wa.workDir)
if err != nil {
wa.jwtEnabled = false
log.Warn(err.Error())
} else {
wa.jwtEnabled = true
}

wa.app = iris.New()

Expand All @@ -167,7 +155,7 @@ func newApplication(controllers []interface{}) (*Application, error) {
}
})

err := wa.initLocale()
err = wa.initLocale()
if err != nil {
log.Warn(err)
}
Expand All @@ -178,30 +166,30 @@ func newApplication(controllers []interface{}) (*Application, error) {
if len(controllers) == 0 {
controllers = Controllers
if len(controllers) == 0 {
return nil, &system.NotFoundError{Name: "controller"}
return &system.NotFoundError{Name: "controller"}
}
}

if ! wa.jwtEnabled {
err := wa.register(controllers, AuthTypeAnon, AuthTypeDefault, AuthTypeJwt)
if err != nil {
return nil, err
return err
}
} else {
err := wa.register(controllers, AuthTypeAnon, AuthTypeDefault)
if err != nil {
return nil, err
return err
}

wa.app.Use(jwtHandler.Serve)

err = wa.register(controllers, AuthTypeJwt)
if err != nil {
return nil, err
return err
}
}

return wa, nil
return nil
}

func (wa *Application) initLocale() error {
Expand Down Expand Up @@ -241,30 +229,31 @@ func (wa *Application) initLocale() error {
return nil
}

func (wa *Application)register(controllers []interface{}, auths... string) error {
func (wa *Application) register(controllers []interface{}, auths... string) error {
app := wa.app
for _, c := range controllers {
field := reflect.ValueOf(c)

fieldType := field.Type()
log.Debug("fieldType: ", fieldType)
//log.Debug("fieldType: ", fieldType)
fieldName := fieldType.Elem().Name()
log.Debug("fieldName: ", fieldName)
//log.Debug("fieldName: ", fieldName)

controller := field.Interface()
log.Debug("controller: ", controller)
//log.Debug("controller: ", controller)

fieldAuth := field.Elem().FieldByName("AuthType")
fieldValue := field.Elem()
fieldAuth := fieldValue.FieldByName("AuthType")
if ! fieldAuth.IsValid() {
return &system.InvalidControllerError{Name: fieldName}
}
a := fmt.Sprintf("%v", fieldAuth.Interface())
log.Debug("authType: ", a)
//log.Debug("authType: ", a)
if ! utils.StringInSlice(a, auths) {
continue
}

cp := field.Elem().FieldByName("ContextMapping")
cp := fieldValue.FieldByName("ContextMapping")
if ! cp.IsValid() {
return &system.InvalidControllerError{Name: fieldName}
}
Expand All @@ -276,19 +265,19 @@ func (wa *Application)register(controllers []interface{}, auths... string) error
controllerName = strings.Replace(fieldName, fieldNames[len(fieldNames)-1], "", 1)
controllerName = utils.LowerFirst(controllerName)
}
log.Debug("controllerName: ", controllerName)
//log.Debug("controllerName: ", controllerName)
if contextMapping == "" {
contextMapping = pathSep + controllerName
}

numOfMethod := field.NumMethod()
log.Debug("methods: ", numOfMethod)
//log.Debug("methods: ", numOfMethod)

beforeMethod, ok := fieldType.MethodByName("Before")
var party iris.Party
if ok {
log.Debug("contextPath: ", contextMapping)
log.Debug("beforeMethod.Name: ", beforeMethod.Name)
//log.Debug("contextPath: ", contextMapping)
//log.Debug("beforeMethod.Name: ", beforeMethod.Name)
party = app.Party(contextMapping, func(ctx context.Context) {
wa.handle(beforeMethod, controller, ctx.(*Context))
})
Expand All @@ -297,7 +286,7 @@ func (wa *Application)register(controllers []interface{}, auths... string) error
for mi := 0; mi < numOfMethod; mi++ {
method := fieldType.Method(mi)
methodName := method.Name
log.Debug("method: ", methodName)
//log.Debug("method: ", methodName)

ctxMap := camelcase.Split(methodName)
httpMethod := strings.ToUpper(ctxMap[0])
Expand All @@ -306,12 +295,12 @@ func (wa *Application)register(controllers []interface{}, auths... string) error

if party == nil {
relativePath := filepath.Join(contextMapping, apiContextMapping)
log.Debug("relativePath: ", relativePath)
//log.Debug("relativePath: ", relativePath)
app.Handle(httpMethod, relativePath, func(ctx context.Context) {
wa.handle(method, controller, ctx.(*Context))
})
} else {
log.Debug("contextMapping: ", apiContextMapping)
//log.Debug("contextMapping: ", apiContextMapping)
party.Handle(httpMethod, apiContextMapping, func(ctx context.Context) {
wa.handle(method, controller, ctx.(*Context))
})
Expand All @@ -324,15 +313,31 @@ func (wa *Application)register(controllers []interface{}, auths... string) error
}


func createApplication(controllers []interface{}) (*Application, error) {
wa := &Application{}
wa.workDir = utils.GetWorkDir()
err := wa.Init(controllers)
log.Debugf("workdir: %v", wa.workDir)
return wa, err
}

func NewApplication(controllers ... interface{}) *Application {

wa, err := newApplication(controllers)
func NewApplication(controllers... interface{}) *Application {
wa, err := createApplication(controllers)
if err != nil {

log.Error(err)
os.Exit(1)
}

return wa
}
}

func NewTestServer(t *testing.T, controllers... interface{}) (*httpexpect.Expect, error) {
log.SetLevel(log.DebugLevel)

wa, err := createApplication(controllers)

e := wa.RunTestServer(t)

return e, err
}

27 changes: 17 additions & 10 deletions pkg/starter/web/web_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"time"
"github.com/hidevopsio/hiboot/pkg/system"
"github.com/stretchr/testify/assert"
"github.com/hidevopsio/hiboot/pkg/utils"
)

type UserRequest struct {
Expand Down Expand Up @@ -51,6 +52,10 @@ type BarController struct{

type InvalidController struct {}

func init() {
utils.ChangeWorkDir("../../../")
}

func (c *FooController) Before(ctx *Context) {
log.Debug("FooController.Before")

Expand Down Expand Up @@ -111,26 +116,28 @@ func (c *HelloController) Get(ctx *Context) {

func TestHelloWorld(t *testing.T) {

// create new web application
e := NewApplication(&HelloController{Controller{ContextMapping: "/"}}).RunTestServer(t)
// create new test server
e, err := NewTestServer(t, &HelloController{Controller{ContextMapping: "/"}})
assert.Equal(t, nil, err)

// run the application
e.Request("GET", "/").
Expect().Status(http.StatusOK).Body().Contains("Success")
}

func TestHelloWorldLocale(t *testing.T) {
// create new test server
e, err := NewTestServer(t, &HelloController{Controller{ContextMapping: "/"}})
assert.Equal(t, nil, err)

e := NewApplication(&HelloController{Controller{ContextMapping: "/"}}).RunTestServer(t)

// cn-ZH
// test cn-ZH
e.Request("GET", "/").
WithHeader("Accept-Language", "cn-ZH").
Expect().
Status(http.StatusOK).
Body().Contains("成功")

// en-US
// test en-US
e.Request("GET", "/").
WithHeader("Accept-Language", "en-US").
Expect().
Expand All @@ -140,10 +147,11 @@ func TestHelloWorldLocale(t *testing.T) {

func TestWebApplication(t *testing.T) {

e := NewApplication(
e, err := NewTestServer(t,
&FooController{},
&BarController{Controller{AuthType: AuthTypeJwt}},
).RunTestServer(t)
)
assert.Equal(t, nil, err)

e.Request("POST", "/foo/login").WithJSON(&UserRequest{Username: "johndoe", Password: "iHop91#15"}).
Expect().Status(http.StatusOK).Body().Contains("Success")
Expand All @@ -158,8 +166,7 @@ func TestWebApplication(t *testing.T) {

func TestInvalidController(t *testing.T) {

controllers := []interface{}{&InvalidController{}}
_, err := newApplication(controllers)
_, err := NewTestServer(t, &InvalidController{})
err, ok := err.(*system.InvalidControllerError)
assert.Equal(t, ok, true)
}
Loading

0 comments on commit 1f81bd6

Please sign in to comment.