Skip to content

Commit

Permalink
feat:add data unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
geebytes committed May 8, 2024
1 parent 37db7c7 commit 63dbc3f
Show file tree
Hide file tree
Showing 16 changed files with 1,057 additions and 176 deletions.
79 changes: 56 additions & 23 deletions internal/data/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ type appRepoImpl struct {
curd biz.CURD
}

func NewAppRepoImpl(data *Data,curd biz.CURD, local *LayeredCache, cfg *config.Config) biz.AppRepo {
return &appRepoImpl{data: data,curd: curd, local: local, cfg: cfg}
func NewAppRepoImpl(data *Data, curd biz.CURD, local *LayeredCache, cfg *config.Config) biz.AppRepo {
return &appRepoImpl{data: data, curd: curd, local: local, cfg: cfg}
}

func (r *appRepoImpl) Add(ctx context.Context, apps *api.Apps) error {

if err := r.curd.Add(ctx, apps,false); err != nil {
if err := r.curd.Add(ctx, apps, false); err != nil {
return fmt.Errorf("add app failed: %w", err)
}
key := r.cfg.GetAPPAccessKey(apps.AccessKey)
Expand All @@ -35,8 +35,8 @@ func (r *appRepoImpl) Add(ctx context.Context, apps *api.Apps) error {
func (r *appRepoImpl) Get(ctx context.Context, key string) (*api.Apps, error) {

app := &api.Apps{}
err := r.curd.Get(ctx, app,false, "access_key = ? or appid=?", key, key)
if err != nil||app.Appid=="" {
err := r.curd.Get(ctx, app, false, "access_key = ? or appid=?", key, key)
if err != nil || app.Appid == "" {
return nil, fmt.Errorf("get app failed: %w", err)
}
return app, err
Expand All @@ -53,38 +53,71 @@ func (r *appRepoImpl) Del(ctx context.Context, key string) error {
return err
}
_ = r.local.Del(ctx, r.cfg.GetAPPAccessKey(app.AccessKey))
return r.curd.Del(ctx, app,false)
return r.curd.Del(ctx, app, false)
}
func (r *appRepoImpl) Patch(ctx context.Context, model *api.Apps) error {

return r.curd.Update(ctx, model,false)
return r.curd.Update(ctx, model, false)
}
func (r *appRepoImpl) List(ctx context.Context, tags []string, status []api.APPStatus, page, pageSize int32) ([]*api.Apps, error) {
apps := make([]*api.Apps, 0)
query:=""
conds:=make([]interface{},0)
if len(tags)>0{
query="tags in (?)"
conds=append(conds,tags)
query := ""
conds := make([]interface{}, 0)
if len(tags) > 0 {
query = "tags in (?)"
conds = append(conds, tags)
}
if len(status)>0{
if query!=""{
query+=" and "
if len(status) > 0 {
if query != "" {
query += " and "
}
query+="status in (?)"
conds=append(conds,status)
query += "status in (?)"
conds = append(conds, status)
}
pagination:= &tiga.Pagination{
Page: page,
pagination := &tiga.Pagination{
Page: page,
PageSize: pageSize,
Query: query,
Args: conds,
Query: query,
Args: conds,
}
err := r.curd.List(ctx,&apps, pagination)
err := r.curd.List(ctx, &apps, pagination)
if err != nil {
return nil, fmt.Errorf("list app failed: %w", err)

}
return apps, nil

}

func (a *appRepoImpl) GetSecret(ctx context.Context, accessKey string) (string, error) {
cacheKey := a.cfg.GetAPPAccessKey(accessKey)
secretBytes, err := a.local.Get(ctx, cacheKey)
secret := string(secretBytes)
if err != nil {
apps, err := a.Get(ctx, accessKey)
if err != nil {
return "", err
}
secret = apps.Secret

// _ = a.rdb.Set(ctx, cacheKey, secret, time.Hour*24*3)
_ = a.local.Set(ctx, cacheKey, []byte(secret), time.Hour*24*3)
}
return secret, nil
}
func (a *appRepoImpl) GetAppid(ctx context.Context, accessKey string) (string, error) {
cacheKey := a.cfg.GetAppidKey(accessKey)
secretBytes, err := a.local.Get(ctx, cacheKey)
appid := string(secretBytes)
if err != nil {
apps, err := a.Get(ctx, accessKey)
if err != nil {
return "", err
}
appid = apps.Appid

// _ = a.rdb.Set(ctx, cacheKey, secret, time.Hour*24*3)
_ = a.local.Set(ctx, cacheKey, []byte(appid), time.Hour*24*3)
}
return appid, nil
}
186 changes: 186 additions & 0 deletions internal/data/app_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package data

import (
"context"
"crypto/rand"
"fmt"
"testing"
"time"

"github.com/agiledragon/gomonkey/v2"
"github.com/begonia-org/begonia"
cfg "github.com/begonia-org/begonia/config"
"github.com/begonia-org/begonia/internal/pkg/config"
"github.com/begonia-org/begonia/internal/pkg/logger"
api "github.com/begonia-org/go-sdk/api/app/v1"
"github.com/cockroachdb/errors"
c "github.com/smartystreets/goconvey/convey"
"github.com/spark-lence/tiga"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
)

var appid = ""
var accessKey = ""
var secret = ""
var appName = ""

func generateRandomString(n int) (string, error) {
const lettersAndDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("Failed to generate random string: %w", err)
}

for i := 0; i < n; i++ {
// 将随机字节转换为lettersAndDigits中的一个有效字符
b[i] = lettersAndDigits[b[i]%byte(len(lettersAndDigits))]
}

return string(b), nil
}
func addTest(t *testing.T) {
c.Convey("test app add success", t, func() {
t.Log("add test")
env := "dev"
if begonia.Env != "" {
env = begonia.Env
}
repo := NewAppRepo(cfg.ReadConfig(env), logger.Log)
snk, _ := tiga.NewSnowflake(1)
access, _ := generateRandomString(32)
accessKey = access
secret, _ = generateRandomString(62)
appid = snk.GenerateIDString()
appName = fmt.Sprintf("app-%s", time.Now().Format("20060102150405"))
err := repo.Add(context.TODO(), &api.Apps{
Appid: appid,
AccessKey: access,
Secret: secret,
Status: api.APPStatus_APP_ENABLED,
IsDeleted: false,
Name: appName,
Description: "test",
CreatedAt: timestamppb.New(time.Now()),
UpdatedAt: timestamppb.New(time.Now()),
})

c.So(err, c.ShouldBeNil)
cfg := config.NewConfig(cfg.ReadConfig(env))
cacheKey := cfg.GetAPPAccessKey(access)

value, err := layered.Get(context.Background(), cacheKey)
c.So(err, c.ShouldBeNil)
c.So(string(value), c.ShouldEqual, secret)

patch := gomonkey.ApplyFuncReturn((*LayeredCache).Get, nil, errors.New("error"))

defer patch.Reset()
val, err := repo.GetSecret(context.Background(), access)
c.So(err, c.ShouldBeNil)
c.So(val, c.ShouldEqual, secret)

})
}
func getTest(t *testing.T) {
c.Convey("test app get success", t, func() {
t.Log("get test")
env := "dev"
if begonia.Env != "" {
env = begonia.Env
}
repo := NewAppRepo(cfg.ReadConfig(env), logger.Log)
app, err := repo.Get(context.TODO(), appid)
c.So(err, c.ShouldBeNil)
c.So(app.Appid, c.ShouldEqual, appid)
app, err = repo.Get(context.TODO(), accessKey)
c.So(err, c.ShouldBeNil)
c.So(app.AccessKey, c.ShouldEqual, accessKey)
_, err = repo.Get(context.TODO(), "123")
c.So(err, c.ShouldNotBeNil)

})
}

func duplicateNameTest(t *testing.T) {
c.Convey("test app add duplicate name", t, func() {
t.Log("add test")
env := "dev"
if begonia.Env != "" {
env = begonia.Env
}
repo := NewAppRepo(cfg.ReadConfig(env), logger.Log)
// snk, _ := tiga.NewSnowflake(1)
access, _ := generateRandomString(32)
accessKey = access
secret, _ = generateRandomString(62)
// appid = snk.GenerateIDString()
err := repo.Add(context.TODO(), &api.Apps{
Appid: appid,
AccessKey: access,
Secret: secret,
Status: api.APPStatus_APP_ENABLED,
IsDeleted: false,
Name: fmt.Sprintf("app-%s", time.Now().Format("20060102150405")),
Description: "test",
CreatedAt: timestamppb.New(time.Now()),
UpdatedAt: timestamppb.New(time.Now()),
})

c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, "Duplicate entry")
})
}
func patchTest(t *testing.T) {
c.Convey("test app patch success", t, func() {
t.Log("patch test")
env := "dev"
if begonia.Env != "" {
env = begonia.Env
}
repo := NewAppRepo(cfg.ReadConfig(env), logger.Log)
err := repo.Patch(context.TODO(), &api.Apps{
Appid: appid,
AccessKey: accessKey,
Secret: secret,
Status: api.APPStatus_APP_DISABLED,
Name: fmt.Sprintf("app-%s", time.Now().Format("20060102150405")),
Description: "test UPDATE",
CreatedAt: timestamppb.New(time.Now()),
UpdatedAt: timestamppb.New(time.Now()),
UpdateMask: &fieldmaskpb.FieldMask{
Paths: []string{"status", "description"},
},
})

c.So(err, c.ShouldBeNil)
t.Log("get test", appid)
updated,err:=repo.Get(context.Background(),appid)
c.So(err,c.ShouldBeNil)
c.So(updated.Status,c.ShouldEqual,api.APPStatus_APP_DISABLED)
c.So(updated.Description,c.ShouldEqual,"test UPDATE")
c.So(updated.Name,c.ShouldEqual,appName)
})

}
func delTest(t *testing.T) {
c.Convey("test app delete success", t, func() {
t.Log("delete test")
env := "dev"
if begonia.Env != "" {
env = begonia.Env
}
repo := NewAppRepo(cfg.ReadConfig(env), logger.Log)
err := repo.Del(context.TODO(), appid)
c.So(err, c.ShouldBeNil)
_, err = repo.Get(context.TODO(), appid)
c.So(err, c.ShouldNotBeNil)
})
}
func TestApp(t *testing.T) {
t.Run("add app", addTest)
t.Run("get app", getTest)
t.Run("add duplicate name", duplicateNameTest)
t.Run("patch app", patchTest)
t.Run("del app", delTest)
}
49 changes: 16 additions & 33 deletions internal/data/authz.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"time"

"github.com/begonia-org/begonia/internal/biz"
api "github.com/begonia-org/go-sdk/api/user/v1"
"github.com/begonia-org/go-sdk/logger"
)

Expand All @@ -15,41 +14,27 @@ type authzRepo struct {
local *LayeredCache
}

func NewAuthzRepo(data *Data, log logger.Logger, local *LayeredCache) biz.AuthzRepo {
func NewAuthzRepoImpl(data *Data, log logger.Logger, local *LayeredCache) biz.AuthzRepo {
return &authzRepo{data: data, log: log, local: local}

Check failure on line 18 in internal/data/authz.go

View workflow job for this annotation

GitHub Actions / test

cannot use &authzRepo{…} (value of type *authzRepo) as biz.AuthzRepo value in return statement: *authzRepo does not implement biz.AuthzRepo (missing method CreateUsers)
}

func (r *authzRepo) ListUsers(ctx context.Context, page, pageSize int32, conds ...interface{}) ([]*api.Users, error) {
users := make([]*api.Users, 0)
if err := r.data.List(&api.Users{}, &users, page, pageSize, conds...); err != nil {
return nil, err
}
return users, nil

}
func (r *authzRepo) GetUser(ctx context.Context, conds ...interface{}) (*api.Users, error) {
user := &api.Users{}
err := r.data.Get(user, user, conds...)
if err != nil {
return nil, err
}
return user, nil
}
func (r *authzRepo) CreateUsers(ctx context.Context, users []*api.Users) error {
sources := NewSourceTypeArray(users)
return r.data.CreateInBatches(sources)
}
func (t *authzRepo) UpdateUsers(ctx context.Context, models []*api.Users) error {
sources := NewSourceTypeArray(models)

return t.data.BatchUpdates(ctx,sources)
}
// func (r *authzRepo) ListUsers(ctx context.Context, page, pageSize int32, conds ...interface{}) ([]*api.Users, error) {
// users := make([]*api.Users, 0)
// if err := r.data.List(&api.Users{}, &users, page, pageSize, conds...); err != nil {
// return nil, err
// }
// return users, nil

func (t *authzRepo) DeleteUsers(ctx context.Context, models []*api.Users) error {
sources := NewSourceTypeArray(models)
// }
// func (r *authzRepo) GetUser(ctx context.Context, conds ...interface{}) (*api.Users, error) {
// user := &api.Users{}
// err := r.data.Get(user, user, conds...)
// if err != nil {
// return nil, err
// }
// return user, nil
// }

return t.data.BatchDelete(sources)
}
func (t *authzRepo) CacheToken(ctx context.Context, key, token string, exp time.Duration) error {
return t.local.Set(ctx, key, []byte(token), exp)
}
Expand All @@ -63,7 +48,6 @@ func (t *authzRepo) GetToken(ctx context.Context, key string) string {
}
func (t *authzRepo) DelToken(ctx context.Context, key string) error {
err := t.local.Del(ctx, key)
// err := t.data.DelCache(ctx, key)
return err
}
func (t *authzRepo) CheckInBlackList(ctx context.Context, token string) (bool, error) {
Expand All @@ -76,4 +60,3 @@ func (t *authzRepo) PutBlackList(ctx context.Context, token string) error {
return t.local.AddToFilter(ctx, key, []byte(token))

}

Loading

0 comments on commit 63dbc3f

Please sign in to comment.