Skip to content

Commit

Permalink
优化单元测试结构
Browse files Browse the repository at this point in the history
  • Loading branch information
gphper committed Sep 5, 2023
1 parent 6667ea8 commit 023e1b8
Show file tree
Hide file tree
Showing 7 changed files with 309 additions and 95 deletions.
Expand Up @@ -3,7 +3,7 @@
* @Author: gphper
* @Date: 2022-03-31 19:59:19
*/
package test
package setting

import (
"log"
Expand All @@ -12,10 +12,11 @@ import (
"testing"

"github.com/gphper/ginadmin/configs"
"github.com/gphper/ginadmin/internal/router"
"github.com/gphper/ginadmin/internal/controllers/admin"
"github.com/gphper/ginadmin/pkg/mysqlx"
"github.com/gphper/ginadmin/pkg/redisx"
"github.com/gphper/ginadmin/pkg/utils/httptestutil"
"github.com/gphper/ginadmin/pkg/utils/httptestutil/router"
"github.com/gphper/ginadmin/web"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
Expand All @@ -34,6 +35,9 @@ func (suite *AdminTestSuite) SetupSuite() {
log.Fatalf("router init fail: %s", err)
}

router.SetAdminRoute("/admin", admin.NewLoginController())
router.SetAdminRoute("/admin/setting/admingroup", NewAdminGroupController())

suite.router = router
}

Expand Down
155 changes: 155 additions & 0 deletions internal/controllers/api/user/userController_test.go
@@ -0,0 +1,155 @@
/*
* @Description:
* @Author: gphper
* @Date: 2022-04-03 10:16:52
*/
package user

import (
"bytes"
"encoding/json"
"log"
"net/url"
"testing"

"github.com/gphper/ginadmin/configs"
"github.com/gphper/ginadmin/internal/dao"
"github.com/gphper/ginadmin/internal/models"
"github.com/gphper/ginadmin/pkg/mysqlx"
"github.com/gphper/ginadmin/pkg/redisx"
"github.com/gphper/ginadmin/pkg/utils/httptestutil"
"github.com/gphper/ginadmin/pkg/utils/httptestutil/router"
"github.com/gphper/ginadmin/web"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)

// api UserController 相关接口测试
type ApiTestSuite struct {
suite.Suite
router *router.Router
jtoken string
}

func (suite *ApiTestSuite) SetupSuite() {

router, err := router.Init()
if err != nil {
log.Fatalf("router init fail: %s", err)
}

router.SetApiRoute("/api/user", NewUserController())

suite.router = router
}

// 注册接口测试
func (suite *ApiTestSuite) TestARegister() {

option := httptestutil.OptionValue{
Param: url.Values{
"nickname": {"gphper"},
"password": {"111111"},
"confirm_password": {"111111"},
"email": {"570165887@qq.com"},
},
}
// 发起post请求,以表单形式传递参数
body, _ := httptestutil.PostForm("/api/user/register", suite.router, option)
assert.JSONEq(suite.T(), `{"code":200,"msg":"success","data":{}}`, string(body))
}

func (suite *ApiTestSuite) TestARegisterErr() {

option := httptestutil.OptionValue{
Param: url.Values{
"nickname": {"gphper"},
"password": {"111111"},
"confirm_password": {"111111"},
"email": {"570165887@qq.com"},
},
}
// 发起post请求,以表单形式传递参数
body, _ := httptestutil.PostForm("/api/user/register", suite.router, option)
assert.JSONEq(suite.T(), `{"code":2000, "msg":"该邮箱已存在"}`, string(body))
}

func (suite *ApiTestSuite) TestARegisterBindErr() {

option := httptestutil.OptionValue{
Param: url.Values{
"nickname": {"gphper"},
},
}
// 发起post请求,以表单形式传递参数
body, _ := httptestutil.PostForm("/api/user/register", suite.router, option)
assert.JSONEq(suite.T(), `{"code":2001, "msg":"绑定参数出错"}`, string(body))
}

// 登录接口测试
func (suite *ApiTestSuite) TestBLogin() {

type (
Data struct {
Jtoken string
Retoken string
}

response struct {
Code int
Msg string
Data Data
}
)

var resp response

option := httptestutil.OptionValue{
Param: url.Values{
"password": {"111111"},
"email": {"570165887@qq.com"},
},
}

body, _ := httptestutil.PostForm("/api/user/login", suite.router, option)
assert.Contains(suite.T(), string(body), "jtoken")

decode := json.NewDecoder(bytes.NewReader(body))
if err := decode.Decode(&resp); err != nil {
assert.FailNow(suite.T(), err.Error())
}

suite.jtoken = resp.Data.Jtoken
}

// 善后恢复数据处理
func (s *ApiTestSuite) TearDownSuite() {
dao.NewUserDao().DB.Model(models.User{}).Where("email = ?", "570165887@qq.com").Delete(nil)
}

func TestApiSuite(t *testing.T) {

var err error

err = configs.Init("")
if err != nil {
log.Fatalf("start fail:[Config Init] %s", err.Error())
}

err = web.Init()
if err != nil {
log.Fatalf("start fail:[Web Init] %s", err.Error())
}

err = redisx.Init()
if err != nil {
log.Fatalf("start fail:[Redis Init] %s", err.Error())
}

err = mysqlx.Init()
if err != nil {
log.Fatalf("start fail:[Mysql Init] %s", err.Error())
}

suite.Run(t, new(ApiTestSuite))
}
2 changes: 1 addition & 1 deletion pkg/utils/httptestutil/httptest.go
Expand Up @@ -12,7 +12,7 @@ import (
"net/url"
"strings"

"github.com/gphper/ginadmin/internal/router"
"github.com/gphper/ginadmin/pkg/utils/httptestutil/router"
)

type OptionValue struct {
Expand Down
39 changes: 39 additions & 0 deletions pkg/utils/httptestutil/router/default.go
@@ -0,0 +1,39 @@
/*
* @Description:
* @Author: gphper
* @Date: 2021-06-01 20:15:04
*/
package router

import (
"time"

"github.com/gphper/ginadmin/internal/controllers"
"github.com/gphper/ginadmin/internal/middleware"
"github.com/gphper/ginadmin/pkg/loggers/facade"
"github.com/gphper/ginadmin/pkg/loggers/medium"
"github.com/gphper/ginadmin/web"

"github.com/gin-gonic/gin"
)

func Init() (*Router, error) {

router := NewRouter(gin.Default())

//设置404错误处理
router.SetRouteError(controllers.NewHandleController().Handle)

//设置全局中间件
router.SetGlobalMiddleware(middleware.Trace(), medium.GinLog(facade.NewLogger("admin"), time.RFC3339, false), medium.RecoveryWithLog(facade.NewLogger("admin"), true))

// 设置模板解析函数
render, err := web.LoadTemplates()
if err != nil {

return nil, err
}
router.SetHtmlRenderer(render)

return &router, nil
}
7 changes: 7 additions & 0 deletions pkg/utils/httptestutil/router/icontroller.go
@@ -0,0 +1,7 @@
package router

import "github.com/gin-gonic/gin"

type IController interface {
Routes(*gin.RouterGroup)
}
101 changes: 101 additions & 0 deletions pkg/utils/httptestutil/router/router.go
@@ -0,0 +1,101 @@
/**
* @Author: GPHPER
* @Date: 2022-12-12 15:06:04
* @Github: https://github.com/gphper
* @LastEditTime: 2022-12-13 19:51:24
* @FilePath: \ginadmin\pkg\router\router.go
* @Description:
*/
package router

import (
"net/http"
"os"

"github.com/gin-contrib/gzip"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/gphper/ginadmin/internal"
"github.com/gphper/multitemplate"
)

type Router struct {
r *gin.Engine
}

func NewRouter(r *gin.Engine) Router {
return Router{
r: r,
}
}

func (route Router) SetGlobalMiddleware(middlewares ...gin.HandlerFunc) {
route.r.Use(middlewares...)
}

// 设置自定义模板加载
func (route Router) SetHtmlRenderer(render multitemplate.Renderer) {
route.r.HTMLRender = render
}

// 设置swagger访问
func (route Router) SetSwaagerHandle(path string, handle gin.HandlerFunc) {
route.r.GET(path, handle)
}

// 设置静态路径
func (route Router) SetStaticFile(path string, fs http.FileSystem) {
route.r.StaticFS(path, fs)
}

// 设置附件保存地址
func (route Router) SetUploadDir(path string) error {
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
err = os.Mkdir(path, os.ModeDir)
if err != nil {

return err
}
}
}

route.r.StaticFS("/uploadfile", http.Dir(path))

return nil
}

func (route Router) SetEngine(app *internal.Application) {
app.Route = route.r
}

func (route Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
route.r.ServeHTTP(w, req)
}

func (route Router) SetRouteError(handler gin.HandlerFunc) {
route.r.NoMethod(handler)
route.r.NoRoute(handler)
}

func (route Router) SetApiRoute(path string, ic IController, middlewares ...gin.HandlerFunc) {
ar := route.r.Group(path)
if len(middlewares) > 0 {
ar.Use(middlewares...)
}
ic.Routes(ar)
}

func (route Router) SetAdminRoute(path string, ic IController, middlewares ...gin.HandlerFunc) {

store := cookie.NewStore([]byte("1GdFRMs4fcWBvLXT"))
middlewares = append(middlewares, gzip.Gzip(gzip.DefaultCompression), sessions.Sessions("mysession", store))

ar := route.r.Group(path)
if len(middlewares) > 0 {
ar.Use(middlewares...)
}
ic.Routes(ar)
}

0 comments on commit 023e1b8

Please sign in to comment.