github.com/cloudwego/kitex@v0.9.0/server/invoke_test.go (about) 1 /* 2 * Copyright 2021 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package server 18 19 import ( 20 "context" 21 "strings" 22 "sync/atomic" 23 "testing" 24 25 "github.com/apache/thrift/lib/go/thrift" 26 27 "github.com/cloudwego/kitex/internal/mocks" 28 "github.com/cloudwego/kitex/internal/test" 29 "github.com/cloudwego/kitex/pkg/remote/trans/invoke" 30 "github.com/cloudwego/kitex/pkg/utils" 31 ) 32 33 // TestInvokerCall tests Invoker, call Kitex server just like SDK. 34 func TestInvokerCall(t *testing.T) { 35 var gotErr atomic.Value 36 invoker := NewInvoker(WithMetaHandler(noopMetahandler{}), WithErrorHandler(func(ctx context.Context, err error) error { 37 gotErr.Store(err) 38 return err 39 })) 40 41 err := invoker.RegisterService(mocks.ServiceInfo(), mocks.MyServiceHandler()) 42 if err != nil { 43 t.Fatal(err) 44 } 45 err = invoker.Init() 46 if err != nil { 47 t.Fatal(err) 48 } 49 50 args := mocks.NewMockArgs() 51 codec := utils.NewThriftMessageCodec() 52 53 // call success 54 b, _ := codec.Encode("mock", thrift.CALL, 0, args.(thrift.TStruct)) 55 msg := invoke.NewMessage(nil, nil) 56 err = msg.SetRequestBytes(b) 57 test.Assert(t, err == nil) 58 err = invoker.Call(msg) 59 if err != nil { 60 t.Fatal(err) 61 } 62 b, err = msg.GetResponseBytes() 63 if err != nil { 64 t.Fatal(err) 65 } 66 test.Assert(t, len(b) > 0) 67 test.Assert(t, gotErr.Load() == nil) 68 69 // call fails 70 b, _ = codec.Encode("mockError", thrift.CALL, 0, args.(thrift.TStruct)) 71 msg = invoke.NewMessage(nil, nil) 72 err = msg.SetRequestBytes(b) 73 test.Assert(t, err == nil) 74 err = invoker.Call(msg) 75 if err != nil { 76 t.Fatal(err) 77 } 78 test.Assert(t, strings.Contains(gotErr.Load().(error).Error(), "mockError")) 79 } 80 81 // TestInvokerInit test invoker init without service info, should fail 82 func TestInvokerInit(t *testing.T) { 83 // test init without register server info 84 invoker := NewInvoker() 85 err := invoker.Init() 86 test.Assert(t, err != nil) 87 test.Assert(t, strings.Contains(err.Error(), "run: no service. Use RegisterService to set one")) 88 89 err = invoker.RegisterService(mocks.ServiceInfo(), mocks.MyServiceHandler()) 90 test.Assert(t, err == nil) 91 }