Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,86 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"canal_test.go",
"dao_test.go",
"ecode_test.go",
"need_test.go",
"pprof_test.go",
"upload_test.go",
"ut_app_test.go",
"ut_rank_test.go",
"ut_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/apm/conf:go_default_library",
"//app/admin/main/apm/model/canal:go_default_library",
"//app/admin/main/apm/model/need:go_default_library",
"//vendor/github.com/bouk/monkey:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"canal.go",
"dao.go",
"ecode.go",
"monkey.go",
"need.go",
"pprof.go",
"upload.go",
"ut.go",
"ut_app.go",
"ut_rank.go",
],
importpath = "go-common/app/admin/main/apm/dao",
tags = ["automanaged"],
deps = [
"//app/admin/main/apm/conf:go_default_library",
"//app/admin/main/apm/model/canal:go_default_library",
"//app/admin/main/apm/model/ecode:go_default_library",
"//app/admin/main/apm/model/need:go_default_library",
"//app/admin/main/apm/model/pprof:go_default_library",
"//app/admin/main/apm/model/ut:go_default_library",
"//library/cache/redis:go_default_library",
"//library/conf/env:go_default_library",
"//library/database/orm:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/bouk/monkey:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/admin/main/apm/dao/mock:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,96 @@
package dao
import (
cml "go-common/app/admin/main/apm/model/canal"
"go-common/library/ecode"
"go-common/library/log"
)
//SetConfigID set canal_apply table conf_id
func (d *Dao) SetConfigID(id int64, addr string) (err error) {
ups := map[string]interface{}{
"conf_id": id,
}
if err = d.DBCanal.Model(&cml.Apply{}).Where("addr = ?", addr).Updates(ups).Error; err != nil {
log.Error(" SetConfigID error(%v)", err)
err = ecode.SetConfigIDErr
return
}
return
}
//CanalInfoCounts count master_info
func (d *Dao) CanalInfoCounts(v *cml.ConfigReq) (cnt int, err error) {
if err = d.DBCanal.Model(&cml.Canal{}).Where("addr=?", v.Addr).Count(&cnt).Error; err != nil {
log.Error("apmSvc.CanalInfoCounts count error(%v)", err)
err = ecode.RequestErr
return
}
return
}
//CanalInfoEdit update master_info
func (d *Dao) CanalInfoEdit(v *cml.ConfigReq) (err error) {
ups := map[string]interface{}{
"remark": v.Mark,
"cluster": v.Project,
"leader": v.Leader,
}
if err = d.DBCanal.Model(&cml.Canal{}).Where("addr=?", v.Addr).Updates(ups).Error; err != nil {
log.Error(" CanalInfoEdit update error(%v)", err)
err = ecode.CanalApplyUpdateErr
return
}
return
}
//CanalApplyCounts count canal_apply
func (d *Dao) CanalApplyCounts(v *cml.ConfigReq) (cnt int, err error) {
if err = d.DBCanal.Model(&cml.Apply{}).Where("addr=?", v.Addr).Count(&cnt).Error; err != nil {
log.Error("apmSvc.CanalApplyEdit count error(%v)", err)
err = ecode.RequestErr
return
}
return
}
//CanalApplyEdit update canal_apply
func (d *Dao) CanalApplyEdit(v *cml.ConfigReq, username string) (err error) {
ups := map[string]interface{}{
"remark": v.Mark,
"operator": username,
"state": 1,
"cluster": v.Project,
"leader": v.Leader,
}
if err = d.DBCanal.Model(&cml.Apply{}).Where("addr=?", v.Addr).Updates(ups).Error; err != nil {
log.Error(" CanalApplyEdit update error(%v)", err)
err = ecode.CanalApplyUpdateErr
return
}
return
}
//CanalApplyCreate insert into canal_apply
func (d *Dao) CanalApplyCreate(v *cml.ConfigReq, username string) (err error) {
var (
ap = &cml.Apply{
Addr: v.Addr,
Remark: v.Mark,
State: 1,
Operator: username,
Cluster: v.Project,
Leader: v.Leader,
}
)
if err = d.DBCanal.Create(ap).Error; err != nil {
log.Error("apSvc.CanalApplyCreate create error(%v)", err)
err = ecode.CanalApplyErr
return
}
return
}

View File

@@ -0,0 +1,246 @@
package dao
import (
"fmt"
"reflect"
"testing"
cml "go-common/app/admin/main/apm/model/canal"
"github.com/bouk/monkey"
"github.com/jinzhu/gorm"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSetConfigID(t *testing.T) {
convey.Convey("SetConfigID", t, func(ctx convey.C) {
var (
id = int64(0)
addr = "127.0.0.1:8000"
db = &gorm.DB{
Error: fmt.Errorf("test"),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetConfigID(id, addr)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When DB update return err", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.DBCanal), "Updates", func(_ *gorm.DB, _ interface{}, _ ...bool) *gorm.DB {
return db
})
err := d.SetConfigID(id, addr)
ctx.Convey("Then err should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, 70014)
})
})
ctx.Reset(func() {
monkey.UnpatchAll()
})
})
}
func TestDaoCanalInfoCounts(t *testing.T) {
convey.Convey("CanalInfoCounts", t, func(ctx convey.C) {
var (
v = &cml.ConfigReq{
Addr: "127.0.0.1:3308",
User: "admin",
Password: "admin",
Project: "main.web-svr",
Leader: "fss",
Databases: "ada",
Mark: "test",
}
db = &gorm.DB{
Error: fmt.Errorf("test"),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
cnt, err := d.CanalInfoCounts(v)
ctx.Convey("Then err should be nil.cnt should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(cnt, convey.ShouldNotBeNil)
})
})
ctx.Convey("When count error", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.DBCanal), "Count", func(_ *gorm.DB, _ interface{}) *gorm.DB {
return db
})
cnt, err := d.CanalInfoCounts(v)
ctx.Convey("Then err should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, -400)
ctx.So(cnt, convey.ShouldEqual, 0)
})
})
ctx.Reset(func() {
monkey.UnpatchAll()
})
})
}
func TestDaoCanalInfoEdit(t *testing.T) {
convey.Convey("CanalInfoEdit", t, func(ctx convey.C) {
var (
v = &cml.ConfigReq{
Addr: "127.0.0.1:3308",
User: "admin",
Password: "admin",
Project: "main.web-svr",
Leader: "fss",
Databases: "ada",
Mark: "test",
}
db = &gorm.DB{
Error: fmt.Errorf("test"),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.CanalInfoEdit(v)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When edit return err", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.DBCanal), "Updates", func(_ *gorm.DB, _ interface{}, _ ...bool) *gorm.DB {
return db
})
err := d.CanalInfoEdit(v)
ctx.Convey("Then err should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, 70005)
})
})
ctx.Reset(func() {
monkey.UnpatchAll()
})
})
}
func TestDaoCanalApplyCounts(t *testing.T) {
convey.Convey("CanalApplyCounts", t, func(ctx convey.C) {
var (
v = &cml.ConfigReq{
Addr: "127.0.0.1:3308",
User: "admin",
Password: "admin",
Project: "main.web-svr",
Leader: "fss",
Databases: "ada",
Mark: "test",
}
db = &gorm.DB{
Error: fmt.Errorf("test"),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
cnt, err := d.CanalApplyCounts(v)
ctx.Convey("Then err should be nil.cnt should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(cnt, convey.ShouldNotBeNil)
})
})
ctx.Convey("When count error", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.DBCanal), "Count", func(_ *gorm.DB, _ interface{}) *gorm.DB {
return db
})
cnt, err := d.CanalApplyCounts(v)
ctx.Convey("Then err should not be nil.cnt should be 0.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, -400)
ctx.So(cnt, convey.ShouldEqual, 0)
})
})
ctx.Reset(func() {
monkey.UnpatchAll()
})
})
}
func TestDaoCanalApplyEdit(t *testing.T) {
convey.Convey("CanalApplyEdit", t, func(ctx convey.C) {
var (
v = &cml.ConfigReq{
Addr: "127.0.0.1:3308",
User: "admin",
Password: "admin",
Databases: "test",
Mark: "test",
}
db = &gorm.DB{
Error: fmt.Errorf("test"),
}
username = "fengshanshan"
)
ctx.Convey("When project and leader is null", func(ctx convey.C) {
err := d.CanalApplyEdit(v, username)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When everything goes positive", func(ctx convey.C) {
v.Leader = "fengshanshan"
v.Project = "main.web-svr"
err := d.CanalApplyEdit(v, username)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When edit error", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.DBCanal), "Updates", func(_ *gorm.DB, _ interface{}, _ ...bool) *gorm.DB {
return db
})
err := d.CanalApplyEdit(v, username)
ctx.Convey("Then err should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, 70005)
})
})
ctx.Reset(func() {
monkey.UnpatchAll()
})
})
}
func TestDaoCanalApplyCreate(t *testing.T) {
convey.Convey("CanalApplyCreate", t, func(ctx convey.C) {
var (
v = &cml.ConfigReq{
Addr: "127.0.0.1:3309",
User: "admin",
Password: "admin",
Project: "main.web-svr",
Leader: "fss",
Databases: "ada",
Mark: "test",
}
db = &gorm.DB{
Error: fmt.Errorf("test"),
}
username = "fengshanshan"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.DBCanal), "Create", func(_ *gorm.DB, _ interface{}) *gorm.DB {
return &gorm.DB{
Error: nil,
}
})
err := d.CanalApplyCreate(v, username)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When creater error", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.DBCanal), "Create", func(_ *gorm.DB, _ interface{}) *gorm.DB {
return db
})
err := d.CanalApplyCreate(v, username)
ctx.Convey("Then err should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, 70006)
})
})
ctx.Reset(func() {
monkey.UnpatchAll()
})
})
}

View File

@@ -0,0 +1,54 @@
package dao
import (
"go-common/app/admin/main/apm/conf"
"go-common/library/cache/redis"
"go-common/library/database/orm"
bm "go-common/library/net/http/blademaster"
"github.com/jinzhu/gorm"
)
// Dao dao.
type Dao struct {
c *conf.Config
DB *gorm.DB
DBDatabus *gorm.DB
DBCanal *gorm.DB
// client
client *bm.Client
Redis *redis.Pool
}
// New new a dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
DB: orm.NewMySQL(c.ORM),
DBDatabus: orm.NewMySQL(c.ORMDatabus),
DBCanal: orm.NewMySQL(c.ORMCanal),
client: bm.NewClient(c.HTTPClient),
Redis: redis.NewPool(c.Redis.Config),
}
d.initORM()
return
}
func (d *Dao) initORM() {
d.DB.LogMode(true)
d.DBDatabus.LogMode(true)
d.DBCanal.LogMode(true)
}
// Close close connection of db , mc.
func (d *Dao) Close() {
if d.DB != nil {
d.DB.Close()
}
if d.DBDatabus != nil {
d.DBDatabus.Close()
}
if d.DBCanal != nil {
d.DBCanal.Close()
}
}

View File

@@ -0,0 +1,44 @@
package dao
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/admin/main/apm/conf"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.common-arch.apm-admin")
flag.Set("conf_token", "1b457a53f52b11e7ab3616a6c13439ad")
flag.Set("tree_id", "11133")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/apm-admin-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"fmt"
"net/http"
"net/url"
"go-common/app/admin/main/apm/model/ecode"
"go-common/library/log"
)
// const (
// _codesLangsSQL = "select a.code,a.message,a.mtime,IFNULL(b.locale,''),IFNULL(b.msg,''),IFNULL(b.mtime,'') as bmtime from codes as a left join code_msg as b on a.id=b.code_id"
// )
// GetCodes ...
func (d *Dao) GetCodes(c context.Context, Interval1, Interval2 string) (data []*codes.Codes, err error) {
var (
req *http.Request
uri = "http://sven.bilibili.co/x/admin/apm/ecode/get/ecodes"
ret = codes.ResultCodes{}
params = url.Values{}
)
params.Set("interval1", Interval1)
params.Set("interval2", Interval2)
if req, err = d.client.NewRequest(http.MethodGet, uri, "", params); err != nil {
log.Error("http.NewRequest error(%v)", err)
return
}
if err = d.client.Do(c, req, &ret); err != nil {
log.Error("client Do error(%v)", err)
return
}
if ret.Code != 0 {
err = fmt.Errorf("%s params(%s) response return_code(%d)", uri, params.Encode(), ret.Code)
log.Error("error(%v)", err)
return
}
data = ret.Data
return
}

View File

@@ -0,0 +1,17 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoGetCodes(t *testing.T) {
convey.Convey("GetCodes", t, func() {
res, err := d.GetCodes(context.Background(), "0", "20000")
t.Logf("res:%+v", res)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,37 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["monkey_dao.go"],
importpath = "go-common/app/admin/main/apm/dao/mock",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/apm/dao:go_default_library",
"//app/admin/main/apm/model/canal:go_default_library",
"//app/admin/main/apm/model/ecode:go_default_library",
"//app/admin/main/apm/model/need:go_default_library",
"//app/admin/main/apm/model/pprof:go_default_library",
"//app/admin/main/apm/model/ut:go_default_library",
"//vendor/github.com/bouk/monkey:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,219 @@
package mock
import (
"context"
"go-common/app/admin/main/apm/dao"
cml "go-common/app/admin/main/apm/model/canal"
"go-common/app/admin/main/apm/model/need"
"go-common/app/admin/main/apm/model/ecode"
"go-common/app/admin/main/apm/model/pprof"
"go-common/app/admin/main/apm/model/ut"
"reflect"
"github.com/bouk/monkey"
)
// MockDaoSetConfigID .
func MockDaoSetConfigID(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SetConfigID", func(_ *dao.Dao, _ int64, _ string) error {
return err
})
}
// MockDaoCanalInfoCounts .
func MockDaoCanalInfoCounts(d *dao.Dao, cnt int, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalInfoCounts", func(_ *dao.Dao, _ *cml.ConfigReq) (int, error) {
return cnt, err
})
}
// MockDaoCanalInfoEdit .
func MockDaoCanalInfoEdit(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalInfoEdit", func(_ *dao.Dao, _ *cml.ConfigReq) error {
return err
})
}
// MockDaoCanalApplyCounts .
func MockDaoCanalApplyCounts(d *dao.Dao, cnt int, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalApplyCounts", func(_ *dao.Dao, _ *cml.ConfigReq) (int, error) {
return cnt, err
})
}
// MockDaoCanalApplyEdit .
func MockDaoCanalApplyEdit(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalApplyEdit", func(_ *dao.Dao, _ *cml.ConfigReq, _ string) error {
return err
})
}
// MockDaoCanalApplyCreate .
func MockDaoCanalApplyCreate(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalApplyCreate", func(_ *dao.Dao, _ *cml.ConfigReq, _ string) error {
return err
})
}
// MockDaoGetCodes .
func MockDaoGetCodes(d *dao.Dao, data []*codes.Codes, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetCodes", func(_ *dao.Dao, _ context.Context, _ string, _ string) ([]*codes.Codes, error) {
return data, err
})
}
// MockDaoNeedInfoAdd .
func MockDaoNeedInfoAdd(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoAdd", func(_ *dao.Dao, _ *need.NAddReq, _ string) error {
return err
})
}
// MockDaoNeedInfoList .
func MockDaoNeedInfoList(d *dao.Dao, res []*need.NInfo, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoList", func(_ *dao.Dao, _ *need.NListReq) ([]*need.NInfo, error) {
return res, err
})
}
// MockDaoNeedInfoCount .
func MockDaoNeedInfoCount(d *dao.Dao, count int64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoCount", func(_ *dao.Dao, _ *need.NListReq) (int64, error) {
return count, err
})
}
// MockDaoGetNeedInfo .
func MockDaoGetNeedInfo(d *dao.Dao, r *need.NInfo, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetNeedInfo", func(_ *dao.Dao, _ int64) (*need.NInfo, error) {
return r, err
})
}
// MockDaoNeedInfoEdit .
func MockDaoNeedInfoEdit(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoEdit", func(_ *dao.Dao, _ *need.NEditReq) error {
return err
})
}
// MockDaoNeedVerify .
func MockDaoNeedVerify(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedVerify", func(_ *dao.Dao, _ *need.NVerifyReq) error {
return err
})
}
// MockDaoLikeCountsStats .
func MockDaoLikeCountsStats(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "LikeCountsStats", func(_ *dao.Dao, _ *need.Likereq, _ int, _ int) error {
return err
})
}
// MockDaoGetVoteInfo .
func MockDaoGetVoteInfo(d *dao.Dao, u *need.UserLikes, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetVoteInfo", func(_ *dao.Dao, _ *need.Likereq, _ string) (*need.UserLikes, error) {
return u, err
})
}
// MockDaoUpdateVoteInfo .
func MockDaoUpdateVoteInfo(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "UpdateVoteInfo", func(_ *dao.Dao, _ *need.Likereq, _ string) error {
return err
})
}
// MockDaoAddVoteInfo .
func MockDaoAddVoteInfo(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "AddVoteInfo", func(_ *dao.Dao, _ *need.Likereq, _ string) error {
return err
})
}
// MockDaoVoteInfoList .
func MockDaoVoteInfoList(d *dao.Dao, res []*need.UserLikes, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "VoteInfoList", func(_ *dao.Dao, _ *need.Likereq) ([]*need.UserLikes, error) {
return res, err
})
}
// MockDaoVoteInfoCounts .
func MockDaoVoteInfoCounts(d *dao.Dao, count int64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "VoteInfoCounts", func(_ *dao.Dao, _ *need.Likereq) (int64, error) {
return count, err
})
}
// MockDaoInstances .
func MockDaoInstances(d *dao.Dao, ins *pprof.Ins, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "Instances", func(_ *dao.Dao, _ context.Context, _ string) (*pprof.Ins, error) {
return ins, err
})
}
// MockDaoGitLabFace .
func MockDaoGitLabFace(d *dao.Dao, avatarURL string, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GitLabFace", func(_ *dao.Dao, _ context.Context, _ string) (string, error) {
return avatarURL, err
})
}
// MockDaoUploadProxy .
func MockDaoUploadProxy(d *dao.Dao, url string, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "UploadProxy", func(_ *dao.Dao, _ context.Context, _ string, _ int64, _ []byte) (string, error) {
return url, err
})
}
// MockDaoParseUTFiles .
func MockDaoParseUTFiles(d *dao.Dao, pkgs []*ut.PkgAnls, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "ParseUTFiles", func(_ *dao.Dao, _ context.Context, _ string) ([]*ut.PkgAnls, error) {
return pkgs, err
})
}
// MockDaoSendWechatToUsers .
func MockDaoSendWechatToUsers(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SendWechatToUsers", func(_ *dao.Dao, _ context.Context, _ []string, _ string) error {
return err
})
}
// MockDaoSendWechatToGroup .
func MockDaoSendWechatToGroup(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SendWechatToGroup", func(_ *dao.Dao, _ context.Context, _ string, _ string) error {
return err
})
}
// MockDaoGitLabCommits .
func MockDaoGitLabCommits(d *dao.Dao, commit *ut.GitlabCommit, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GitLabCommits", func(_ *dao.Dao, _ context.Context, _ string) (*ut.GitlabCommit, error) {
return commit, err
})
}
// MockDaoGetCoverage .
func MockDaoGetCoverage(d *dao.Dao, cov float64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetCoverage", func(_ *dao.Dao, _ context.Context, _ string, _ string) (float64, error) {
return cov, err
})
}
// MockDaoSetAppCovCache .
func MockDaoSetAppCovCache(d *dao.Dao, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SetAppCovCache", func(_ *dao.Dao, _ context.Context) error {
return err
})
}
// MockDaoGetAppCovCache .
func MockDaoGetAppCovCache(d *dao.Dao, coverage float64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetAppCovCache", func(_ *dao.Dao, _ context.Context, _ string) (float64, error) {
return coverage, err
})
}

View File

@@ -0,0 +1,202 @@
package dao
import (
"context"
cml "go-common/app/admin/main/apm/model/canal"
"go-common/app/admin/main/apm/model/ecode"
"go-common/app/admin/main/apm/model/need"
"go-common/app/admin/main/apm/model/pprof"
"go-common/app/admin/main/apm/model/ut"
"reflect"
"github.com/bouk/monkey"
)
//MockSetConfigID is
func (d *Dao) MockSetConfigID(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SetConfigID", func(_ *Dao, _ int64, _ string) error {
return err
})
}
//MockCanalInfoCounts is
func (d *Dao) MockCanalInfoCounts(cnt int, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalInfoCounts", func(_ *Dao, _ *cml.ConfigReq) (int, error) {
return cnt, err
})
}
//MockCanalInfoEdit is
func (d *Dao) MockCanalInfoEdit(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalInfoEdit", func(_ *Dao, _ *cml.ConfigReq) error {
return err
})
}
//MockCanalApplyCounts is
func (d *Dao) MockCanalApplyCounts(cnt int, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalApplyCounts", func(_ *Dao, _ *cml.ConfigReq) (int, error) {
return cnt, err
})
}
//MockCanalApplyEdit is
func (d *Dao) MockCanalApplyEdit(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalApplyEdit", func(_ *Dao, _ *cml.ConfigReq, _ string) error {
return err
})
}
//MockCanalApplyCreate is
func (d *Dao) MockCanalApplyCreate(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "CanalApplyCreate", func(_ *Dao, _ *cml.ConfigReq, _ string) error {
return err
})
}
//MockGetCodes is
func (d *Dao) MockGetCodes(data []*codes.Codes, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetCodes", func(_ *Dao, _ context.Context, _ string, _ string) ([]*codes.Codes, error) {
return data, err
})
}
//MockNeedInfoAdd is
func (d *Dao) MockNeedInfoAdd(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoAdd", func(_ *Dao, _ *need.NAddReq, _ string) error {
return err
})
}
//MockNeedInfoList is
func (d *Dao) MockNeedInfoList(res []*need.NInfo, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoList", func(_ *Dao, _ *need.NListReq) ([]*need.NInfo, error) {
return res, err
})
}
//MockNeedInfoCount is
func (d *Dao) MockNeedInfoCount(count int64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoCount", func(_ *Dao, _ *need.NListReq) (int64, error) {
return count, err
})
}
//MockGetNeedInfo is
func (d *Dao) MockGetNeedInfo(r []*need.NInfo, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetNeedInfo", func(_ *Dao, _ int64) ([]*need.NInfo, error) {
return r, err
})
}
//MockNeedInfoEdit is
func (d *Dao) MockNeedInfoEdit(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedInfoEdit", func(_ *Dao, _ *need.NEditReq) error {
return err
})
}
//MockNeedVerify is
func (d *Dao) MockNeedVerify(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "NeedVerify", func(_ *Dao, _ *need.NVerifyReq) error {
return err
})
}
//MockLikeCountsStats is
func (d *Dao) MockLikeCountsStats(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "LikeCountsStats", func(_ *Dao, _ *need.Likereq, _ int, _ int) error {
return err
})
}
//MockGetVoteInfo is
func (d *Dao) MockGetVoteInfo(u []*need.UserLikes, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetVoteInfo", func(_ *Dao, _ *need.Likereq, _ string) ([]*need.UserLikes, error) {
return u, err
})
}
//MockUpdateVoteInfo is
func (d *Dao) MockUpdateVoteInfo(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "UpdateVoteInfo", func(_ *Dao, _ *need.Likereq, _ string) error {
return err
})
}
//MockAddVoteInfo is
func (d *Dao) MockAddVoteInfo(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "AddVoteInfo", func(_ *Dao, _ *need.Likereq, _ string) error {
return err
})
}
//MockVoteInfoList is
func (d *Dao) MockVoteInfoList(res []*need.UserLikes, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "VoteInfoList", func(_ *Dao, _ *need.Likereq) ([]*need.UserLikes, error) {
return res, err
})
}
//MockVoteInfoCounts is
func (d *Dao) MockVoteInfoCounts(count int64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "VoteInfoCounts", func(_ *Dao, _ *need.Likereq) (int64, error) {
return count, err
})
}
//MockInstances is
func (d *Dao) MockInstances(ins *pprof.Ins, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "Instances", func(_ *Dao, _ context.Context, _ string) (*pprof.Ins, error) {
return ins, err
})
}
//MockGitLabFace is
func (d *Dao) MockGitLabFace(avatarURL string, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GitLabFace", func(_ *Dao, _ context.Context, _ string) (string, error) {
return avatarURL, err
})
}
//MockUploadProxy is
func (d *Dao) MockUploadProxy(url string, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "UploadProxy", func(_ *Dao, _ context.Context, _ string, _ int64, _ []byte) (string, error) {
return url, err
})
}
//MockParseUTFiles is
func (d *Dao) MockParseUTFiles(pkgs []*ut.PkgAnls, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "ParseUTFiles", func(_ *Dao, _ context.Context, _ string) ([]*ut.PkgAnls, error) {
return pkgs, err
})
}
//MockSendWechatToUsers is
func (d *Dao) MockSendWechatToUsers(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SendWechatToUsers", func(_ *Dao, _ context.Context, _ []string, _ string) error {
return err
})
}
//MockSendWechatToGroup is
func (d *Dao) MockSendWechatToGroup(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SendWechatToGroup", func(_ *Dao, _ context.Context, _ string, _ string) error {
return err
})
}
//MockGitLabCommits is
func (d *Dao) MockGitLabCommits(commit *ut.GitlabCommit, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GitLabCommits", func(_ *Dao, _ context.Context, _ string) (*ut.GitlabCommit, error) {
return commit, err
})
}
//MockGetCoverage is
func (d *Dao) MockGetCoverage(cov float64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "GetCoverage", func(_ *Dao, _ context.Context, _ string, _ string) (float64, error) {
return cov, err
})
}

View File

@@ -0,0 +1,181 @@
package dao
import (
"fmt"
"go-common/app/admin/main/apm/model/need"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_tableNeed = "needs"
_tableLike = "user_likes"
_addCountsSQL = "UPDATE needs SET like_counts=like_counts+?,dislike_counts=dislike_counts+? WHERE id=?"
)
//NeedInfoAdd add need info
func (d *Dao) NeedInfoAdd(r *need.NAddReq, username string) (err error) {
ni := &need.NInfo{
Title: r.Title,
Content: r.Content,
Reporter: username,
Status: 1,
}
if err = d.DB.Create(&ni).Error; err != nil {
err = errors.WithStack(err)
return
}
return
}
//NeedInfoList all need info
func (d *Dao) NeedInfoList(arg *need.NListReq) (res []*need.NInfo, err error) {
where := d.needInfoCondition(arg)
if err = d.DB.Table(_tableNeed).Where(where).Order("id DESC").Offset((arg.Pn - 1) * arg.Ps).Limit(arg.Ps).Find(&res).Error; err != nil {
err = errors.WithStack(err)
log.Error("NeedInfoList:%s", err)
return
}
return
}
//NeedInfoCount need info count
func (d *Dao) NeedInfoCount(arg *need.NListReq) (count int64, err error) {
where := d.needInfoCondition(arg)
if err = d.DB.Table(_tableNeed).Where(where).Count(&count).Error; err != nil {
log.Error("NeedInfoCount:%s", err)
return
}
return
}
//needInfoCondition is
func (d *Dao) needInfoCondition(arg *need.NListReq) (where string) {
where = "status !=5"
if arg.Status > 0 {
where += fmt.Sprintf(" and `status`='%d'", arg.Status)
}
if arg.Reporter != "" {
where += fmt.Sprintf(" and `reporter`='%s'", arg.Reporter)
}
return where
}
// GetNeedInfo is
func (d *Dao) GetNeedInfo(id int64) (r *need.NInfo, err error) {
r = &need.NInfo{}
if err = d.DB.Table(_tableNeed).Where("id=?", id).Find(r).Error; err != nil {
log.Error("GetNeedInfo:%s", err)
return
}
return
}
//NeedInfoEdit is
func (d *Dao) NeedInfoEdit(arg *need.NEditReq) (err error) {
if err = d.DB.Table(_tableNeed).Where("id=?", arg.ID).Updates(map[string]interface{}{"content": arg.Content, "title": arg.Title}).Error; err != nil {
log.Error("NeedInfoEdit:%s", err)
return
}
return
}
//NeedVerify is
func (d *Dao) NeedVerify(r *need.NVerifyReq) (err error) {
tx := d.DB.Begin()
if err = d.DB.Table(_tableNeed).Where("id=?", r.ID).Update("status", r.Status).Error; err != nil {
log.Error("NeedVerify:%s", err)
tx.Rollback()
return
}
tx.Commit()
return
}
//LikeCountsStats thumbsup counts
func (d *Dao) LikeCountsStats(r *need.Likereq, like, dislike int) (err error) {
tx := d.DB.Begin()
if err = d.DB.Exec(_addCountsSQL, like, dislike, r.ReqID).Error; err != nil {
err = errors.WithStack(err)
log.Error("LikeCountsStats:%s", err)
tx.Rollback()
return
}
tx.Commit()
return
}
//GetVoteInfo is
func (d *Dao) GetVoteInfo(r *need.Likereq, username string) (u *need.UserLikes, err error) {
u = &need.UserLikes{}
if err = d.DB.Table(_tableLike).Where("req_id=? and `user`=?", r.ReqID, username).Find(u).Error; err != nil {
err = errors.WithStack(err)
return
}
return
}
//UpdateVoteInfo is
func (d *Dao) UpdateVoteInfo(r *need.Likereq, username string) (err error) {
if err = d.DB.Table(_tableLike).Where("req_id=? and `user`=?", r.ReqID, username).Update("like_type", r.LikeType).Error; err != nil {
err = errors.WithStack(err)
log.Error("UpdateVoteInfo:%s", err)
return
}
return
}
//AddVoteInfo is
func (d *Dao) AddVoteInfo(r *need.Likereq, username string) (err error) {
ul := &need.UserLikes{
ReqID: r.ReqID,
User: username,
LikeType: r.LikeType,
}
if err = d.DB.Create(&ul).Error; err != nil {
err = errors.WithStack(err)
return
}
return
}
//voteInfoCondition is
func (d *Dao) voteInfoCondition(arg *need.Likereq) (where string) {
where = " like_type != 0 "
if arg.ReqID > 0 {
where += fmt.Sprintf(" and `req_id`='%d'", arg.ReqID)
}
if arg.LikeType > 0 {
where += fmt.Sprintf(" and `like_type`='%d'", arg.LikeType)
}
return where
}
//VoteInfoList is vote info
func (d *Dao) VoteInfoList(arg *need.Likereq) (res []*need.UserLikes, err error) {
where := d.voteInfoCondition(arg)
if err = d.DB.Table(_tableLike).Where(where).Find(&res).Error; err != nil {
err = errors.WithStack(err)
log.Error("VoteInfoList:%s", err)
return
}
return
}
//VoteInfoCounts vote info count
func (d *Dao) VoteInfoCounts(arg *need.Likereq) (count int64, err error) {
where := d.voteInfoCondition(arg)
if err = d.DB.Table(_tableLike).Where(where).Count(&count).Error; err != nil {
log.Error("VoteInfoCount:%s", err)
return
}
return
}

View File

@@ -0,0 +1,160 @@
package dao
import (
"reflect"
"testing"
"go-common/app/admin/main/apm/model/need"
"github.com/bouk/monkey"
"github.com/jinzhu/gorm"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoNeedInfoAdd(t *testing.T) {
convey.Convey("NeedInfoAdd", t, func() {
arg := &need.NAddReq{
Title: "wwe",
Content: "sds",
}
err := d.NeedInfoAdd(arg, "fengshanshan")
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoNeedInfoList(t *testing.T) {
convey.Convey("NeedInfoList", t, func() {
arg := &need.NListReq{
Status: 1,
Ps: 10,
Pn: 1,
}
res, err := d.NeedInfoList(arg)
t.Logf("res:%+v", res)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
func TestDaoNeedInfoCount(t *testing.T) {
convey.Convey("NeedInfoCount", t, func() {
arg := &need.NListReq{
Status: 1,
}
count, err := d.NeedInfoCount(arg)
t.Logf("count:%+v", count)
convey.So(err, convey.ShouldBeNil)
convey.So(count, convey.ShouldNotBeNil)
})
}
func TestDaoneedInfoCondition(t *testing.T) {
convey.Convey("needInfoCondition", t, func() {
arg := &need.NListReq{}
p1 := d.needInfoCondition(arg)
t.Logf("condition:%+v", p1)
convey.So(p1, convey.ShouldNotBeNil)
})
}
func TestDaoGetNeedInfo(t *testing.T) {
convey.Convey("GetNeedInfo", t, func() {
r, err := d.GetNeedInfo(97)
t.Logf("GetNeedInfo:%+v", r)
convey.So(err, convey.ShouldBeNil)
convey.So(r, convey.ShouldNotBeNil)
})
}
func TestDaoNeedInfoEdit(t *testing.T) {
convey.Convey("NeedInfoEdit", t, func() {
arg := &need.NEditReq{
Content: "dsada",
Title: "fsd",
ID: 28,
}
err := d.NeedInfoEdit(arg)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoNeedVerify(t *testing.T) {
convey.Convey("NeedVerify", t, func() {
v := &need.NVerifyReq{
ID: 28,
Status: 2,
}
err := d.NeedVerify(v)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoLikeCountsAdd(t *testing.T) {
convey.Convey("LikeCountsAdd", t, func() {
v := &need.Likereq{
ReqID: 148,
LikeType: 1,
}
err := d.LikeCountsStats(v, 1, 0)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoGetVoteInfo(t *testing.T) {
convey.Convey("GetVoteInfo", t, func() {
var (
db = &gorm.DB{
Error: nil,
}
v = &need.Likereq{
ReqID: 148,
LikeType: 1,
}
)
guard := monkey.PatchInstanceMethod(reflect.TypeOf(d.DB), "Find", func(_ *gorm.DB, _ interface{}, _ ...interface{}) *gorm.DB {
return db
})
defer guard.Unpatch()
res, err := d.GetVoteInfo(v, "fengshanshan")
t.Logf("res:%+v", res)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
func TestDaoUpdateVoteInfo(t *testing.T) {
convey.Convey("UpdateVoteInfo", t, func() {
v := &need.Likereq{
ReqID: 30,
LikeType: 2,
}
err := d.UpdateVoteInfo(v, "fengshanshan")
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoVoteInfoList(t *testing.T) {
convey.Convey("VoteInfoList", t, func() {
arg := &need.Likereq{
ReqID: 11,
LikeType: 2,
}
res, err := d.VoteInfoList(arg)
t.Logf("res:%+v", res)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
func TestDaoVoteInfoCounts(t *testing.T) {
convey.Convey("VoteInfoCounts", t, func() {
arg := &need.Likereq{
ReqID: 11,
LikeType: 1,
}
count, err := d.VoteInfoCounts(arg)
t.Logf("count:%+v", count)
convey.So(err, convey.ShouldBeNil)
convey.So(count, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"fmt"
"net/http"
"net/url"
"go-common/app/admin/main/apm/model/pprof"
"go-common/library/conf/env"
"go-common/library/log"
)
// Instances get instances
func (d *Dao) Instances(c context.Context, appName string) (ins *pprof.Ins, err error) {
var (
req *http.Request
uri = d.c.Host.SVENCo + "/x/admin/apm/noauth/discovery/fetch"
ret = &pprof.Response{}
params = url.Values{}
)
params.Add("zone", env.Zone)
params.Add("env", env.DeployEnv)
params.Add("region", env.Region)
params.Add("appid", appName)
params.Add("status", "3")
if req, err = d.client.NewRequest(http.MethodGet, uri, "", params); err != nil {
log.Error("d.Instances http.NewRequest error(%v)", err)
return
}
if err = d.client.Do(c, req, ret); err != nil {
log.Error("d.Instances client Do error(%v)", err)
return
}
if ret.Code != 0 {
err = fmt.Errorf("%s params(%s) response return_code(%d)", uri, params.Encode(), ret.Code)
log.Error("d.Instance error(%v)", err)
return
}
ins = ret.Data
return
}

View File

@@ -0,0 +1,18 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoInstance(t *testing.T) {
convey.Convey("Instance", t, func() {
var appName = "main.app-svr.app-view"
ins, err := d.Instances(context.Background(), appName)
convey.So(err, convey.ShouldBeNil)
convey.So(ins, convey.ShouldNotEqual, nil)
})
}

View File

@@ -0,0 +1,66 @@
package dao
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"hash"
"net/http"
"strconv"
)
func authorize(key, secret, method, bucket string, expire int64) (authorization string) {
var (
content string
hash2 hash.Hash
signature string
template = "%s\n%s\n\n%d\n"
)
content = fmt.Sprintf(template, method, bucket, expire)
hash2 = hmac.New(sha1.New, []byte(secret))
hash2.Write([]byte(content))
signature = base64.StdEncoding.EncodeToString(hash2.Sum(nil))
authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
return
}
// UploadProxy upload file to bfs with no filename.
func (d *Dao) UploadProxy(c context.Context, fileType string, expire int64, body []byte) (url string, err error) {
var (
req *http.Request
resp *http.Response
header http.Header
code string
bfs = d.c.Bfs
uploadURL = "/%s"
)
url = fmt.Sprintf(bfs.Addr+uploadURL, bfs.Bucket)
if req, err = http.NewRequest(http.MethodPut, url, bytes.NewReader(body)); err != nil {
err = fmt.Errorf("dao.UploadProxy NewRequest error(%v)", err)
return
}
authorization := authorize(bfs.Key, bfs.Secret, http.MethodPut, bfs.Bucket, expire)
req.Header.Set("Host", bfs.Addr)
req.Header.Add("Date", fmt.Sprint(expire))
req.Header.Add("Authorization", authorization)
req.Header.Add("Content-Type", fileType)
if resp, err = http.DefaultClient.Do(req); err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("dao.UploadProxy error return_status(%d)", resp.StatusCode)
return
}
header = resp.Header
code = header.Get("Code")
if code != strconv.Itoa(http.StatusOK) {
err = fmt.Errorf("dao.UploadProxy Upload url(%s) return_code(%s)", url, code)
return
}
url = header.Get("Location")
return
}

View File

@@ -0,0 +1,45 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoauthorize(t *testing.T) {
convey.Convey("authorize", t, func(ctx convey.C) {
var (
key = d.c.Bfs.Key
secret = d.c.Bfs.Secret
method = "PUT"
bucket = d.c.Bfs.Bucket
expire = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
authorization := authorize(key, secret, method, bucket, expire)
ctx.Convey("Then authorization should not be nil.", func(ctx convey.C) {
ctx.So(authorization, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUploadProxy(t *testing.T) {
convey.Convey("UploadProxy", t, func(ctx convey.C) {
var (
c = context.Background()
fileType = ""
expire = int64(1)
body = []byte("")
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
httpMock("PUT", d.c.Bfs.Addr+"/"+d.c.Bfs.Bucket).Reply(200).SetHeader("Code", "200")
url, err := d.UploadProxy(c, fileType, expire, body)
ctx.Convey("Then err should be nil.url should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(url, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,183 @@
package dao
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"go-common/app/admin/main/apm/conf"
"go-common/app/admin/main/apm/model/ut"
"go-common/library/log"
"github.com/jinzhu/gorm"
)
const (
_sagaWechatURL = "http://uat-saga-admin.bilibili.co/ep/admin/saga/v2/wechat"
_gitCommitsAPI = "http://git.bilibili.co/api/v4/projects/682/repository/commits"
)
// ParseUTFiles parse html to get specific file
func (d *Dao) ParseUTFiles(c context.Context, url string) (pkgs []*ut.PkgAnls, err error) {
var (
req *http.Request
html []byte
files []string
)
if req, err = http.NewRequest(http.MethodGet, url, nil); err != nil {
log.Error("apmSvc.ParseUTFiless error (%v)", err)
return
}
if html, err = d.client.Raw(c, req); err != nil {
log.Error("apmSvc.ParseUTFiles error (%v)", err)
return
}
reg := regexp.MustCompile(`<option(.*)</option>`)
files = reg.FindAllString(string(html), -1)
for _, file := range files {
cov, _ := strconv.ParseFloat(file[strings.Index(file, "(")+1:strings.Index(file, "%)")], 64)
pkg := &ut.PkgAnls{
PKG: file[strings.Index(file, "go-common") : strings.Index(file, ".go")+3],
Coverage: cov,
HTMLURL: url + "#" + file[strings.Index(file, `="`)+2:strings.Index(file, `">`)],
}
pkgs = append(pkgs, pkg)
}
return
}
// SendWechatToUsers send msg to multiple users by saga-admin api
func (d *Dao) SendWechatToUsers(c context.Context, users []string, msg string) (err error) {
var (
req *http.Request
b = &bytes.Buffer{}
url = _sagaWechatURL + "/message/send"
res struct {
Code int `json:"code"`
Message string `json:"message"`
}
body = &ut.WechatUsersMsg{
ToUser: users,
Content: msg,
}
)
if err = json.NewEncoder(b).Encode(body); err != nil {
log.Error("apmSvc.SendWechatToUsers Error(%v)", err)
return
}
if req, err = http.NewRequest(http.MethodPost, url, b); err != nil {
log.Error("apmSvc.SendWechatToUsers Error(%v)", err)
return
}
if err = d.client.Do(c, req, &res); err != nil {
log.Error("apmSvc.SendWechatToUsers Error(%v)", err)
return
}
if res.Code != 0 {
err = fmt.Errorf("Http response Code(%v)!=0", res.Code)
log.Error("apmSvc.SendWechatToUsers Error(%v)", err)
return
}
return
}
// SendWechatToGroup send msg to a group by saga-admin api
func (d *Dao) SendWechatToGroup(c context.Context, chatid, msg string) (err error) {
var (
num int
req *http.Request
b = &bytes.Buffer{}
url = _sagaWechatURL + "/appchat/send"
body = &ut.WechatGroupMsg{
ChatID: chatid,
MsgType: "text",
Safe: 0,
}
)
msgBlock := strings.Split(msg, "\n")
if len(msgBlock)%40 == 0 {
num = len(msgBlock)/40 - 1
} else {
num = len(msgBlock) / 40
}
for i := 0; i <= num; i++ {
var (
res struct {
Code int `json:"code"`
Message string `json:"message"`
}
)
start, end := 40*i, 40*(i+1)
if end > len(msgBlock) {
end = len(msgBlock)
}
body.Text = &ut.TextContent{
Content: strings.Join(msgBlock[start:end], "\n") + fmt.Sprintf("\n(%d/%d)", i+1, num+1),
}
if err = json.NewEncoder(b).Encode(body); err != nil {
log.Error("apmSvc.SendWechatToGroup Error(%v)", err)
return
}
if req, err = http.NewRequest(http.MethodPost, url, b); err != nil {
log.Error("apmSvc.SendWechatToGroup Error(%v)", err)
return
}
if err = d.client.Do(c, req, &res); err != nil {
log.Error("apmSvc.SendWechatToGroup Error(%v)", err)
return
}
if res.Code != 0 {
err = fmt.Errorf("Http response Code(%v)!=0", res.Code)
log.Error("apmSvc.SendWechatToGroup Error(%v)", err)
return
}
}
return
}
// GitLabCommits transfer gitlab uri,now support get method
func (d *Dao) GitLabCommits(c context.Context, commitID string) (commit *ut.GitlabCommit, err error) {
var req *http.Request
params := url.Values{}
params.Set("private_token", conf.Conf.Gitlab.Token)
if req, err = http.NewRequest(http.MethodGet, _gitCommitsAPI+"/"+commitID+"?"+params.Encode(), nil); err != nil {
log.Error("GitLabCommits http.NewRequest error(%v) params(%s)", err, params.Encode())
return
}
if err = d.client.Do(c, req, &commit); err != nil {
log.Error("GitLabCommits d.client.Do error(%v) params(%s)", err, params.Encode())
return
}
return
}
// GetCoverage get the none-file coverage by commitID and pkg (pkg cannot be fileName)
func (d *Dao) GetCoverage(c context.Context, commitID, pkg string) (cov float64, err error) {
var (
count = strings.Count(pkg, "/")
file = &ut.File{}
)
if len(pkg) == 0 {
err = fmt.Errorf("The pkg should not be empty")
return
}
if pkg[len(pkg)-1] != '/' {
count++
}
err = d.DB.Select(`commit_id,substring_index(name,"/",?) as pkg,round(sum(covered_statements)/sum(statements)*100,2) as coverage`, count).Group(fmt.Sprintf(`commit_id,substring_index(name,"/",%d)`, count)).Having("commit_id=? and pkg=?", commitID, pkg).First(file).Error
if err == gorm.ErrRecordNotFound {
cov, err = 0.00, nil
return
} else if err != nil {
log.Error("dao.GetCoverage commitID(%s) pkg(%s) error(%v)", commitID, pkg, err)
return
}
cov = file.Coverage
return
}

View File

@@ -0,0 +1,58 @@
package dao
import (
"context"
"go-common/app/admin/main/apm/model/ut"
"go-common/library/cache/redis"
"go-common/library/log"
"time"
)
// SetAppCovCache set apps and depts coverage into redis.
func (d *Dao) SetAppCovCache(c context.Context) (err error) {
var (
apps []*ut.App
deptApps []*ut.App
conn = d.Redis.Get(c)
expireTime = int64(time.Duration(d.c.Redis.ExpireTime) / time.Second)
)
defer conn.Close()
if err = d.DB.Find(&apps).Error; err != nil {
log.Error("d.AddAppCovCache DB.Find Error(%v)", err)
return
}
if err = d.DB.Raw(`select substring_index(substring_index(path,"/",4),"/",-1) as path,avg(coverage) as coverage,max(mtime) as mtime from ut_app where has_ut=1 group by substring_index(substring_index(path,"/",4),"/",-1)`).
Find(&deptApps).Error; err != nil {
log.Error("d.AddAppCovCache DB.Find Error(%v)", err)
return
}
apps = append(apps, deptApps...)
for _, app := range apps {
if err = conn.Send("SETEX", app.Path, expireTime, app.Coverage); err != nil {
log.Error("d.AddAppCovCache Redis.SETEX Error(%v)", err)
return
}
}
return
}
// GetAppCovCache get apps and depts coverage from redis.
func (d *Dao) GetAppCovCache(c context.Context, path string) (coverage float64, err error) {
var (
conn = d.Redis.Get(c)
exist bool
key = path
)
defer conn.Close()
if exist, err = redis.Bool(conn.Do("EXISTS", key)); err != nil {
log.Error("d.GetAppCov Error(%v)", err)
return
}
if exist {
if coverage, err = redis.Float64(conn.Do("GET", key)); err != nil {
log.Error("d.GetAppCov Error(%v)", err)
return
}
}
return
}

View File

@@ -0,0 +1,41 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSetAppCovCache(t *testing.T) {
convey.Convey("SetAppCovCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.SetAppCovCache(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
// coverage, _ := d.GetAppCovCache(c, "main")
// t.Logf("\nthe coverage is %.2f\n", coverage)
})
})
})
}
func TestDaoGetAppCovCache(t *testing.T) {
convey.Convey("GetAppCovCache", t, func(ctx convey.C) {
var (
c = context.Background()
path = "main"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
coverage, err := d.GetAppCovCache(c, path)
ctx.Convey("Then err should be nil.coverage should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(coverage, convey.ShouldNotBeNil)
t.Logf("\nthe coverage is %.2f\n", coverage)
})
})
})
}

View File

@@ -0,0 +1,38 @@
package dao
import (
"context"
"net/http"
"net/url"
"strings"
"go-common/app/admin/main/apm/conf"
"go-common/app/admin/main/apm/model/ut"
"go-common/library/log"
)
const (
_gitUsersAPI = "http://git.bilibili.co/api/v4/users"
)
// GitLabFace return face of gitlab.
func (d *Dao) GitLabFace(c context.Context, username string) (avatarURL string, err error) {
params := url.Values{}
params.Set("username", username)
params.Set("private_token", conf.Conf.Gitlab.Token)
var req *http.Request
if req, err = http.NewRequest(http.MethodGet, _gitUsersAPI, strings.NewReader(params.Encode())); err != nil {
log.Error("http.NewRequest(%s) error(%v)", username, err)
return
}
res := make([]*ut.Image, 0)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if err = d.client.Do(c, req, &res); err != nil {
log.Error("d.client.Do(%s) error(%v)", username, err)
return
}
for _, v := range res {
avatarURL = v.AvatarURL
}
return
}

View File

@@ -0,0 +1,17 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoGitLabFace(t *testing.T) {
username := "chenjianrong"
convey.Convey("GitLabFace", t, func() {
res, err := d.GitLabFace(context.Background(), username)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,144 @@
package dao
import (
"context"
"net/http"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoParseUTFiles(t *testing.T) {
convey.Convey("ParseUTFiles", t, func(ctx convey.C) {
var (
c = context.Background()
url = "http://uat-i0.hdslb.com/bfs/test/03af5d0707e4c6ec41a3eb797c8e9897f124515c.html"
)
gock.Off()
d.client.SetTransport(http.DefaultClient.Transport)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
pkgs, err := d.ParseUTFiles(c, url)
//t.Logf("the pkg[0] is PKG: %s, Coverage: %v, HTMLURL: %s", pkgs[0].PKG, pkgs[0].Coverage, pkgs[0].HTMLURL)
ctx.Convey("Then err should be nil.pkgs should not be nil.", func(ctx convey.C) {
ctx.So(pkgs, convey.ShouldNotBeNil)
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGitCommitInfo(t *testing.T) {
convey.Convey("GitCommitInfo", t, func(ctx convey.C) {
var (
c = context.Background()
commitID = "ae1377033a11ca85a19bca365af32a5b0ebea31c"
)
gock.Off()
d.client.SetTransport(http.DefaultClient.Transport)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
commit, err := d.GitLabCommits(c, commitID)
ctx.Convey("Then err should be nil. gitcommit should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(commit, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSendWechatToUsers(t *testing.T) {
convey.Convey("SendWechatToUsers", t, func(ctx convey.C) {
var (
c = context.Background()
users = []string{"zhaobingqing"}
msg = "给你我的小心心❤"
)
d.client.SetTransport(gock.DefaultTransport)
ctx.Convey("When everything gose postive", func(ctx convey.C) {
httpMock("POST", _sagaWechatURL+"/message/send").Reply(200).JSON(`{"code":0,"message":"0"}`)
err := d.SendWechatToUsers(c, users, msg)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When http status != 200", func(ctx convey.C) {
httpMock("POST", _sagaWechatURL+"/message/send").Reply(404)
err := d.SendWechatToUsers(c, users, msg)
ctx.Convey("Then err should not be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("When http response code != 0", func(ctx convey.C) {
httpMock("POST", _sagaWechatURL+"/message/send").Reply(200).JSON(`{"code":-401,"message":"0"}`)
err := d.SendWechatToUsers(c, users, msg)
ctx.Convey("Then err should not be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Reset(func() {
gock.Off()
d.client.SetTransport(http.DefaultClient.Transport)
})
})
}
func TestDaoSendWechatToGroup(t *testing.T) {
convey.Convey("SendWechatToGroup", t, func(ctx convey.C) {
var (
msg = "信息测试~@002157"
c = context.Background()
)
d.client.SetTransport(gock.DefaultTransport)
ctx.Convey("When everything gose postive", func(ctx convey.C) {
httpMock("POST", _sagaWechatURL+"/appchat/send").Reply(200).JSON(`{"code":0,"message":"0"}`)
err := d.SendWechatToGroup(c, d.c.WeChat.ChatID, msg)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When http status != 200", func(ctx convey.C) {
httpMock("POST", _sagaWechatURL+"/appchat/send").Reply(404)
err := d.SendWechatToGroup(c, d.c.WeChat.ChatID, msg)
ctx.Convey("Then err should not be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("When http response code != 0", func(ctx convey.C) {
httpMock("POST", _sagaWechatURL+"/appchat/send").Reply(200).JSON(`{"code":-401,"message":"0"}`)
err := d.SendWechatToGroup(c, d.c.WeChat.ChatID, msg)
ctx.Convey("Then err should not be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Reset(func() {
gock.Off()
d.client.SetTransport(http.DefaultClient.Transport)
})
})
}
func TestDaoGetCoverage(t *testing.T) {
convey.Convey("GetCoverage", t, func(ctx convey.C) {
var (
c = context.Background()
commitID = "8d2f1b49661c7089e2b595eafff326033a138c23"
pkg = "go-common/app/admin/main/apm"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
cov, err := d.GetCoverage(c, commitID, pkg)
ctx.Convey("Then err should be nil.cov should not be nil.", func(ctx convey.C) {
// t.Logf("the cov of %s is %.2f", pkg, cov)
ctx.So(cov, convey.ShouldNotBeNil)
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When the pkg is empty string", func(ctx convey.C) {
pkg = ""
_, err := d.GetCoverage(c, commitID, pkg)
ctx.Convey("Then err should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}