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,79 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"hbase.go",
"httpclient.go",
"infoc.go",
"monkey.go",
"mysql.go",
"rpc.go",
],
importpath = "go-common/app/job/main/creative/dao/weeklyhonor",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/up/util/hbaseutil:go_default_library",
"//app/interface/main/creative/model/weeklyhonor:go_default_library",
"//app/job/main/creative/conf:go_default_library",
"//app/service/main/archive/api/gorpc:go_default_library",
"//app/service/main/archive/model/archive:go_default_library",
"//app/service/main/up/api/v1:go_default_library",
"//library/database/hbase.v2:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/log/infoc:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/bouk/monkey:go_default_library",
"//vendor/github.com/tsuna/gohbase/hrpc: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"],
)
go_test(
name = "go_default_test",
srcs = [
"dao_test.go",
"hbase_test.go",
"httpclient_test.go",
"infoc_test.go",
"mysql_test.go",
"rpc_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/main/creative/model/weeklyhonor:go_default_library",
"//app/job/main/creative/conf:go_default_library",
"//app/service/main/up/api/v1:go_default_library",
"//library/database/hbase.v2:go_default_library",
"//vendor/github.com/bouk/monkey:go_default_library",
"//vendor/github.com/golang/mock/gomock:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/github.com/tsuna/gohbase/hrpc:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)

View File

@@ -0,0 +1,63 @@
package weeklyhonor
import (
"context"
"time"
"go-common/app/job/main/creative/conf"
arcrpc "go-common/app/service/main/archive/api/gorpc"
upgrpc "go-common/app/service/main/up/api/v1"
"go-common/library/database/hbase.v2"
"go-common/library/database/sql"
binfoc "go-common/library/log/infoc"
bm "go-common/library/net/http/blademaster"
)
// Dao is creative dao.
type Dao struct {
// config
c *conf.Config
// db
db *sql.DB
// httpClient
httpClient *bm.Client
// hbase
hbase *hbase.Client
hbaseTimeOut time.Duration
// rpc
arc *arcrpc.Service2
infoc *binfoc.Infoc
// grpc
upClient upgrpc.UpClient
}
// New init api url
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
db: sql.NewMySQL(c.DB.Creative),
httpClient: bm.NewClient(c.HTTPClient.Normal),
// hbase
hbase: hbase.NewClient(c.HBaseOld.Config),
hbaseTimeOut: time.Duration(time.Millisecond * 200),
arc: arcrpc.New2(c.ArchiveRPC),
infoc: binfoc.New(c.WeeklyHonorInfoc),
}
var err error
d.upClient, err = upgrpc.NewClient(c.UpGRPCClient)
if err != nil {
panic(err)
}
return
}
// Ping creativeDb
func (d *Dao) Ping(c context.Context) (err error) {
return d.pingMySQL(c)
}
// Close creativeDb
func (d *Dao) Close() (err error) {
_ = d.infoc.Close()
return d.db.Close()
}

View File

@@ -0,0 +1,54 @@
package weeklyhonor
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/job/main/creative/conf"
"github.com/golang/mock/gomock"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.creative-job")
flag.Set("conf_token", "43943fda0bb311e8865c66d44b23cda7")
flag.Set("tree_id", "16037")
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/creative-job.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)
d.httpClient.SetTransport(gock.DefaultTransport)
return r
}
func WithMock(t *testing.T, f func(controller *gomock.Controller)) func() {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
return func() {
f(ctrl)
}
}

View File

@@ -0,0 +1,63 @@
package weeklyhonor
import (
"context"
"strconv"
"go-common/app/admin/main/up/util/hbaseutil"
model "go-common/app/interface/main/creative/model/weeklyhonor"
"go-common/library/ecode"
"go-common/library/log"
"github.com/tsuna/gohbase/hrpc"
)
// reverse for string.
func reverseString(s string) string {
rs := []rune(s)
l := len(rs)
for f, t := 0, l-1; f < t; f, t = f+1, t-1 {
rs[f], rs[t] = rs[t], rs[f]
}
ns := string(rs)
if l < 10 {
for i := 0; i < 10-l; i++ {
ns = ns + "0"
}
}
return ns
}
func honorRowKey(id int64, date string) string {
idStr := strconv.FormatInt(id, 10)
s := reverseString(idStr) + date
return s
}
// HonorStat get up honor.
func (d *Dao) HonorStat(c context.Context, mid int64, date string) (stat *model.HonorStat, err error) {
var (
result *hrpc.Result
ctx, cancel = context.WithTimeout(c, d.hbaseTimeOut)
tableName = "up_honorary_weekly"
key = honorRowKey(mid, date)
)
defer cancel()
if result, err = d.hbase.GetStr(ctx, tableName, key); err != nil {
log.Error("HonorStat d.hbase.GetStr tableName(%s) mid(%d) key(%v) error(%v)", tableName, mid, key, err)
err = ecode.CreativeDataErr
return
}
if result == nil {
return
}
stat = new(model.HonorStat)
parser := hbaseutil.Parser{}
err = parser.Parse(result.Cells, &stat)
if err != nil {
log.Error("failed to parse hbase cells,tableName(%s) mid(%d) key(%v) stat(%+v) err(%v)", tableName, mid, key, stat, err)
return
}
log.Info("HonorStat d.hbase.GetStr tableName(%s) mid(%d) key(%v) stat(%+v)", tableName, mid, key, stat)
return
}

View File

@@ -0,0 +1,130 @@
package weeklyhonor
import (
"bytes"
"context"
"encoding/binary"
"reflect"
"testing"
"go-common/library/database/hbase.v2"
"github.com/bouk/monkey"
"github.com/smartystreets/goconvey/convey"
"github.com/tsuna/gohbase/hrpc"
)
func TestWeeklyhonorreverseString(t *testing.T) {
convey.Convey("reverseString", t, func(ctx convey.C) {
var (
s = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := reverseString(s)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, p1)
})
})
})
}
func TestWeeklyhonorhonorRowKey(t *testing.T) {
convey.Convey("honorRowKey", t, func(ctx convey.C) {
var (
id = int64(0)
date = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := honorRowKey(id, date)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, p1)
})
})
})
}
func TestWeeklyhonorHonorStat(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
date = "20181112"
val1 int32 = 500
val2 int32 = -2
cs = getMockCells(val1, val2)
)
guard := monkey.PatchInstanceMethod(reflect.TypeOf(d.hbase), "GetStr", func(_ *hbase.Client, _ context.Context, _, _ string, _ ...func(hrpc.Call) error) (*hrpc.Result, error) {
res := &hrpc.Result{
Cells: cs,
}
return res, nil
})
defer guard.Unpatch()
convey.Convey("honorStat", t, func() {
stat, err := d.HonorStat(c, mid, date)
convey.So(err, convey.ShouldBeNil)
convey.So(stat, convey.ShouldNotBeNil)
convey.So(stat.Play, convey.ShouldEqual, val1)
convey.So(stat.PlayInc, convey.ShouldEqual, val1)
convey.So(stat.Rank0, convey.ShouldEqual, val1)
convey.So(stat.FansInc, convey.ShouldEqual, val2)
})
}
func getMockCells(v1, v2 int32) []*hrpc.Cell {
s1 := make([]byte, 0)
buf1 := bytes.NewBuffer(s1)
s2 := make([]byte, 0)
buf2 := bytes.NewBuffer(s2)
binary.Write(buf1, binary.BigEndian, v1)
binary.Write(buf2, binary.BigEndian, v2)
cells := []*hrpc.Cell{
{
Qualifier: []byte("play"),
Value: buf1.Bytes(),
Family: []byte("f"),
},
{
Qualifier: []byte("play_last_w"),
Value: buf1.Bytes(),
Family: []byte("f"),
},
{
Qualifier: []byte("play_inc"),
Value: buf1.Bytes(),
Family: []byte("f"),
},
{
Qualifier: []byte("fans_inc"),
Value: buf2.Bytes(),
Family: []byte("f"),
},
{
Qualifier: []byte("rank168"),
Value: buf1.Bytes(),
Family: []byte("r"),
},
{
Qualifier: []byte("rank0"),
Value: buf1.Bytes(),
Family: []byte("r"),
},
{
Qualifier: []byte("rank1"),
Value: buf1.Bytes(),
Family: []byte("r"),
},
{
Qualifier: []byte("rank3"),
Value: buf1.Bytes(),
Family: []byte("r"),
},
{
Qualifier: []byte("rank4"),
Value: buf1.Bytes(),
Family: []byte("r"),
},
}
return cells
}

View File

@@ -0,0 +1,110 @@
package weeklyhonor
import (
"context"
"errors"
"fmt"
"net/url"
"time"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_title = "叮!你有一份荣誉周报待查收!"
_newYearTitle = "嘭~~~啪!你有一份荣誉周报待查收!"
_content = "这周的成就已达成,快进来瞅瞅吧~ #{周报传送门}{\"https://member.bilibili.com/studio/annyroal/upper-honor-weekly/my\"}"
_newYearContent = "这周的成就已达成,元气满满过新年~ #{周报传送门}{\"https://member.bilibili.com/studio/annyroal/upper-honor-weekly/my\"}"
_notifyDataType = "4" // 消息类型1、回复我的2、@我3、收到的爱4、业务通知
_notifyURL = "/api/notify/send.user.notify.do"
_notifyMC = "1_17_1"
_upMidsURL = "/x/internal/uper/list_up"
)
type newYear struct {
start, end time.Time
}
var (
ny = newYear{
start: time.Date(2019, 2, 3, 0, 0, 0, 0, time.Local),
end: time.Date(2019, 2, 24, 0, 0, 0, 0, time.Local),
}
)
type msgReply struct {
Code int `json:"code"`
Data *data `json:"data"`
}
type data struct {
TotalCount int `json:"total_count"`
ErrorCount int `json:"error_count"`
ErrorMidList []int64 `json:"error_mid_list"`
}
// SendNotify 发送站内信
func (d *Dao) SendNotify(c context.Context, mids []int64) (errMids []int64, err error) {
title, content := getTitleAndContent()
res := msgReply{}
params := url.Values{}
params.Set("mc", _notifyMC)
params.Set("title", title)
params.Set("data_type", _notifyDataType)
params.Set("context", content)
params.Set("mid_list", xstr.JoinInts(mids))
notifyURI := d.c.Host.Message + _notifyURL
if err = d.httpClient.Post(c, notifyURI, "", params, &res); err != nil {
log.Error("d.httpClient.Post(%s,%v,%d)", notifyURI, params, err)
return
}
if res.Code != 0 {
err = errors.New("code != 0")
log.Error("d.httpClient.Post(%s,%v,%v,%d)", notifyURI, params, err, res.Code)
}
if res.Data != nil {
errMids = res.Data.ErrorMidList
log.Info("SendNotify log total_count(%d) error_count(%d) error_mid_list(%v)", res.Data.TotalCount, res.Data.ErrorCount, res.Data.ErrorMidList)
}
return
}
func getTitleAndContent() (string, string) {
now := time.Now()
if now.After(ny.end) || now.Before(ny.start) {
return _title, _content
}
return _newYearTitle, _newYearContent
}
// Deprecated: use UpActivesList instead.
func (d *Dao) UpMids(c context.Context, size int, lastid int64, activeOnly bool) (mids []int64, newid int64, err error) {
res := &struct {
Code int `json:"code"`
Data *struct {
Result []int64 `json:"result"`
LastID int64 `json:"last_id"`
} `json:"data"`
}{}
params := url.Values{}
params.Set("size", fmt.Sprintf("%d", size))
params.Set("last_id", fmt.Sprintf("%d", lastid))
if activeOnly {
// filter by having archive within 180 days
params.Set("activity", "1,2,3")
}
midsURI := d.c.Host.API + _upMidsURL
if err = d.httpClient.Get(c, midsURI, "", params, &res); err != nil {
log.Error("d.httpClient.Get(%s,%v,%d)", midsURI+"?"+params.Encode(), params, err)
return
}
if res.Code != 0 {
err = errors.New("code != 0")
log.Error("d.httpClient.Get(%s,%v,%v,%d)", midsURI, params, err, res.Code)
}
if res != nil && res.Data != nil {
return res.Data.Result, res.Data.LastID, nil
}
return
}

View File

@@ -0,0 +1,45 @@
package weeklyhonor
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestWeeklyhonorSendNotify(t *testing.T) {
convey.Convey("SendNotify", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{11}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer gock.Off()
httpMock("POST", d.c.Host.Message+_notifyURL).Reply(200).JSON(`{"code":0,"data":{}}`)
_, err := d.SendNotify(c, mids)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, err)
})
})
})
}
func TestWeeklyhonorUpMids(t *testing.T) {
convey.Convey("UpMids", t, func(ctx convey.C) {
var (
c = context.Background()
size = int(0)
lastid = int64(0)
activeOnly bool
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
mids, newid, err := d.UpMids(c, size, lastid, activeOnly)
ctx.Convey("Then err should be nil.mids,newid should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(newid, convey.ShouldNotBeNil)
ctx.So(mids, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,21 @@
package weeklyhonor
import (
"context"
"go-common/library/log"
"time"
)
// HonorInfoc log honor msg send status
func (d *Dao) HonorInfoc(c context.Context, mid int64, success int32) (err error) {
ctime := time.Now().Format("20060102 15:04:05")
i := map[string]interface{}{
"mid": mid,
"ctime": ctime,
"exc": "",
"success": success,
}
log.Warn("infocproc create infoc(%v)", i)
err = d.infoc.Info(mid, ctime, "", success)
return
}

View File

@@ -0,0 +1,24 @@
package weeklyhonor
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestWeeklyhonorHonorInfoc(t *testing.T) {
convey.Convey("HonorInfoc", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
success = int32(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.HonorInfoc(c, mid, success)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,52 @@
package weeklyhonor
import (
"context"
model "go-common/app/interface/main/creative/model/weeklyhonor"
upgrpc "go-common/app/service/main/up/api/v1"
"reflect"
"github.com/bouk/monkey"
)
//MockHonorStat is
func (d *Dao) MockHonorStat(stat *model.HonorStat, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "HonorStat", func(_ *Dao, _ context.Context, _ int64, _ string) (*model.HonorStat, error) {
return stat, err
})
}
//MockSendNotify is
func (d *Dao) MockSendNotify(err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "SendNotify", func(_ *Dao, _ context.Context, _ []int64) error {
return err
})
}
//MockLatestHonorLogs is
func (d *Dao) MockLatestHonorLogs(hls []*model.HonorLog, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "LatestHonorLogs", func(_ *Dao, _ context.Context, _ []int64) ([]*model.HonorLog, error) {
return hls, err
})
}
//MockClickCounts is
func (d *Dao) MockClickCounts(res map[int64]int32, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "ClickCounts", func(_ *Dao, _ context.Context, _ []int64) (map[int64]int32, error) {
return res, err
})
}
//MockUpCount is
func (d *Dao) MockUpCount(count int, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "UpCount", func(_ *Dao, _ context.Context, _ int64) (int, error) {
return count, err
})
}
//MockUpActivesList is
func (d *Dao) MockUpActivesList(upActives []*upgrpc.UpActivity, newid int64, err error) (guard *monkey.PatchGuard) {
return monkey.PatchInstanceMethod(reflect.TypeOf(d), "UpActivesList", func(_ *Dao, _ context.Context, _ int64, _ int) ([]*upgrpc.UpActivity, int64, error) {
return upActives, newid, err
})
}

View File

@@ -0,0 +1,107 @@
package weeklyhonor
import (
"context"
"fmt"
model "go-common/app/interface/main/creative/model/weeklyhonor"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_honorLogsSQL = `SELECT id,mid,hid,count,ctime,mtime FROM weeklyhonor WHERE mid=?`
_honorLatestLogsSQL = `SELECT id,mid,hid,mtime FROM weeklyhonor WHERE mid in (%s) and mtime >= ?`
_honorClicksSQL = `SELECT mid,count FROM weeklyhonor_click WHERE mid in (%s) and mtime >= ?`
_upsertCountSQL = `INSERT INTO weeklyhonor (mid,hid,count) VALUES (?,?,?) ON DUPLICATE KEY UPDATE count=count+1`
)
// pingMySQL check mysql connection.
func (d *Dao) pingMySQL(c context.Context) error {
return d.db.Ping(c)
}
// HonorLogs .
func (d *Dao) HonorLogs(c context.Context, mid int64) (hls map[int]*model.HonorLog, err error) {
rows, err := d.db.Query(c, _honorLogsSQL, mid)
if err != nil {
log.Error("d.db.Query(%s,%d) error(%v)", _honorLogsSQL, mid, err)
return
}
defer rows.Close()
hls = make(map[int]*model.HonorLog)
for rows.Next() {
h := new(model.HonorLog)
if err = rows.Scan(&h.ID, &h.MID, &h.HID, &h.Count, &h.CTime, &h.MTime); err != nil {
log.Error("rows.Scan error(%v)", err)
return
}
hls[h.HID] = h
}
err = rows.Err()
return
}
// LatestHonorLogs list latest honor logs by mids
func (d *Dao) LatestHonorLogs(c context.Context, mids []int64) (hls []*model.HonorLog, err error) {
latestSun := model.LatestSunday()
midsStr := xstr.JoinInts(mids)
if midsStr == "" {
return
}
sql := fmt.Sprintf(_honorLatestLogsSQL, midsStr)
rows, err := d.db.Query(c, sql, latestSun)
if err != nil {
log.Error("d.db.Query(%s,%q,%v) error(%v)", _honorLatestLogsSQL, mids, latestSun, err)
return
}
defer rows.Close()
for rows.Next() {
h := new(model.HonorLog)
if err = rows.Scan(&h.ID, &h.MID, &h.HID, &h.MTime); err != nil {
log.Error("rows.Scan error(%v)", err)
return
}
hls = append(hls, h)
}
err = rows.Err()
return
}
// UpsertCount .
func (d *Dao) UpsertCount(c context.Context, mid int64, hid int) (affected int64, err error) {
res, err := d.db.Exec(c, _upsertCountSQL, mid, hid, 1)
if err != nil {
log.Error("d.db.Exec(%s,%d,%d,%d) error(%v)", _upsertCountSQL, mid, hid, 1, err)
return
}
return res.RowsAffected()
}
// ClickCounts honor click count map
func (d *Dao) ClickCounts(c context.Context, mids []int64) (res map[int64]int32, err error) {
res = make(map[int64]int32)
twoWeekAgo := model.LatestSunday().AddDate(0, 0, -14)
midsStr := xstr.JoinInts(mids)
if midsStr == "" {
return
}
sql := fmt.Sprintf(_honorClicksSQL, midsStr)
rows, err := d.db.Query(c, sql, twoWeekAgo)
if err != nil {
log.Error("d.db.Query(%s,%v) error(%v)", sql, twoWeekAgo, err)
return
}
defer rows.Close()
for rows.Next() {
var mid, count int64
if err = rows.Scan(&mid, &count); err != nil {
log.Error("rows.Scan error(%v)", err)
return
}
if count > 0 {
res[mid] = int32(count)
}
}
return
}

View File

@@ -0,0 +1,85 @@
package weeklyhonor
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestWeeklyhonorpingMySQL(t *testing.T) {
convey.Convey("pingMySQL", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.pingMySQL(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestWeeklyhonorHonorLogs(t *testing.T) {
convey.Convey("HonorLogs", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.HonorLogs(c, mid)
ctx.Convey("Then err should be nil.hls should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestWeeklyhonorLatestHonorLogs(t *testing.T) {
convey.Convey("LatestHonorLogs", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.LatestHonorLogs(c, mids)
ctx.Convey("Then err should be nil.hls should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestWeeklyhonorUpsertCount(t *testing.T) {
convey.Convey("UpsertCount", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
hid = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
affected, err := d.UpsertCount(c, mid, hid)
ctx.Convey("Then err should be nil.affected should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(affected, convey.ShouldNotBeNil)
})
})
})
}
func TestWeeklyhonorClickCounts(t *testing.T) {
convey.Convey("ClickCounts", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ClickCounts(c, mids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,53 @@
package weeklyhonor
import (
"context"
"go-common/app/service/main/archive/model/archive"
upgrpc "go-common/app/service/main/up/api/v1"
"go-common/library/ecode"
"go-common/library/log"
)
const fromWeeklyHonor = 1
// UpCount get archives count.
func (d *Dao) UpCount(c context.Context, mid int64) (count int, err error) {
var arg = &archive.ArgUpCount2{Mid: mid}
if count, err = d.arc.UpCount2(c, arg); err != nil {
log.Error("rpc UpCount2 (%v) error(%v)", mid, err)
err = ecode.CreativeArcServiceErr
}
return
}
// UpActivesList list up-actives
func (d *Dao) UpActivesList(c context.Context, lastID int64, ps int) (upActives []*upgrpc.UpActivity, newid int64, err error) {
upListReq := upgrpc.UpListByLastIDReq{
LastID: lastID,
Ps: ps,
}
reply, err := d.upClient.UpInfoActivitys(c, &upListReq)
if err != nil {
log.Error("failed to list up&active info,err(%v)", err)
return
}
newid = reply.GetLastID()
upActives = reply.GetUpActivitys()
return
}
// GetUpSwitch get up switch state
func (d *Dao) GetUpSwitch(c context.Context, mid int64) (state uint8, err error) {
req := upgrpc.UpSwitchReq{
Mid: mid,
From: fromWeeklyHonor,
}
reply, err := d.upClient.UpSwitch(c, &req)
if err != nil {
log.Error("d.upClient.UpSwitch req(%+v),err(%v)", req, err)
return
}
state = reply.GetState()
return
}

View File

@@ -0,0 +1,96 @@
package weeklyhonor
import (
"context"
"fmt"
"testing"
whmdl "go-common/app/interface/main/creative/model/weeklyhonor"
upgrpc "go-common/app/service/main/up/api/v1"
"github.com/golang/mock/gomock"
"github.com/smartystreets/goconvey/convey"
)
var c = context.Background()
func TestWeeklyhonorUpCount(t *testing.T) {
convey.Convey("UpCount", t, func(ctx convey.C) {
var (
mid = int64(1627855)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.UpCount(c, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestWeeklyhonorUpActiveLists(t *testing.T) {
convey.Convey("UpActivesList", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", WithMock(t, func(mockCtrl *gomock.Controller) {
// mock
mockUpClient := upgrpc.NewMockUpClient(mockCtrl)
d.upClient = mockUpClient
mockReq := upgrpc.UpListByLastIDReq{
LastID: 0,
Ps: 100,
}
mockReply := upgrpc.UpActivityListReply{
UpActivitys: []*upgrpc.UpActivity{
{Mid: 1},
{Activity: 2},
},
LastID: 1,
}
mockUpClient.EXPECT().UpInfoActivitys(gomock.Any(), &mockReq).Return(&mockReply, nil)
// test
upActives, newId, err := d.UpActivesList(c, 0, 100)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(upActives[0], convey.ShouldEqual, mockReply.UpActivitys[0])
ctx.So(newId, convey.ShouldEqual, mockReply.LastID)
})
}))
})
}
func TestWeeklyhonorGetUpSwitch(t *testing.T) {
convey.Convey("GetUpSwitch", t, WithMock(t, func(mockCtrl *gomock.Controller) {
var (
c = context.Background()
mid = int64(75379101)
)
convey.Convey("When everything gose positive", func(ctx convey.C) {
mockUpClient := upgrpc.NewMockUpClient(mockCtrl)
d.upClient = mockUpClient
mockReq := upgrpc.UpSwitchReq{
Mid: mid,
From: fromWeeklyHonor,
}
mockState := whmdl.HonorUnSub
mockUpClient.EXPECT().UpSwitch(gomock.Any(), &mockReq).Return(&upgrpc.UpSwitchReply{State: mockState}, nil)
state, err := d.GetUpSwitch(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(state, convey.ShouldEqual, mockState)
})
})
convey.Convey("When return err", func(ctx convey.C) {
mockUpClient := upgrpc.NewMockUpClient(mockCtrl)
d.upClient = mockUpClient
mockReq := upgrpc.UpSwitchReq{
Mid: mid,
From: fromWeeklyHonor,
}
mockUpClient.EXPECT().UpSwitch(gomock.Any(), &mockReq).Return(nil, fmt.Errorf("mock err"))
_, err := d.GetUpSwitch(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
}))
}