github.com/cloudwego/kitex@v0.9.0/pkg/generic/map_test/generic_init.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 test ...
    18  package test
    19  
    20  import (
    21  	"context"
    22  	"encoding/base64"
    23  	"errors"
    24  	"fmt"
    25  	"net"
    26  	"reflect"
    27  	"time"
    28  
    29  	"github.com/cloudwego/kitex/client"
    30  	"github.com/cloudwego/kitex/client/genericclient"
    31  	kt "github.com/cloudwego/kitex/internal/mocks/thrift"
    32  	"github.com/cloudwego/kitex/internal/test"
    33  	"github.com/cloudwego/kitex/pkg/generic"
    34  	"github.com/cloudwego/kitex/pkg/generic/descriptor"
    35  	"github.com/cloudwego/kitex/pkg/rpcinfo"
    36  	"github.com/cloudwego/kitex/pkg/serviceinfo"
    37  	"github.com/cloudwego/kitex/server"
    38  	"github.com/cloudwego/kitex/server/genericserver"
    39  )
    40  
    41  var reqMsg = map[string]interface{}{
    42  	"Msg": "hello",
    43  	"InnerBase": map[string]interface{}{
    44  		"Base": map[string]interface{}{
    45  			"LogID": "log_id_inner",
    46  		},
    47  	},
    48  	"Base": map[string]interface{}{
    49  		"LogID": "log_id",
    50  	},
    51  }
    52  
    53  var errResp = "Test Error"
    54  
    55  func newGenericClient(destService string, g generic.Generic, targetIPPort string) genericclient.Client {
    56  	var opts []client.Option
    57  	opts = append(opts, client.WithHostPorts(targetIPPort))
    58  	genericCli, _ := genericclient.NewClient(destService, g, opts...)
    59  	return genericCli
    60  }
    61  
    62  func newGenericServer(g generic.Generic, addr net.Addr, handler generic.Service) server.Server {
    63  	var opts []server.Option
    64  	opts = append(opts, server.WithServiceAddr(addr), server.WithExitWaitTime(time.Microsecond*10))
    65  	svr := genericserver.NewServer(handler, g, opts...)
    66  	go func() {
    67  		err := svr.Run()
    68  		if err != nil {
    69  			panic(err)
    70  		}
    71  	}()
    72  	test.WaitServerStart(addr.String())
    73  	return svr
    74  }
    75  
    76  // GenericServiceImpl ...
    77  type GenericServiceImpl struct{}
    78  
    79  // GenericCall ...
    80  func (g *GenericServiceImpl) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
    81  	buf := request.(map[string]interface{})
    82  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
    83  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
    84  	fmt.Printf("Recv: %v\n", buf)
    85  	fmt.Printf("Method: %s\n", method)
    86  	return buf, nil
    87  }
    88  
    89  type GenericServiceWithBase64Binary struct{}
    90  
    91  // GenericCall ...
    92  func (g *GenericServiceWithBase64Binary) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
    93  	buf := request.(map[string]interface{})
    94  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
    95  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
    96  	fmt.Printf("Recv: %v\n", buf)
    97  	fmt.Printf("Method: %s\n", method)
    98  	if buf["BinaryMsg"] != base64.StdEncoding.EncodeToString([]byte("hello")) {
    99  		return "", fmt.Errorf("BinaryMsg is not %s but %s", base64.StdEncoding.EncodeToString([]byte("hello")), buf["BinaryMsg"])
   100  	}
   101  	return buf, nil
   102  }
   103  
   104  type GenericServiceWithByteSliceImpl struct{}
   105  
   106  // GenericCall ...
   107  func (g *GenericServiceWithByteSliceImpl) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   108  	buf := request.(map[string]interface{})
   109  	rpcinfo := rpcinfo.GetRPCInfo(ctx)
   110  	fmt.Printf("Method from Ctx: %s\n", rpcinfo.Invocation().MethodName())
   111  	fmt.Printf("Recv: %v\n", buf)
   112  	fmt.Printf("Method: %s\n", method)
   113  	if !reflect.DeepEqual(buf["BinaryMsg"], []byte("hello")) {
   114  		return "", fmt.Errorf("BinaryMsg is not %s but %s", []byte("hello"), buf["BinaryMsg"])
   115  	}
   116  	return buf, nil
   117  }
   118  
   119  // GenericServiceErrorImpl ...
   120  type GenericServiceErrorImpl struct{}
   121  
   122  // GenericCall ...
   123  func (g *GenericServiceErrorImpl) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   124  	return response, errors.New(errResp)
   125  }
   126  
   127  // GenericServicePingImpl ...
   128  type GenericServicePingImpl struct{}
   129  
   130  // GenericCall ...
   131  func (g *GenericServicePingImpl) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   132  	msg := request.(string)
   133  	fmt.Printf("Recv: %v\n", msg)
   134  	return request, nil
   135  }
   136  
   137  // GenericServiceOnewayImpl ...
   138  type GenericServiceOnewayImpl struct{}
   139  
   140  // GenericCall ...
   141  func (g *GenericServiceOnewayImpl) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   142  	msg := request.(string)
   143  	fmt.Printf("Recv: %v\n", msg)
   144  	return descriptor.Void{}, nil
   145  }
   146  
   147  // GenericServiceVoidImpl ...
   148  type GenericServiceVoidImpl struct{}
   149  
   150  // GenericCall ...
   151  func (g *GenericServiceVoidImpl) GenericCall(ctx context.Context, method string, request interface{}) (response interface{}, err error) {
   152  	msg := request.(string)
   153  	fmt.Printf("Recv: %v\n", msg)
   154  	return descriptor.Void{}, nil
   155  }
   156  
   157  var (
   158  	mockReq = map[string]interface{}{
   159  		"Msg": "hello",
   160  		"strMap": map[interface{}]interface{}{
   161  			"mk1": "mv1",
   162  			"mk2": "mv2",
   163  		},
   164  		"strList": []interface{}{
   165  			"lv1", "lv2",
   166  		},
   167  	}
   168  	mockResp = "this is response"
   169  )
   170  
   171  // normal server
   172  func newMockServer(handler kt.Mock, addr net.Addr, opts ...server.Option) server.Server {
   173  	var options []server.Option
   174  	opts = append(opts, server.WithServiceAddr(addr), server.WithExitWaitTime(time.Microsecond*10))
   175  	options = append(options, opts...)
   176  
   177  	svr := server.NewServer(options...)
   178  	if err := svr.RegisterService(serviceInfo(), handler); err != nil {
   179  		panic(err)
   180  	}
   181  	go func() {
   182  		err := svr.Run()
   183  		if err != nil {
   184  			panic(err)
   185  		}
   186  	}()
   187  	test.WaitServerStart(addr.String())
   188  	return svr
   189  }
   190  
   191  func serviceInfo() *serviceinfo.ServiceInfo {
   192  	destService := "Mock"
   193  	handlerType := (*kt.Mock)(nil)
   194  	methods := map[string]serviceinfo.MethodInfo{
   195  		"Test": serviceinfo.NewMethodInfo(testHandler, newMockTestArgs, newMockTestResult, false),
   196  	}
   197  	svcInfo := &serviceinfo.ServiceInfo{
   198  		ServiceName: destService,
   199  		HandlerType: handlerType,
   200  		Methods:     methods,
   201  		Extra:       make(map[string]interface{}),
   202  	}
   203  	return svcInfo
   204  }
   205  
   206  func newMockTestArgs() interface{} {
   207  	return kt.NewMockTestArgs()
   208  }
   209  
   210  func newMockTestResult() interface{} {
   211  	return kt.NewMockTestResult()
   212  }
   213  
   214  func testHandler(ctx context.Context, handler, arg, result interface{}) error {
   215  	realArg := arg.(*kt.MockTestArgs)
   216  	realResult := result.(*kt.MockTestResult)
   217  	success, err := handler.(kt.Mock).Test(ctx, realArg.Req)
   218  	if err != nil {
   219  		return err
   220  	}
   221  	realResult.Success = &success
   222  	return nil
   223  }
   224  
   225  type mockImpl struct{}
   226  
   227  // Test ...
   228  func (m *mockImpl) Test(ctx context.Context, req *kt.MockReq) (r string, err error) {
   229  	if req.Msg != mockReq["Msg"] {
   230  		return "", fmt.Errorf("msg is not %s", mockReq)
   231  	}
   232  	sm, ok := mockReq["strMap"].(map[interface{}]interface{})
   233  	if !ok {
   234  		return "", fmt.Errorf("strmsg is not map[interface{}]interface{}")
   235  	}
   236  	for k, v := range sm {
   237  		if req.StrMap[k.(string)] != v.(string) {
   238  			return "", fmt.Errorf("strMsg is not %s", req.StrMap)
   239  		}
   240  	}
   241  	sl, ok := mockReq["strList"].([]interface{})
   242  	if !ok {
   243  		return "", fmt.Errorf("strlist is not %s", mockReq["strList"])
   244  	}
   245  	for idx := range sl {
   246  		if sl[idx].(string) != req.StrList[idx] {
   247  			return "", fmt.Errorf("strlist is not %s", mockReq)
   248  		}
   249  	}
   250  	return mockResp, nil
   251  }
   252  
   253  // ExceptionTest ...
   254  func (m *mockImpl) ExceptionTest(ctx context.Context, req *kt.MockReq) (r string, err error) {
   255  	return "", kt.NewException()
   256  }