Skip to content

Commit

Permalink
feat:add middleware auth unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
geebytes committed Jun 1, 2024
1 parent 42655de commit 133eb46
Show file tree
Hide file tree
Showing 71 changed files with 1,142 additions and 671 deletions.
3 changes: 1 addition & 2 deletions cmd/gateway/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import (
"log"

"github.com/begonia-org/begonia/config"
"github.com/begonia-org/begonia/gateway"
"github.com/begonia-org/begonia/internal"
"github.com/spf13/cobra"
"github.com/begonia-org/begonia/gateway"

)

// var ProviderSet = wire.NewSet(NewMasterCmd)
Expand Down
14 changes: 7 additions & 7 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,14 @@ test:
private_key: "/tmp/auth_private_key.pem"
public_key: "/tmp/auth_public_key.pem"
common:
rdb_key_prefix: "begonia"
filter_key_prefix: "begonia:filter"
app_key_prefix: "begonia:kv:app"
blacklist_key_prefix: "begonia:blacklist"
pubsub_key_prefix: "begonia:pubsub"
cache_prefix_key: "begonia"
filter_key_prefix: "filter"
app_key_prefix: "kv:app"
# blacklist_key_prefix: "blacklist"
pubsub_key_prefix: "pubsub"
multi_cache_strategy: 1
kv_prefix: "begonia:cache"
pubsub_key_channel: "begonia:pubsub:channel"
kv_prefix: "cache"
pubsub_key_channel: "pubsub:channel"
etcd:
endpoint:
prefix: "/begonia/endpoints"
Expand Down
4 changes: 2 additions & 2 deletions gateway/exception_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ func TestUnaryInterceptor(t *testing.T) {
mid := NewException(Log)

ctx := context.Background()
handler:= func(ctx context.Context, req interface{}) (interface{}, error) {
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
panic("test panic error")
}
_, err := mid.UnaryInterceptor(ctx, nil, &grpc.UnaryServerInfo{}, handler)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, "test panic error")

handler2:= func(ctx context.Context, req interface{}) (interface{}, error) {
handler2 := func(ctx context.Context, req interface{}) (interface{}, error) {
return nil, fmt.Errorf("test error")
}
_, err2 := mid.UnaryInterceptor(ctx, nil, &grpc.UnaryServerInfo{}, handler2)
Expand Down
13 changes: 6 additions & 7 deletions gateway/formdata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ func TestFormDataContentType(t *testing.T) {
c.So(pb.SfixedData, c.ShouldEqual, 11949)
c.So(pb.Sfixed32Data, c.ShouldEqual, 21949)
c.So(pb.Fixed32Data, c.ShouldEqual, 31949)
marshal:=&FormDataMarshaler{}
c.So(marshal.ContentType(nil),c.ShouldEqual,"multipart/form-data")
marshal := &FormDataMarshaler{}
c.So(marshal.ContentType(nil), c.ShouldEqual, "multipart/form-data")
})
}

Expand All @@ -108,8 +108,8 @@ func TestFormUrlEncodedContentType(t *testing.T) {
c.So(err, c.ShouldBeNil)
c.So(pb.Message, c.ShouldEqual, "John Doe")
c.So(pb.Allow, c.ShouldEqual, api.EnumAllow_DENY)
marshal:=&FormUrlEncodedMarshaler{}
c.So(marshal.ContentType(nil),c.ShouldEqual,"application/x-www-form-urlencoded")
marshal := &FormUrlEncodedMarshaler{}
c.So(marshal.ContentType(nil), c.ShouldEqual, "application/x-www-form-urlencoded")
})
}

Expand All @@ -136,21 +136,20 @@ func TestFormUrlEncodedErr(t *testing.T) {
formData.Add("message", "John Doe")
formData.Add("allow", api.EnumAllow_DENY.String())
_, filePath, _, _ := runtime.Caller(0)

// 添加文件
data, _ := os.ReadFile(filePath)
formData.Add("byte_data", string(data))
pb := &api.ExampleMessage{}
dpb := dynamicpb.NewMessage(pb.ProtoReflect().Descriptor())
decoder := &FormUrlEncodedDecoder{r: strings.NewReader(formData.Encode())}
patch:=gomonkey.ApplyFuncReturn(caseV.patch, caseV.output...)
patch := gomonkey.ApplyFuncReturn(caseV.patch, caseV.output...)
defer patch.Reset()
err := decoder.Decode(dpb)
c.So(err, c.ShouldNotBeNil)
patch.Reset()
}


})
}

Expand Down
2 changes: 1 addition & 1 deletion gateway/mask.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,6 @@ func (d *maskDecoder) Decode(v interface{}) error {
}
// 设置更新掩码字段
SetUpdateMaskFields(message, fields)

return nil
}
2 changes: 1 addition & 1 deletion gateway/mask_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestDecodeErr(t *testing.T) {
}
r := bytes.NewReader([]byte(`{"message":"John Doe","msg":{"msg":"hello world"},"allow":"DENY","repeated_msg":[{"msg":"John Doe"}]}`))
decoder := NewMaskDecoder(NewJsonDecoder(r))
mapData:=make(map[string]interface{})
mapData := make(map[string]interface{})
err := decoder.Decode(mapData)
c.So(err, c.ShouldBeNil)
c.So(len(mapData), c.ShouldEqual, 0)
Expand Down
6 changes: 3 additions & 3 deletions gateway/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,9 @@ func HandleErrorWithLogger(logger logger.Logger) runtime.ErrorHandlerFunc {
"status": statusCode,
},
)
if _,ok:=metadata.FromIncomingContext(ctx);!ok{
md:=IncomingHeadersToMetadata(ctx,req)
ctx=metadata.NewIncomingContext(ctx,md)
if _, ok := metadata.FromIncomingContext(ctx); !ok {
md := IncomingHeadersToMetadata(ctx, req)
ctx = metadata.NewIncomingContext(ctx, md)
}
code := statusCode
data := &common.HttpResponse{}
Expand Down
8 changes: 4 additions & 4 deletions gateway/protobuf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ func testSetHttpResponseErr(t *testing.T) {
c.So(err, c.ShouldNotBeNil)
patch.Reset()
}
patch:=gomonkey.ApplyFunc((*json.Decoder).Decode, func(_ *json.Decoder, v any) error {
val:=v.(*map[string]interface{})
(*val)["/SayHello"]=[]interface{}{map[string]interface{}{"OutName":"HttpBody"}}
patch := gomonkey.ApplyFunc((*json.Decoder).Decode, func(_ *json.Decoder, v any) error {
val := v.(*map[string]interface{})
(*val)["/SayHello"] = []interface{}{map[string]interface{}{"OutName": "HttpBody"}}
return nil
})
defer patch.Reset()
err = pd.SetHttpResponse(common.E_HttpResponse)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(),c.ShouldContainSubstring,"invalid gateway.json")
c.So(err.Error(), c.ShouldContainSubstring, "invalid gateway.json")
patch.Reset()
})
}
Expand Down
5 changes: 0 additions & 5 deletions gateway/serialization.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,3 @@ func (m *JSONMarshaler) Marshal(v interface{}) ([]byte, error) {
func (m *JSONMarshaler) ContentType(v interface{}) string {
return "application/json"
}

// func (m *JSONMarshaler) NewDecoder(r io.Reader) runtime.Decoder {
// // return NewMaskDecoder(m.JSONPb.NewDecoder(r))
// return json.NewDecoder(r)
// }
2 changes: 1 addition & 1 deletion gateway/serialization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestRawBinaryUnmarshaler(t *testing.T) {
c.So(marshal.ContentType(msg2), c.ShouldEqual, "application/octet-stream")
patch1.Reset()

patch2:=gomonkey.ApplyFuncReturn(proto.Unmarshal, fmt.Errorf("io.ReadAll: unexpected EOF"))
patch2 := gomonkey.ApplyFuncReturn(proto.Unmarshal, fmt.Errorf("io.ReadAll: unexpected EOF"))
defer patch2.Reset()
c.So(marshal.ContentType(msg2), c.ShouldEqual, "application/octet-stream")
})
Expand Down
6 changes: 3 additions & 3 deletions gateway/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ func (x *serverSideStreamClient) Recv() (protoreflect.ProtoMessage, error) {
}
return x.buildEventStreamResponse(out)
}
func (x *serverSideStreamClient)SendMsg(v any)error{
func (x *serverSideStreamClient) SendMsg(v any) error {
return x.ClientStream.SendMsg(v)
}
func (x *serverSideStreamClient)CloseSend()error{
func (x *serverSideStreamClient) CloseSend() error {
return x.ClientStream.CloseSend()

}
Expand All @@ -81,7 +81,7 @@ func (x *clientSideStreamClient) Send(m protoreflect.ProtoMessage) error {
func (x *clientSideStreamClient) CloseSend() error {
return x.ClientStream.CloseSend()
}
func (x *clientSideStreamClient)RecvMsg(v any)error{
func (x *clientSideStreamClient) RecvMsg(v any) error {
return x.ClientStream.RecvMsg(v)
}
func (x *clientSideStreamClient) CloseAndRecv() (protoreflect.ProtoMessage, error) {
Expand Down
4 changes: 2 additions & 2 deletions gateway/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ func (w *websocketForwarder) Flush() {
}
func (w *websocketForwarder) Close() error {
// w.websocket.NextWriter()
return w.websocket.WriteMessage(websocket.CloseMessage,websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
return w.websocket.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
}
func (w *websocketForwarder)CloseConn() error{
func (w *websocketForwarder) CloseConn() error {
return w.websocket.Close()
}
func (w *websocketForwarder) NextReader() (io.Reader, error) {
Expand Down
22 changes: 21 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,23 @@ require (
require (
dario.cat/mergo v1.0.0 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect
github.com/DATA-DOG/go-sqlmock v1.5.2 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect
github.com/ProtonMail/go-crypto v1.0.0 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cloudflare/circl v1.3.7 // indirect
github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect
github.com/cockroachdb/redact v1.1.5 // indirect
github.com/containerd/continuity v0.4.3 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/cyphar/filepath-securejoin v0.2.4 // indirect
github.com/docker/cli v26.1.3+incompatible // indirect
github.com/docker/docker v26.1.3+incompatible // indirect
github.com/docker/go-connections v0.5.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/getsentry/sentry-go v0.18.0 // indirect
Expand All @@ -114,21 +122,32 @@ require (
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/gopherjs/gopherjs v1.17.2 // indirect
github.com/imdario/mergo v0.3.16 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/jtolds/gls v4.20.0+incompatible // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/term v0.5.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.0 // indirect
github.com/opencontainers/runc v1.1.12 // indirect
github.com/ory/dockertest/v3 v3.10.0 // indirect
github.com/pjbgf/sha1cd v0.3.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/sergi/go-diff v1.3.1 // indirect
github.com/skeema/knownhosts v1.2.2 // indirect
github.com/smarty/assertions v1.15.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.etcd.io/etcd/client/pkg/v3 v3.5.13 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/mod v0.17.0 // indirect
Expand All @@ -137,6 +156,7 @@ require (
golang.org/x/tools v0.21.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240521202816-d264139d666e // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

// replace github.com/spark-lence/tiga => /data/work/spark-lence/tiga
Expand Down
Loading

0 comments on commit 133eb46

Please sign in to comment.