Skip to content

Commit

Permalink
feat:add service unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
geebytes committed May 24, 2024
1 parent 2a1617a commit ee3f490
Show file tree
Hide file tree
Showing 11 changed files with 78 additions and 26 deletions.
1 change: 1 addition & 0 deletions gateway/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ func (h *HttpEndpointImpl) RegisterHandlerClient(ctx context.Context, pd Protobu
}
for _, item := range items {
item := item
// log.Printf("register endpoint %s: %s %v", strings.ToUpper(item.HttpMethod), item.HttpUri, item.Pattern)
mux.Handle(strings.ToUpper(item.HttpMethod), item.Pattern, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
if req.Header.Get("accept") == "" {
req.Header.Set("accept", "application/json")
Expand Down
16 changes: 12 additions & 4 deletions gateway/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,10 @@ func testRegisterClient(t *testing.T) {
time.Sleep(2 * time.Second)
go gw.Start()
time.Sleep(1 * time.Second)
f:=func(){
f := func() {
gw.Start()
}
c.So(f,c.ShouldPanic)
c.So(f, c.ShouldPanic)
time.Sleep(4 * time.Second)
_, err = gw.proxyLB.Select("test/.test")
c.So(err, c.ShouldNotBeNil)
Expand Down Expand Up @@ -181,6 +181,16 @@ func testRequestGet(t *testing.T) {
c.So(err, c.ShouldBeNil)
c.So(resp.StatusCode, c.ShouldEqual, http.StatusIMUsed)

url = fmt.Sprintf("http://127.0.0.1:%d/api/v1/example/world?msg=hello", gwPort)
r2, err := http.NewRequest(http.MethodPost, url, nil)

c.So(err, c.ShouldBeNil)

resp2, err := http.DefaultClient.Do(r2)

c.So(err, c.ShouldBeNil)
c.So(resp2.StatusCode, c.ShouldEqual, http.StatusNotImplemented)

})
}
func testCors(t *testing.T) {
Expand Down Expand Up @@ -1075,9 +1085,7 @@ func testUpdateLoadbalance(t *testing.T) {
}
for _, v := range endps {
c.So(v.Stats().GetIdleConns(), c.ShouldBeGreaterThan, 0)
// c.So(v.Close(), c.ShouldBeNil)
}
// helloAddr := fmt.Sprintf("")
})
}
func TestHttp(t *testing.T) {
Expand Down
4 changes: 4 additions & 0 deletions gateway/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,10 @@ func HandleErrorWithLogger(logger logger.Logger) runtime.ErrorHandlerFunc {
"status": statusCode,
},
)
if _,ok:=metadata.FromIncomingContext(ctx);!ok{
md:=IncomingHeadersToMetadata(ctx,req)
ctx=metadata.NewIncomingContext(ctx,md)
}
code := statusCode
data := &common.HttpResponse{}
data.Code = int32(common.Code_INTERNAL_ERROR)
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ require (
require (
github.com/agiledragon/gomonkey/v2 v2.11.0
github.com/begonia-org/go-loadbalancer v0.0.0-20240519060752-71ca464f0f1a
github.com/begonia-org/go-sdk v0.0.0-20240521170528-b02c5a54f25e
github.com/begonia-org/go-sdk v0.0.0-20240524034736-5c195b7e4b0f
github.com/go-git/go-git/v5 v5.11.0
github.com/go-playground/validator/v10 v10.19.0
github.com/gorilla/websocket v1.5.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ github.com/begonia-org/go-loadbalancer v0.0.0-20240519060752-71ca464f0f1a h1:Mpw
github.com/begonia-org/go-loadbalancer v0.0.0-20240519060752-71ca464f0f1a/go.mod h1:crPS67sfgmgv47psftwfmTMbmTfdepVm8MPeqApINlI=
github.com/begonia-org/go-sdk v0.0.0-20240521170528-b02c5a54f25e h1:QIlVvEUYC2t+ctxzKMFtMw0a1eXauR87pimm2D55guQ=
github.com/begonia-org/go-sdk v0.0.0-20240521170528-b02c5a54f25e/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y=
github.com/begonia-org/go-sdk v0.0.0-20240524034736-5c195b7e4b0f h1:DQAupqwJEj9lYPk7phcbr+8+lZOFPLRNA9Ao+8Sh11M=
github.com/begonia-org/go-sdk v0.0.0-20240524034736-5c195b7e4b0f/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y=
github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
Expand Down
13 changes: 10 additions & 3 deletions internal/biz/data_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
loadbalance "github.com/begonia-org/go-loadbalancer"
appApi "github.com/begonia-org/go-sdk/api/app/v1"
api "github.com/begonia-org/go-sdk/api/user/v1"
ep "github.com/begonia-org/go-sdk/api/endpoint/v1"
gwRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
c "github.com/smartystreets/goconvey/convey"

Expand Down Expand Up @@ -204,18 +205,24 @@ func TestOnStart(t *testing.T) {
defer patch.Reset()
ctx, cancel := context.WithCancel(context.Background())
err := dataOperator.OnStart(ctx)
time.Sleep(1 * time.Second)
time.Sleep(4 * time.Second)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, "test endpoint list error")
patch.Reset()
cancel()
// []*api.Endpoints, error
patch2:= gomonkey.ApplyMethodReturn(repo, "List", []*ep.Endpoints{{
Name: "test",
Owner: "test",
Description: "test",
}}, nil)
patch2 = patch2.ApplyFuncReturn((*endpoint.EndpointWatcher).Update, fmt.Errorf("test endpoint watcher update error"))

patch2 := gomonkey.ApplyFuncReturn((*endpoint.EndpointWatcher).Update, fmt.Errorf("test endpoint watcher update error"))
defer patch2.Reset()
ctx, cancel = context.WithCancel(context.Background())
err = dataOperator.OnStart(ctx)

time.Sleep(1 * time.Second)
time.Sleep(2 * time.Second)

c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, "test endpoint watcher update error")
Expand Down
10 changes: 6 additions & 4 deletions internal/biz/endpoint/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ func (e *EndpointUsecase) AddConfig(ctx context.Context, srvConfig *api.Endpoint
ServiceName: srvConfig.ServiceName,
DescriptorSet: srvConfig.DescriptorSet,
}
log.Printf("endpoint add tags :%v", srvConfig.Tags)
err := e.repo.Put(ctx, endpoint)
if err != nil {
return "", gosdk.NewError(err, int32(common.Code_INTERNAL_ERROR), codes.Internal, "put_endpoint")
Expand All @@ -83,10 +82,12 @@ func (e *EndpointUsecase) Patch(ctx context.Context, srvConfig *api.EndpointSrvU
return "", gosdk.NewError(err, int32(common.Code_INTERNAL_ERROR), codes.Internal, "unmarshal_config")

}
// 过滤掉不允许修改的字段
for _, field := range srvConfig.UpdateMask.Paths {
patch[field] = svrConfigPatch[field]
if srvConfig.UpdateMask != nil {
// 过滤掉不允许修改的字段
for _, field := range srvConfig.UpdateMask.Paths {
patch[field] = svrConfigPatch[field]

}
}

updated_at := timestamppb.New(time.Now()).AsTime().Format(time.RFC3339)
Expand Down Expand Up @@ -125,6 +126,7 @@ func (u *EndpointUsecase) Get(ctx context.Context, uniqueKey string) (*api.Endpo
func (u *EndpointUsecase) List(ctx context.Context, in *api.ListEndpointRequest) ([]*api.Endpoints, error) {
keys := make([]string, 0)
if len(in.Tags) > 0 {
log.Printf("list tags:%v", in.Tags)
ks, err := u.repo.GetKeysByTags(ctx, in.Tags)
if err != nil {
return nil, gosdk.NewError(err, int32(common.Code_INTERNAL_ERROR), codes.Internal, "get_keys_by_tags")
Expand Down
6 changes: 3 additions & 3 deletions internal/biz/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -428,8 +428,8 @@ func (f *FileUsecase) DownloadForRange(ctx context.Context, in *api.DownloadRequ
return nil, 0, err
}
in.Key = key
if start > end {
err := gosdk.NewError(errors.ErrInvalidRange, int32(api.FileSvrStatus_FILE_INVALIDATE_RANGE_ERR), codes.InvalidArgument, "invalid_range")
if start > end && end > 0{
err := gosdk.NewError(fmt.Errorf("%w:start=%d,end=%d", errors.ErrInvalidRange, start, end), int32(api.FileSvrStatus_FILE_INVALIDATE_RANGE_ERR), codes.InvalidArgument, "invalid_range")
return nil, 0, err

}
Expand Down Expand Up @@ -464,7 +464,7 @@ func (f *FileUsecase) Metadata(ctx context.Context, in *api.FileMetadataRequest,
in.Key = key
file, err := f.getReader(in.Key, in.Version)
if err != nil {
code,grpcCode:=f.checkStatusCode(err)
code, grpcCode := f.checkStatusCode(err)
return nil, gosdk.NewError(err, code, grpcCode, "open_file")

}
Expand Down
8 changes: 7 additions & 1 deletion internal/biz/file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1084,9 +1084,15 @@ func testDownloadRange(t *testing.T) {
_, _, err = fileBiz.DownloadForRange(context.Background(), &api.DownloadRequest{
Key: "test/upload.parts.test1",
Version: "latest",
}, 1024, 0, fileAuthor)
}, 1024, 1, fileAuthor)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, errors.ErrInvalidRange.Error())

_, _, err = fileBiz.DownloadForRange(context.Background(), &api.DownloadRequest{
Key: fileAuthor + "/test/upload.parts.test1",
Version: "latest",
}, 1024, 0, fileAuthor)
c.So(err, c.ShouldBeNil)
patch := gomonkey.ApplyFuncReturn(file.NewFileVersionReader, nil, git.ErrRepositoryNotExists)
defer patch.Reset()
_, _, err = fileBiz.DownloadForRange(context.Background(), &api.DownloadRequest{
Expand Down
24 changes: 23 additions & 1 deletion internal/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ import (
"github.com/begonia-org/begonia/internal/pkg/migrate"
"github.com/begonia-org/begonia/internal/server"
"github.com/begonia-org/begonia/internal/service"
"github.com/begonia-org/go-sdk/logger"
app "github.com/begonia-org/go-sdk/api/app/v1"
ep "github.com/begonia-org/go-sdk/api/endpoint/v1"
file "github.com/begonia-org/go-sdk/api/file/v1"
sys "github.com/begonia-org/go-sdk/api/sys/v1"
user "github.com/begonia-org/go-sdk/api/user/v1"

"github.com/google/wire"

Expand All @@ -23,8 +29,24 @@ func InitOperatorApp(config *tiga.Configuration) *migrate.InitOperator {

}

func New(config *tiga.Configuration, log gateway.Logger, endpoint string) GatewayWorker {
func New(config *tiga.Configuration, log logger.Logger, endpoint string) GatewayWorker {

panic(wire.Build(biz.ProviderSet, pkg.ProviderSet, data.ProviderSet, service.ProviderSet, daemon.ProviderSet, server.ProviderSet, NewGatewayWorkerImpl))

}

func NewAuthzSvr(config *tiga.Configuration, log logger.Logger)user.AuthServiceServer {
panic(wire.Build(biz.ProviderSet, pkg.ProviderSet, data.ProviderSet, service.ProviderSet, daemon.ProviderSet, server.ProviderSet, service.NewAuthzService))
}
func NewAPPSvr(config *tiga.Configuration, log logger.Logger)app.AppsServiceServer {
panic(wire.Build(biz.ProviderSet, pkg.ProviderSet, data.ProviderSet, service.ProviderSet, daemon.ProviderSet, server.ProviderSet, service.NewAppService))
}
func NewEndpointSvr(config *tiga.Configuration, log logger.Logger)ep.EndpointServiceServer {
panic(wire.Build(biz.ProviderSet, pkg.ProviderSet, data.ProviderSet, service.ProviderSet, daemon.ProviderSet, server.ProviderSet, service.NewEndpointsService))
}
func NewFileSvr(config *tiga.Configuration, log logger.Logger)file.FileServiceServer {
panic(wire.Build(biz.ProviderSet, pkg.ProviderSet, data.ProviderSet, service.ProviderSet, daemon.ProviderSet, server.ProviderSet, service.NewFileService))
}
func NewSysSvr(config *tiga.Configuration, log logger.Logger)sys.SystemServiceServer {
panic(wire.Build(biz.ProviderSet, pkg.ProviderSet, data.ProviderSet, service.ProviderSet, daemon.ProviderSet, server.ProviderSet, service.NewSysService))
}
18 changes: 9 additions & 9 deletions internal/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit ee3f490

Please sign in to comment.