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,67 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"db_wechat.go",
"hbase.go",
"http.go",
"lock.go",
"mc.go",
"redis.go",
],
importpath = "go-common/app/tool/saga/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/tool/saga/conf:go_default_library",
"//app/tool/saga/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/hbase.v2:go_default_library",
"//library/database/orm:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
"//vendor/github.com/tsuna/gohbase/hrpc:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = [
"dao_test.go",
"hbase_test.go",
"lock_test.go",
"redis_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/tool/saga/conf:go_default_library",
"//app/tool/saga/model:go_default_library",
"//library/cache/redis:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey: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"],
)

84
app/tool/saga/dao/dao.go Normal file
View File

@@ -0,0 +1,84 @@
package dao
import (
"bytes"
"context"
"encoding/json"
"net/http"
"time"
"go-common/app/tool/saga/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/hbase.v2"
"go-common/library/database/orm"
bm "go-common/library/net/http/blademaster"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
// Dao def
type Dao struct {
// cache
httpClient *bm.Client
mysql *gorm.DB
mcMR *memcache.Pool
redis *redis.Pool
hbase *hbase.Client
mcMRRecordExpire int32
}
// New create instance of Dao
func New() (d *Dao) {
d = &Dao{
httpClient: bm.NewClient(conf.Conf.HTTPClient),
mysql: orm.NewMySQL(conf.Conf.ORM),
mcMR: memcache.NewPool(conf.Conf.Memcache.MR),
redis: redis.NewPool(conf.Conf.Redis),
hbase: hbase.NewClient(conf.Conf.HBase.Config),
mcMRRecordExpire: int32(time.Duration(conf.Conf.Memcache.MRRecordExpire) / time.Second),
}
return
}
// Ping dao.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.pingRedis(c); err != nil {
return
}
if err = d.pingMC(c); err != nil {
return
}
return d.mysql.DB().Ping()
}
// Close dao.
func (d *Dao) Close() {
if d.mcMR != nil {
d.mcMR.Close()
}
if d.redis != nil {
d.redis.Close()
}
if d.mysql != nil {
d.mysql.Close()
}
if d.hbase != nil {
d.hbase.Close()
}
}
func (d *Dao) newRequest(method, url string, v interface{}) (req *http.Request, err error) {
body := &bytes.Buffer{}
if method != http.MethodGet {
if err = json.NewEncoder(body).Encode(v); err != nil {
err = errors.WithStack(err)
return
}
}
if req, err = http.NewRequest(method, url, body); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,38 @@
package dao
import (
"context"
"flag"
"os"
"testing"
"go-common/app/tool/saga/conf"
)
var (
d *Dao
ctx = context.Background()
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "test.ep.saga")
flag.Set("conf_token", "1d10044ab80b21d37ea67445f0475237")
flag.Set("tree_id", "56733")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "fat")
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/saga-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New()
defer d.Close()
os.Exit(m.Run())
}

View File

@@ -0,0 +1,88 @@
package dao
import (
"regexp"
"strings"
"go-common/app/tool/saga/model"
"go-common/library/log"
"github.com/pkg/errors"
pkgerr "github.com/pkg/errors"
)
var (
regUserID = regexp.MustCompile(`^\d+$`)
)
// QueryUserByUserName query user by user name
func (d *Dao) QueryUserByUserName(userName string) (contactInfo *model.ContactInfo, err error) {
contactInfo = &model.ContactInfo{}
err = pkgerr.WithStack(d.mysql.Where(&model.ContactInfo{UserName: userName}).First(contactInfo).Error)
return
}
// QueryUserByID query user by user ID
func (d *Dao) QueryUserByID(userID string) (contactInfo *model.ContactInfo, err error) {
contactInfo = &model.ContactInfo{}
err = pkgerr.WithStack(d.mysql.Where(&model.ContactInfo{UserID: userID}).First(contactInfo).Error)
return
}
// UserIds query user ids for the user names
func (d *Dao) UserIds(userNames []string) (userIds string, err error) {
var (
userName string
ids []string
contactInfo *model.ContactInfo
)
if len(userNames) == 0 {
err = errors.Errorf("UserIds: userNames is empty!")
return
}
for _, userName = range userNames {
if contactInfo, err = d.QueryUserByUserName(userName); err != nil {
log.Error("UserIds: no such user (%s) in db, err (%s)", userName, err.Error())
}
log.Info("UserIds: username (%s), userid (%s)", userName, contactInfo.UserID)
if contactInfo.UserID != "" && regUserID.MatchString(contactInfo.UserID) {
ids = append(ids, contactInfo.UserID)
}
}
if len(ids) > 0 {
userIds = strings.Join(ids, "|")
err = nil
} else {
err = errors.Wrapf(err, "UserIds: failed to find all the users in db, what a pity!")
}
return
}
// ContactInfos query all the records in contact_infos
func (d *Dao) ContactInfos() (contactInfos []*model.ContactInfo, err error) {
err = pkgerr.WithStack(d.mysql.Find(&contactInfos).Error)
return
}
// CreateContact create contact info record
func (d *Dao) CreateContact(contact *model.ContactInfo) (err error) {
err = pkgerr.WithStack(d.mysql.Create(contact).Error)
return
}
// DelContact delete the contact info with the specified UserID
func (d *Dao) DelContact(contact *model.ContactInfo) (err error) {
err = pkgerr.WithStack(d.mysql.Delete(contact).Error)
return
}
// UptContact update the contact information
func (d *Dao) UptContact(contact *model.ContactInfo) (err error) {
err = pkgerr.WithStack(d.mysql.Model(&model.ContactInfo{}).Where(&model.ContactInfo{UserID: contact.UserID}).Updates(*contact).Error)
return
}

105
app/tool/saga/dao/hbase.go Normal file
View File

@@ -0,0 +1,105 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"time"
"go-common/app/tool/saga/conf"
"go-common/library/log"
"github.com/pkg/errors"
"github.com/tsuna/gohbase/hrpc"
)
const (
_sagaTable = "ep:saga"
_ColFamily = "saga_auth"
_cSagaPathOwner = "path_owner"
_cSagaPathReviewer = "path_reviewer"
)
// sagaAuthKey ...
func sagaAuthKey(projID int, branch string, path string) string {
return fmt.Sprintf("saga_auth_%d_%s_%s", projID, branch, path)
}
// SetPathAuthH ...
func (d *Dao) SetPathAuthH(c context.Context, projID int, branch string, path string, owners []string, reviewers []string) (err error) {
var (
key = sagaAuthKey(projID, branch, path)
auth = make(map[string][]byte)
bOwner []byte
bReviewer []byte
)
if bOwner, err = json.Marshal(owners); err != nil {
return errors.WithStack(err)
}
if bReviewer, err = json.Marshal(reviewers); err != nil {
return errors.WithStack(err)
}
auth[_cSagaPathOwner] = bOwner
auth[_cSagaPathReviewer] = bReviewer
values := map[string]map[string][]byte{_ColFamily: auth}
ctx, cancel := context.WithTimeout(c, time.Duration(conf.Conf.HBase.WriteTimeout))
defer cancel()
if _, err = d.hbase.PutStr(ctx, _sagaTable, key, values); err != nil {
return errors.Wrapf(err, "hbase PutStr error (key: %s values: %v)", key, values)
}
return
}
// PathAuthH ...
func (d *Dao) PathAuthH(ctx context.Context, projID int, branch string, path string) (owners []string, reviewers []string, err error) {
var (
key = sagaAuthKey(projID, branch, path)
result *hrpc.Result
)
ctx, cancel := context.WithTimeout(ctx, time.Duration(conf.Conf.HBase.ReadTimeout))
defer cancel()
if result, err = d.hbase.GetStr(ctx, _sagaTable, key); err != nil {
err = errors.Wrapf(err, "hbase GetStr error (key: %s)", key)
return
}
for _, c := range result.Cells {
switch string(c.Qualifier) {
case _cSagaPathOwner:
if err = json.Unmarshal(c.Value, &owners); err != nil {
err = errors.WithStack(err)
return
}
log.Info("Get key: (%s), owners Info: (%+v)", key, owners)
case _cSagaPathReviewer:
if err = json.Unmarshal(c.Value, &reviewers); err != nil {
err = errors.WithStack(err)
return
}
log.Info("Get key: (%s), reviewers Info: (%+v)", key, reviewers)
}
}
return
}
// DeletePathAuthH ...
func (d *Dao) DeletePathAuthH(c context.Context, projID int, branch string, path string) (err error) {
key := sagaAuthKey(projID, branch, path)
ctx, cancel := context.WithTimeout(c, time.Duration(conf.Conf.HBase.WriteTimeout))
defer cancel()
auth := make(map[string][]byte)
auth[_cSagaPathOwner] = nil
auth[_cSagaPathReviewer] = nil
values := map[string]map[string][]byte{_ColFamily: auth}
if _, err = d.hbase.Delete(ctx, _sagaTable, key, values); err != nil {
err = errors.Wrapf(err, "hbase delete error (key: %s)", key)
}
return
}

View File

@@ -0,0 +1,133 @@
package dao
import (
"context"
"fmt"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSagaAuthKey(t *testing.T) {
convey.Convey("sagaAuthKey", t, func(ctx convey.C) {
var (
projID = int(111)
branch = "test"
path = "."
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := sagaAuthKey(projID, branch, path)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_auth_111_test_.")
})
})
})
}
func TestDaoSetPathAuthH(t *testing.T) {
convey.Convey("SetPathAuthH", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(111)
branch = "master"
path = "."
owners = []string{"zhanglin", "wuwei"}
reviewers = []string{"tangyongqiang", "changhengyuan"}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetPathAuthH(c, projID, branch, path, owners, reviewers)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoPathAuthH(t *testing.T) {
convey.Convey("PathAuthH", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(111)
branch = "master"
path = "."
owner = []string{"zhanglin", "wuwei"}
reviewer = []string{"tangyongqiang", "changhengyuan"}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
owners, reviewers, err := d.PathAuthH(c, projID, branch, path)
ctx.Convey("Then err should be nil.owners,reviewers should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(fmt.Sprint(reviewers), convey.ShouldEqual, fmt.Sprint(reviewer))
ctx.So(fmt.Sprint(owners), convey.ShouldEqual, fmt.Sprint(owner))
})
})
})
}
func TestDaoDeletePathAuthH(t *testing.T) {
convey.Convey("DeletePathAuthH", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(111)
branch = "master"
path = "."
owners = []string{"zhanglin", "wuwei"}
reviewers = []string{"tangyongqiang", "changhengyuan"}
path2 = "test"
owners2 = []string{"zhang", "wu"}
reviewers2 = []string{"tang", "chang"}
)
ctx.Convey("When data not exist", func(ctx convey.C) {
err := d.DeletePathAuthH(c, projID, branch, path)
ctx.Convey("delete err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("When data exist", func(ctx convey.C) {
err := d.SetPathAuthH(c, projID, branch, path, owners, reviewers)
ctx.Convey("save path auth.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
err = d.SetPathAuthH(c, projID, branch, path2, owners2, reviewers2)
ctx.Convey("save path auth 2.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
os, rs, err := d.PathAuthH(c, projID, branch, path)
ctx.Convey("get path auth", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(fmt.Sprint(rs), convey.ShouldEqual, fmt.Sprint(reviewers))
ctx.So(fmt.Sprint(os), convey.ShouldEqual, fmt.Sprint(owners))
})
os, rs, err = d.PathAuthH(c, projID, branch, path2)
ctx.Convey("get path auth 2.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(fmt.Sprint(rs), convey.ShouldEqual, fmt.Sprint(reviewers2))
ctx.So(fmt.Sprint(os), convey.ShouldEqual, fmt.Sprint(owners2))
})
err = d.DeletePathAuthH(c, projID, branch, path)
ctx.Convey("delete auth path.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
os, rs, err = d.PathAuthH(c, projID, branch, path)
ctx.Convey("get again path auth.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(fmt.Sprint(rs), convey.ShouldEqual, "[]")
ctx.So(fmt.Sprint(os), convey.ShouldEqual, "[]")
ctx.So(len(rs), convey.ShouldEqual, 0)
ctx.So(len(os), convey.ShouldEqual, 0)
})
os, rs, err = d.PathAuthH(c, projID, branch, path2)
ctx.Convey("get again path auth 2.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(fmt.Sprint(rs), convey.ShouldEqual, fmt.Sprint(reviewers2))
ctx.So(fmt.Sprint(os), convey.ShouldEqual, fmt.Sprint(owners2))
})
})
})
}

188
app/tool/saga/dao/http.go Normal file
View File

@@ -0,0 +1,188 @@
package dao
import (
"bytes"
"context"
"encoding/json"
"fmt"
xhttp "net/http"
"net/url"
"strconv"
"go-common/app/tool/saga/model"
"github.com/pkg/errors"
)
const (
qyWechatURL = "https://qyapi.weixin.qq.com"
corpID = "wx0833ac9926284fa5" // 企业微信Bilibili的企业ID
departmentID = "12" // 公司统一用部门ID
)
// WechatPushMsg wechat push text message to specified user
func (d *Dao) WechatPushMsg(c context.Context, token string, txtMsg *model.TxtNotification) (invalidUser string, err error) {
var (
u string
params = url.Values{}
res struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
InvalidUser string `json:"invaliduser"`
InvalidParty string `json:"invalidparty"`
InvalidTag string `json:"invalidtag"`
}
)
u = qyWechatURL + "/cgi-bin/message/send"
params.Set("access_token", token)
if err = d.PostJSON(c, u, "", params, &res, txtMsg); err != nil {
return
}
if res.ErrCode != 0 || res.InvalidUser != "" || res.InvalidParty != "" || res.InvalidTag != "" {
invalidUser = res.InvalidUser
err = errors.Errorf("WechatPushMsg: errcode: %d, errmsg: %s, invalidUser: %s, invalidParty: %s, invalidTag: %s",
res.ErrCode, res.ErrMsg, res.InvalidUser, res.InvalidParty, res.InvalidTag)
return
}
return
}
// PostJSON post http request with json params.
func (d *Dao) PostJSON(c context.Context, uri, ip string, params url.Values, res interface{}, v interface{}) (err error) {
var (
body = &bytes.Buffer{}
req *xhttp.Request
url string
en string
)
if err = json.NewEncoder(body).Encode(v); err != nil {
return
}
url = uri
if en = params.Encode(); en != "" {
url += "?" + en
}
if req, err = xhttp.NewRequest(xhttp.MethodPost, url, body); err != nil {
return
}
if err = d.httpClient.Do(c, req, &res); err != nil {
return
}
return
}
// WechatAccessToken query access token with the specified secret
func (d *Dao) WechatAccessToken(c context.Context, secret string) (token string, expire int32, err error) {
var (
u string
params = url.Values{}
res struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
AccessToken string `json:"access_token"`
ExpiresIn int32 `json:"expires_in"`
}
)
u = qyWechatURL + "/cgi-bin/gettoken"
params.Set("corpid", corpID)
params.Set("corpsecret", secret)
if err = d.httpClient.Get(c, u, "", params, &res); err != nil {
return
}
if res.ErrCode != 0 {
err = errors.Errorf("WechatAccessToken: errcode: %d, errmsg: %s", res.ErrCode, res.ErrMsg)
return
}
token = res.AccessToken
expire = res.ExpiresIn
return
}
// WechatContacts query all the contacts
func (d *Dao) WechatContacts(c context.Context, accessToken string) (contacts []*model.ContactInfo, err error) {
var (
u string
params = url.Values{}
res struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
UserList []*model.ContactInfo `json:"userlist"`
}
)
u = qyWechatURL + "/cgi-bin/user/list"
params.Set("access_token", accessToken)
params.Set("department_id", departmentID)
params.Set("fetch_child", "1")
if err = d.httpClient.Get(c, u, "", params, &res); err != nil {
return
}
if res.ErrCode != 0 {
err = errors.Errorf("WechatContacts: errcode: %d, errmsg: %s", res.ErrCode, res.ErrMsg)
return
}
contacts = res.UserList
return
}
// WechatSagaVisible get all the user ids who can visiable saga
func (d *Dao) WechatSagaVisible(c context.Context, accessToken string, agentID int) (users []*model.UserInfo, err error) {
var (
u string
params = url.Values{}
res struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
VisibleUsers model.AllowUserInfo `json:"allow_userinfos"`
}
)
u = qyWechatURL + "/cgi-bin/agent/get"
params.Set("access_token", accessToken)
params.Set("agentid", strconv.Itoa(agentID))
if err = d.httpClient.Get(c, u, "", params, &res); err != nil {
return
}
if res.ErrCode != 0 {
err = errors.Errorf("WechatSagaVisible: errcode: %d, errmsg: %s", res.ErrCode, res.ErrMsg)
return
}
users = res.VisibleUsers.Users
return
}
// RepoFiles ...TODO 该方法放在gitlab里比较好
func (d *Dao) RepoFiles(c context.Context, Host string, token string, repo *model.RepoInfo) (files []string, err error) {
var (
u string
req *xhttp.Request
)
u = fmt.Sprintf("http://%s/%s/%s/files/%s?format=json", Host, repo.Group, repo.Name, repo.Branch)
if req, err = d.newRequest("GET", u, nil); err != nil {
return
}
req.Header.Set("PRIVATE-TOKEN", token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
if err = d.httpClient.Do(c, req, &files); err != nil {
return
}
return
}

31
app/tool/saga/dao/lock.go Normal file
View File

@@ -0,0 +1,31 @@
package dao
import (
"context"
"go-common/library/cache/redis"
"go-common/library/log"
)
//TryLock ...
func (d *Dao) TryLock(c context.Context, key string, value string, timeout int) (ok bool, err error) {
var conn = d.redis.Get(c)
defer conn.Close()
_, err = redis.String(conn.Do("SET", key, value, "EX", timeout, "NX"))
if err == redis.ErrNil {
log.Info("TryLock redis key(%s) is ErrNil!", key)
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// UnLock ...
func (d *Dao) UnLock(c context.Context, key string) (err error) {
var conn = d.redis.Get(c)
defer conn.Close()
_, err = conn.Do("DEL", key)
return
}

View File

@@ -0,0 +1,35 @@
package dao
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestLock(t *testing.T) {
var (
key string
ok bool
err error
)
Convey("TEST Lock", t, func() {
ok, err = d.TryLock(ctx, key, "test", 1)
So(err, ShouldBeNil)
So(ok, ShouldBeTrue)
ok, err = d.TryLock(ctx, key, "test", 1)
So(err, ShouldBeNil)
So(ok, ShouldBeFalse)
err = d.UnLock(ctx, key)
So(err, ShouldBeNil)
ok, err = d.TryLock(ctx, key, "test", 1)
So(err, ShouldBeNil)
So(ok, ShouldBeTrue)
ok, err = d.TryLock(ctx, key, "test", 1)
So(err, ShouldBeNil)
So(ok, ShouldBeFalse)
})
}

181
app/tool/saga/dao/mc.go Normal file
View File

@@ -0,0 +1,181 @@
package dao
import (
"context"
"fmt"
"go-common/app/tool/saga/model"
"go-common/library/cache/memcache"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
requiredViableUsersKey = "saga_wechat_require_visible_users_key"
)
func (d *Dao) pingMC(c context.Context) (err error) {
conn := d.mcMR.Get(c)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 0}); err != nil {
err = errors.Wrap(err, "conn.Store(set,ping,1)")
}
return
}
func mrRecordKey(mrID int) string {
return fmt.Sprintf("saga_mr_%d", mrID)
}
// MRRecordCache get MRRecord from mc
func (d *Dao) MRRecordCache(c context.Context, mrID int) (record *model.MRRecord, err error) {
var (
key = mrRecordKey(mrID)
conn = d.mcMR.Get(c)
reply *memcache.Item
)
defer conn.Close()
reply, err = conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(get,%s)", key)
return
}
record = &model.MRRecord{}
if err = conn.Scan(reply, record); err != nil {
err = errors.Wrapf(err, "reply.Scan(%s)", string(reply.Value))
}
return
}
// SetMRRecordCache set MRRecord to mc
func (d *Dao) SetMRRecordCache(c context.Context, record *model.MRRecord) (err error) {
var (
key = mrRecordKey(record.MRID)
conn = d.mcMR.Get(c)
)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: key, Object: record, Expiration: 0, Flags: memcache.FlagJSON}); err != nil {
err = errors.Wrapf(err, "conn.Add(%s,%v)", key, record)
return
}
return
}
func weixinTokenKey(key string) string {
return fmt.Sprintf("saga_weixin_token_%s", key)
}
// AccessToken get access token from mc
func (d *Dao) AccessToken(c context.Context, key string) (token string, err error) {
var (
wkey = weixinTokenKey(key)
conn = d.mcMR.Get(c)
reply *memcache.Item
)
defer conn.Close()
reply, err = conn.Get(wkey)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(get,%s)", wkey)
return
}
if err = conn.Scan(reply, &token); err != nil {
err = errors.Wrapf(err, "reply.Scan(%s)", string(reply.Value))
}
return
}
// SetAccessToken set the access token to mc
func (d *Dao) SetAccessToken(c context.Context, key string, token string, expire int32) (err error) {
var (
wkey = weixinTokenKey(key)
conn = d.mcMR.Get(c)
item *memcache.Item
)
defer conn.Close()
item = &memcache.Item{Key: wkey, Object: token, Expiration: expire, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "conn.Add(%s,%v)", wkey, token)
return
}
return
}
// RequireVisibleUsers get wechat require visible users from memcache
func (d *Dao) RequireVisibleUsers(c context.Context, userMap *map[string]model.RequireVisibleUser) (err error) {
var (
conn = d.mcMR.Get(c)
reply *memcache.Item
)
defer conn.Close()
reply, err = conn.Get(requiredViableUsersKey)
if err != nil {
if err == memcache.ErrNotFound {
log.Info("no such key (%s) in cache, err (%s)", requiredViableUsersKey, err.Error())
err = nil
}
return
}
if err = conn.Scan(reply, userMap); err != nil {
err = errors.Wrapf(err, "reply.Scan(%s)", string(reply.Value))
}
return
}
// SetRequireVisibleUsers set wechat require visible users to memcache
func (d *Dao) SetRequireVisibleUsers(c context.Context, contactInfo *model.ContactInfo) (err error) {
var (
conn = d.mcMR.Get(c)
item *memcache.Item
userMap = make(map[string]model.RequireVisibleUser)
)
defer conn.Close()
if err = d.RequireVisibleUsers(c, &userMap); err != nil {
log.Error("get require visible user error(%v)", err)
return
}
user := model.RequireVisibleUser{
UserName: contactInfo.UserName,
NickName: contactInfo.NickName,
}
userMap[contactInfo.UserID] = user
item = &memcache.Item{Key: requiredViableUsersKey, Object: userMap, Expiration: 0, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "conn.Set(%s,%v)", requiredViableUsersKey, userMap)
return
}
return
}
// DeleteRequireVisibleUsers delete the wechat require visible key in memcache
func (d *Dao) DeleteRequireVisibleUsers(c context.Context) (err error) {
var (
conn = d.mcMR.Get(c)
)
defer conn.Close()
err = conn.Delete(requiredViableUsersKey)
if err != nil {
err = errors.Wrapf(err, "conn.Delete(%s)", requiredViableUsersKey)
}
return
}

465
app/tool/saga/dao/redis.go Normal file
View File

@@ -0,0 +1,465 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/tool/saga/model"
"go-common/library/cache/redis"
"github.com/pkg/errors"
)
func mergeTaskKey(taskType int) string {
return fmt.Sprintf("saga_task_%d", taskType)
}
func mrIIDKey(mrIID int) string {
return fmt.Sprintf("saga_mrIID_%d", mrIID)
}
func (d *Dao) pingRedis(c context.Context) (err error) {
conn := d.redis.Get(c)
_, err = conn.Do("SET", "PING", "PONG")
conn.Close()
return
}
// AddMRIID ...
func (d *Dao) AddMRIID(c context.Context, mrIID int, expire int) (err error) {
var (
key = mrIIDKey(mrIID)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("SET", key, mrIID); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
if _, err = conn.Do("EXPIRE", key, expire); err != nil {
return
}
return
}
// ExistMRIID ...
func (d *Dao) ExistMRIID(c context.Context, mrIID int) (ok bool, err error) {
var (
key = mrIIDKey(mrIID)
conn = d.redis.Get(c)
)
defer conn.Close()
if _, err = redis.Int(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
}
return false, err
}
return true, nil
}
// DeleteMRIID ...
func (d *Dao) DeleteMRIID(c context.Context, mrIID int) (err error) {
var (
key = mrIIDKey(mrIID)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// PushMergeTask ...
func (d *Dao) PushMergeTask(c context.Context, taskType int, taskInfo *model.TaskInfo) (err error) {
var (
key = mergeTaskKey(taskType)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = json.Marshal(taskInfo); err != nil {
err = errors.WithStack(err)
return
}
if err = conn.Send("LPUSH", key, bs); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// DeleteMergeTask ...
func (d *Dao) DeleteMergeTask(c context.Context, taskType int, taskInfo *model.TaskInfo) (err error) {
var (
key = mergeTaskKey(taskType)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = json.Marshal(taskInfo); err != nil {
err = errors.WithStack(err)
return
}
if err = conn.Send("LREM", key, 0, bs); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// MergeTasks ...
func (d *Dao) MergeTasks(c context.Context, taskType int) (count int, taskInfos []*model.TaskInfo, err error) {
var (
key = mergeTaskKey(taskType)
values [][]byte
conn = d.redis.Get(c)
)
defer conn.Close()
if count, err = redis.Int(conn.Do("LLEN", key)); err != nil {
return
}
if values, err = redis.ByteSlices(conn.Do("LRANGE", key, 0, -1)); err != nil {
if err == redis.ErrNil {
err = nil
}
return
}
taskInfos = make([]*model.TaskInfo, 0, count)
for _, value := range values {
taskInfo := &model.TaskInfo{}
if err = json.Unmarshal(value, &taskInfo); err != nil {
err = errors.WithStack(err)
return
}
taskInfos = append(taskInfos, taskInfo)
//taskInfos = append([]*model.TaskInfo{taskInfo}, taskInfos...)
}
return
}
func mergeInfoKey(projID int, branch string) string {
return fmt.Sprintf("saga_mergeInfo_%d_%s", projID, branch)
}
func pathOwnerKey(projID int, branch string, path string) string {
return fmt.Sprintf("saga_PathOwner_%d_%s_%s", projID, branch, path)
}
func pathReviewerKey(projID int, branch string, path string) string {
return fmt.Sprintf("saga_PathReviewer_%d_%s_%s", projID, branch, path)
}
func authInfoKey(projID int, mrIID int) string {
return fmt.Sprintf("saga_auth_%d_%d", projID, mrIID)
}
// SetMergeInfo ...
func (d *Dao) SetMergeInfo(c context.Context, projID int, branch string, mergeInfo *model.MergeInfo) (err error) {
var (
key = mergeInfoKey(projID, branch)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = json.Marshal(mergeInfo); err != nil {
err = errors.WithStack(err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// MergeInfo ...
func (d *Dao) MergeInfo(c context.Context, projID int, branch string) (ok bool, mergeInfo *model.MergeInfo, err error) {
var (
key = mergeInfoKey(projID, branch)
value []byte
conn = d.redis.Get(c)
)
defer conn.Close()
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
}
return
}
mergeInfo = &model.MergeInfo{}
if err = json.Unmarshal(value, &mergeInfo); err != nil {
err = errors.WithStack(err)
return
}
ok = true
return
}
// DeleteMergeInfo ...
func (d *Dao) DeleteMergeInfo(c context.Context, projID int, branch string) (err error) {
var (
key = mergeInfoKey(projID, branch)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// SetPathOwner ...
func (d *Dao) SetPathOwner(c context.Context, projID int, branch string, path string, owners []string) (err error) {
var (
key = pathOwnerKey(projID, branch, path)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = json.Marshal(owners); err != nil {
err = errors.WithStack(err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// PathOwner ...
func (d *Dao) PathOwner(c context.Context, projID int, branch string, path string) (owners []string, err error) {
var (
key = pathOwnerKey(projID, branch, path)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
}
return
}
if err = json.Unmarshal(bs, &owners); err != nil {
err = errors.WithStack(err)
return
}
return
}
// SetPathReviewer ...
func (d *Dao) SetPathReviewer(c context.Context, projID int, branch string, path string, reviewers []string) (err error) {
var (
key = pathReviewerKey(projID, branch, path)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = json.Marshal(reviewers); err != nil {
return errors.WithStack(err)
}
if err = conn.Send("SET", key, bs); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// PathReviewer ...
func (d *Dao) PathReviewer(c context.Context, projID int, branch string, path string) (reviewers []string, err error) {
var (
key = pathReviewerKey(projID, branch, path)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
}
return
}
if err = json.Unmarshal(bs, &reviewers); err != nil {
err = errors.WithStack(err)
return
}
return
}
// pathAuthKey ...
func pathAuthKey(projID int, branch string, path string) string {
return fmt.Sprintf("saga_path_auth_%d_%s_%s", projID, branch, path)
}
// PathAuthR ...
func (d *Dao) PathAuthR(c context.Context, projID int, branch string, path string) (authUsers *model.AuthUsers, err error) {
var (
key = pathAuthKey(projID, branch, path)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
}
return
}
authUsers = new(model.AuthUsers)
if err = json.Unmarshal(bs, authUsers); err != nil {
err = errors.WithStack(err)
return
}
return
}
// SetPathAuthR ...
func (d *Dao) SetPathAuthR(c context.Context, projID int, branch string, path string, authUsers *model.AuthUsers) (err error) {
var (
key = pathAuthKey(projID, branch, path)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = json.Marshal(authUsers); err != nil {
return errors.WithStack(err)
}
if err = conn.Send("SET", key, bs); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// DeletePathAuthR ...
func (d *Dao) DeletePathAuthR(c context.Context, projID int, branch string, path string) (err error) {
var (
key = pathAuthKey(projID, branch, path)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// SetReportStatus ...
func (d *Dao) SetReportStatus(c context.Context, projID int, mrIID int, result bool) (err error) {
var (
key = authInfoKey(projID, mrIID)
conn = d.redis.Get(c)
bs []byte
)
defer conn.Close()
if bs, err = json.Marshal(result); err != nil {
return errors.WithStack(err)
}
if err = conn.Send("SET", key, bs); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}
// ReportStatus ...
func (d *Dao) ReportStatus(c context.Context, projID int, mrIID int) (result bool, err error) {
var (
key = authInfoKey(projID, mrIID)
value []byte
conn = d.redis.Get(c)
)
defer conn.Close()
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
}
return
}
if err = json.Unmarshal(value, &result); err != nil {
err = errors.WithStack(err)
return
}
return
}
// DeleteReportStatus ...
func (d *Dao) DeleteReportStatus(c context.Context, projID int, mrIID int) (err error) {
var (
key = authInfoKey(projID, mrIID)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
if _, err = conn.Receive(); err != nil {
return
}
return
}

View File

@@ -0,0 +1,475 @@
package dao
import (
"context"
"encoding/json"
"testing"
"go-common/app/tool/saga/model"
"go-common/library/cache/redis"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoMergeTaskKey(t *testing.T) {
convey.Convey("mergeTaskKey", t, func(ctx convey.C) {
var (
taskType = int(111)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := mergeTaskKey(taskType)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_task_111")
})
})
})
}
func TestDaoMrIIDKey(t *testing.T) {
convey.Convey("mrIIDKey", t, func(ctx convey.C) {
var (
mrIID = int(222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := mrIIDKey(mrIID)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_mrIID_222")
})
})
})
}
func TestDaoPingRedis(t *testing.T) {
convey.Convey("pingRedis", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.pingRedis(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddMRIID(t *testing.T) {
convey.Convey("AddMRIID", t, func(ctx convey.C) {
var (
c = context.Background()
mrIID = int(333)
expire = int(1800)
conn = d.redis.Get(c)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddMRIID(c, mrIID, expire)
mrID, err := redis.Int(conn.Do("GET", "saga_mrIID_333"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
// 检查redis存储结果
ctx.So(mrID, convey.ShouldEqual, mrIID)
})
})
})
}
func TestDaoExistMRIID(t *testing.T) {
convey.Convey("ExistMRIID", t, func(ctx convey.C) {
var (
c = context.Background()
mrIID = int(444)
conn = d.redis.Get(c)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
conn.Do("DEL", "saga_mrIID_444")
ok, err := d.ExistMRIID(c, mrIID)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ok, convey.ShouldBeFalse)
})
})
ctx.Convey("When MRIID exist", func(ctx convey.C) {
conn.Do("SET", "saga_mrIID_444", 1)
ok, err := d.ExistMRIID(c, mrIID)
ctx.Convey("Then ok should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ok, convey.ShouldBeTrue)
})
})
})
}
func TestDaoDeleteMRIID(t *testing.T) {
convey.Convey("DeleteMRIID", t, func(ctx convey.C) {
var (
c = context.Background()
mrIID = int(555)
conn = d.redis.Get(c)
)
ctx.Convey("When data not exist", func(ctx convey.C) {
err := d.DeleteMRIID(c, mrIID)
value, _ := redis.Int(conn.Do("GET", "saga_mrIID_555"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, 0)
})
})
ctx.Convey("When data exist", func(ctx convey.C) {
redis.String(conn.Do("SET", "saga_mrIID_555", "Test"))
err := d.DeleteMRIID(c, mrIID)
value, _ := redis.Int(conn.Do("GET", "saga_mrIID_555"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, 0)
})
})
})
}
func TestDaoPushMergeTask(t *testing.T) {
convey.Convey("PushMergeTask", t, func(ctx convey.C) {
var (
c = context.Background()
taskType = int(666)
taskInfo = &model.TaskInfo{NoteID: 111, Event: nil, Repo: nil}
conn = d.redis.Get(c)
)
bs, _ := json.Marshal(taskInfo)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.PushMergeTask(c, taskType, taskInfo)
value, _ := redis.Bytes(conn.Do("LPOP", "saga_task_666"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
// push 运行函数 pop 检验结果
ctx.So(string(value), convey.ShouldEqual, string(bs))
})
})
})
}
func TestDaoDeleteMergeTask(t *testing.T) {
convey.Convey("DeleteMergeTask", t, func(ctx convey.C) {
var (
c = context.Background()
taskType = int(777)
taskInfo = &model.TaskInfo{NoteID: 777, Event: nil, Repo: nil}
conn = d.redis.Get(c)
)
ctx.Convey("When data is not exist", func(ctx convey.C) {
err := d.DeleteMergeTask(c, taskType, taskInfo)
value, _ := redis.Int(conn.Do("LPOP", "saga_task_777"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, 0)
})
})
ctx.Convey("When data is exist", func(ctx convey.C) {
taskInfoJSON, _ := json.Marshal(taskInfo)
redis.String(conn.Do("LPUSH", "saga_task_777", taskInfoJSON))
err := d.DeleteMergeTask(c, taskType, taskInfo)
value, _ := redis.Int(conn.Do("LPOP", "saga_task_777"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, 0)
})
})
})
}
func TestDaoMergeTasks(t *testing.T) {
convey.Convey("MergeTasks", t, func(ctx convey.C) {
var (
c = context.Background()
taskType = int(888)
conn = d.redis.Get(c)
taskInfo = &model.TaskInfo{NoteID: 888, Event: nil, Repo: nil}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
taskInfoJSON, _ := json.Marshal(taskInfo)
conn.Do("LPUSH", "saga_task_888", taskInfoJSON)
count, taskInfos, err := d.MergeTasks(c, taskType)
taskInfoFirst, _ := json.Marshal(taskInfos[0])
ctx.Convey("Then err should be nil.count,taskInfos should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(string(taskInfoFirst), convey.ShouldEqual, string(taskInfoJSON))
ctx.So(count, convey.ShouldNotEqual, 0)
})
})
})
}
func TestDaoMergeInfoKey(t *testing.T) {
convey.Convey("mergeInfoKey", t, func(ctx convey.C) {
var (
projID = int(999)
branch = "test"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := mergeInfoKey(projID, branch)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_mergeInfo_999_test")
})
})
})
}
func TestDaoPathOwnerKey(t *testing.T) {
convey.Convey("pathOwnerKey", t, func(ctx convey.C) {
var (
projID = int(1111)
branch = "test"
path = "."
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := pathOwnerKey(projID, branch, path)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_PathOwner_1111_test_.")
})
})
})
}
func TestDaoPathReviewerKey(t *testing.T) {
convey.Convey("pathReviewerKey", t, func(ctx convey.C) {
var (
projID = int(2222)
branch = "test"
path = "."
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := pathReviewerKey(projID, branch, path)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_PathReviewer_2222_test_.")
})
})
})
}
func TestDaoAuthInfoKey(t *testing.T) {
convey.Convey("authInfoKey", t, func(ctx convey.C) {
var (
projID = int(3333)
mrIID = int(3333)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := authInfoKey(projID, mrIID)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_auth_3333_3333")
})
})
})
}
func TestDaoSetMergeInfo(t *testing.T) {
convey.Convey("SetMergeInfo", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(4444)
branch = "test"
mergeInfo = &model.MergeInfo{}
conn = d.redis.Get(c)
)
redis.String(conn.Do(""))
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetMergeInfo(c, projID, branch, mergeInfo)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoMergeInfo(t *testing.T) {
convey.Convey("MergeInfo", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(5555)
branch = "test"
conn = d.redis.Get(c)
info = []byte(`{"NoteID":111,"Event":null,"Repo":null}`)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
conn.Do("SET", "saga_mergeInfo_5555_test", info)
ok, mergeInfo, err := d.MergeInfo(c, projID, branch)
ctx.Convey("Then err should be nil.ok,mergeInfo should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(mergeInfo, convey.ShouldNotBeNil)
ctx.So(ok, convey.ShouldBeTrue)
})
})
})
}
func TestDaoDeleteMergeInfo(t *testing.T) {
convey.Convey("DeleteMergeInfo", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(6666)
branch = "test"
conn = d.redis.Get(c)
info = []byte(`{"NoteID":111,"Event":null,"Repo":null}`)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
conn.Do("SET", "saga_mergeInfo_6666_test", info)
err := d.DeleteMergeInfo(c, projID, branch)
value, _ := redis.Int(conn.Do("GET", "saga_mergeInfo_6666_test"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, 0)
})
})
})
}
func TestDaoPathAuthKey(t *testing.T) {
convey.Convey("pathAuthKey", t, func(ctx convey.C) {
var (
projID = int(7777)
branch = "test"
path = "."
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := pathAuthKey(projID, branch, path)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "saga_path_auth_7777_test_.")
})
})
})
}
func TestDaoPathAuthR(t *testing.T) {
convey.Convey("PathAuthR", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(8888)
branch = "test"
path = "."
conn = d.redis.Get(c)
)
redis.Int(conn.Do("SET", "saga_path_auth_8888_test_.", `{"Owners": ["c"]}`))
ctx.Convey("When everything goes positive", func(ctx convey.C) {
authUsers, err := d.PathAuthR(c, projID, branch, path)
authUsersJSON, _ := json.Marshal(authUsers)
ctx.Convey("Then err should be nil.authUsers should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(string(authUsersJSON), convey.ShouldEqual, `{"Owners":["c"],"Reviewers":null}`)
ctx.So(authUsers, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetPathAuthR(t *testing.T) {
convey.Convey("SetPathAuthR", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(9999)
branch = "test"
path = "."
authUsers = &model.AuthUsers{Owners: []string{"testOwner"}, Reviewers: []string{"testReviewers"}}
conn = d.redis.Get(c)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetPathAuthR(c, projID, branch, path, authUsers)
value, _ := redis.String(conn.Do("GET", "saga_path_auth_9999_test_."))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, `{"Owners":["testOwner"],"Reviewers":["testReviewers"]}`)
})
})
})
}
func TestDaoDeletePathAuthR(t *testing.T) {
convey.Convey("DeletePathAuthR", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(88)
branch = "test"
path = "."
authUsers = &model.AuthUsers{Owners: []string{"testOwner"}, Reviewers: []string{"testReviewers"}}
conn = d.redis.Get(c)
)
ctx.Convey("When data not exist", func(ctx convey.C) {
err := d.DeletePathAuthR(c, projID, branch, path)
value, _ := redis.String(conn.Do("GET", "saga_path_auth_88_test_."))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, "")
})
})
ctx.Convey("When data exist", func(ctx convey.C) {
err := d.SetPathAuthR(c, projID, branch, path, authUsers)
value, _ := redis.String(conn.Do("GET", "saga_path_auth_88_test_."))
ctx.Convey("Then err should be nil 1.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, `{"Owners":["testOwner"],"Reviewers":["testReviewers"]}`)
})
err = d.DeletePathAuthR(c, projID, branch, path)
value, _ = redis.String(conn.Do("GET", "saga_path_auth_88_test_."))
ctx.Convey("Then err should be nil 2.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, "")
})
})
})
}
func TestDaoSetReportStatus(t *testing.T) {
convey.Convey("SetReportStatus", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(11111)
mrIID = int(11111)
result bool
conn = d.redis.Get(c)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetReportStatus(c, projID, mrIID, result)
value, _ := redis.String(conn.Do("GET", "saga_auth_11111_11111"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, "false")
})
})
})
}
func TestDaoReportStatus(t *testing.T) {
convey.Convey("ReportStatus", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(22222)
mrIID = int(22222)
conn = d.redis.Get(c)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
conn.Do("SET", "saga_auth_22222_22222", "true")
result, err := d.ReportStatus(c, projID, mrIID)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldEqual, true)
})
})
})
}
func TestDaoDeleteReportStatus(t *testing.T) {
convey.Convey("DeleteReportStatus", t, func(ctx convey.C) {
var (
c = context.Background()
projID = int(33333)
mrIID = int(33333)
conn = d.redis.Get(c)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
conn.Do("SET", "saga_auth_33333_33333", "true")
err := d.DeleteReportStatus(c, projID, mrIID)
value, _ := redis.Int(conn.Do("GET", "saga_auth_33333_33333"))
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(value, convey.ShouldEqual, 0)
})
})
})
}