github.com/polarismesh/polaris@v1.17.8/service/service_alias_test.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package service_test
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"regexp"
    24  	"strings"
    25  	"sync"
    26  	"testing"
    27  	"time"
    28  
    29  	apimodel "github.com/polarismesh/specification/source/go/api/v1/model"
    30  	apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage"
    31  	apitraffic "github.com/polarismesh/specification/source/go/api/v1/traffic_manage"
    32  	. "github.com/smartystreets/goconvey/convey"
    33  	"github.com/stretchr/testify/assert"
    34  	"google.golang.org/protobuf/types/known/wrapperspb"
    35  
    36  	api "github.com/polarismesh/polaris/common/api/v1"
    37  	"github.com/polarismesh/polaris/common/utils"
    38  	"github.com/polarismesh/polaris/service"
    39  )
    40  
    41  const defaultAliasNs = "Production"
    42  
    43  // 创建一个服务别名
    44  func (d *DiscoverTestSuit) createCommonAlias(service *apiservice.Service, alias string, aliasNamespace string, typ apiservice.AliasType) *apiservice.Response {
    45  	req := &apiservice.ServiceAlias{
    46  		Service:        service.Name,
    47  		Namespace:      service.Namespace,
    48  		Alias:          utils.NewStringValue(alias),
    49  		AliasNamespace: utils.NewStringValue(aliasNamespace),
    50  		Type:           typ,
    51  		Owners:         utils.NewStringValue("polaris"),
    52  	}
    53  	return d.DiscoverServer().CreateServiceAlias(d.DefaultCtx, req)
    54  }
    55  
    56  // 创建别名,并检查
    57  func (d *DiscoverTestSuit) createCommonAliasCheck(
    58  	t *testing.T, service *apiservice.Service, alias string, aliasNamespace string, typ apiservice.AliasType) *apiservice.Response {
    59  	resp := d.createCommonAlias(service, alias, aliasNamespace, typ)
    60  	if !respSuccess(resp) {
    61  		t.Fatalf("error : %s", resp.GetInfo().GetValue())
    62  	}
    63  	return resp
    64  }
    65  
    66  // 检查一个服务别名是否是sid
    67  func isSid(alias string) bool {
    68  	items := strings.Split(alias, ":")
    69  	if len(items) != 2 {
    70  		return false
    71  	}
    72  
    73  	for _, it := range items {
    74  		if ok, _ := regexp.MatchString("^[0-9]+$", it); !ok {
    75  			return false
    76  		}
    77  	}
    78  
    79  	return true
    80  }
    81  
    82  // 正常场景测试
    83  func TestCreateServiceAlias(t *testing.T) {
    84  
    85  	discoverSuit := &DiscoverTestSuit{}
    86  	if err := discoverSuit.Initialize(); err != nil {
    87  		t.Fatal(err)
    88  	}
    89  	defer discoverSuit.Destroy()
    90  
    91  	_, serviceResp := discoverSuit.createCommonService(t, 123)
    92  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
    93  
    94  	Convey("正常创建非Sid的别名", t, func() {
    95  		alias := fmt.Sprintf("alias.%d", time.Now().Unix())
    96  		resp := discoverSuit.createCommonAlias(serviceResp, alias, serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
    97  		defer discoverSuit.cleanServiceName(alias, serviceResp.GetNamespace().GetValue())
    98  		So(respSuccess(resp), ShouldEqual, true)
    99  		So(resp.Alias.Alias.Value, ShouldEqual, alias)
   100  	})
   101  
   102  	Convey("正常创建Sid别名", t, func() {
   103  		resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   104  		So(respSuccess(resp), ShouldEqual, true)
   105  		defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.GetNamespace().GetValue())
   106  		So(isSid(resp.Alias.Alias.Value), ShouldEqual, true)
   107  		t.Logf("alias sid: %s", resp.Alias.Alias.Value)
   108  	})
   109  
   110  	Convey("使用ctx带上的token可以创建成功", t, func() {
   111  		req := &apiservice.ServiceAlias{
   112  			Service:        serviceResp.Name,
   113  			Namespace:      serviceResp.Namespace,
   114  			AliasNamespace: serviceResp.Namespace,
   115  			Type:           apiservice.AliasType_CL5SID,
   116  		}
   117  		ctx := context.WithValue(discoverSuit.DefaultCtx, utils.StringContext("polaris-token"),
   118  			serviceResp.GetToken().GetValue())
   119  		resp := discoverSuit.DiscoverServer().CreateServiceAlias(ctx, req)
   120  		So(respSuccess(resp), ShouldEqual, true)
   121  		discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.GetNamespace().GetValue())
   122  
   123  		// 带上系统token,也可以成功
   124  		ctx = context.WithValue(discoverSuit.DefaultCtx, utils.StringContext("polaris-token"),
   125  			"polaris@12345678")
   126  		resp = discoverSuit.DiscoverServer().CreateServiceAlias(ctx, req)
   127  		So(respSuccess(resp), ShouldEqual, true)
   128  		discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.GetNamespace().GetValue())
   129  	})
   130  	Convey("不允许为别名创建别名", t, func() {
   131  		resp := discoverSuit.NamespaceServer().CreateNamespace(discoverSuit.DefaultCtx, &apimodel.Namespace{
   132  			Name: &wrapperspb.StringValue{Value: defaultAliasNs},
   133  		})
   134  		if !respSuccess(resp) {
   135  			t.Fatalf("error : %s", resp.GetInfo().GetValue())
   136  		}
   137  
   138  		resp = discoverSuit.createCommonAliasCheck(t, serviceResp, "", defaultAliasNs, apiservice.AliasType_CL5SID)
   139  		defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.Namespace.Value)
   140  
   141  		service := &apiservice.Service{
   142  			Name:      resp.Alias.Alias,
   143  			Namespace: serviceResp.Namespace,
   144  			Token:     serviceResp.Token,
   145  		}
   146  		repeatedResp := discoverSuit.createCommonAlias(service, "", defaultAliasNs, apiservice.AliasType_CL5SID)
   147  		if respSuccess(repeatedResp) {
   148  			t.Fatalf("error: %+v", repeatedResp)
   149  		}
   150  		t.Logf("%+v", repeatedResp)
   151  	})
   152  }
   153  
   154  // 重点测试创建sid别名的场景
   155  // 注意:该测试函数出错的情况,会遗留一些测试数据无法清理 TODO
   156  func TestCreateSid(t *testing.T) {
   157  
   158  	discoverSuit := &DiscoverTestSuit{}
   159  	if err := discoverSuit.Initialize(); err != nil {
   160  		t.Fatal(err)
   161  	}
   162  	defer discoverSuit.Destroy()
   163  
   164  	Convey("创建不同命名空间的sid,可以返回符合规范的sid", t, func() {
   165  		for namespace, layout := range service.Namespace2SidLayoutID {
   166  			service := &apiservice.Service{
   167  				Name:      utils.NewStringValue("sid-test-xxx"),
   168  				Namespace: utils.NewStringValue(namespace),
   169  				Revision:  utils.NewStringValue("revision111"),
   170  				Owners:    utils.NewStringValue("owners111"),
   171  			}
   172  			discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue())
   173  			serviceResp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
   174  			t.Logf("resp : %s", serviceResp.GetInfo().GetValue())
   175  			So(respSuccess(serviceResp), ShouldEqual, true)
   176  
   177  			aliasResp := discoverSuit.createCommonAlias(serviceResp.Responses[0].Service, "", namespace, apiservice.AliasType_CL5SID)
   178  			So(respSuccess(aliasResp), ShouldEqual, true)
   179  			modID, cmdID := parseStr2Sid(aliasResp.GetAlias().GetAlias().GetValue())
   180  			So(modID, ShouldNotEqual, uint32(0))
   181  			So(cmdID, ShouldNotEqual, uint32(0))
   182  			So(modID>>6, ShouldBeGreaterThanOrEqualTo, 3000001) // module
   183  			So(modID&63, ShouldEqual, layout)                   // 根据保留字段标识服务名
   184  			So(aliasResp.GetAlias().GetNamespace().GetValue(), ShouldEqual, namespace)
   185  			discoverSuit.cleanServiceName(aliasResp.GetAlias().GetAlias().GetValue(), namespace)
   186  			discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue())
   187  		}
   188  	})
   189  	Convey("非默认的5个命名空间,不允许创建sid别名", t, func() {
   190  		namespace := &apimodel.Namespace{
   191  			Name:   utils.NewStringValue("other-namespace-xxx"),
   192  			Owners: utils.NewStringValue("aaa"),
   193  		}
   194  		So(respSuccess(discoverSuit.NamespaceServer().CreateNamespace(discoverSuit.DefaultCtx, namespace)), ShouldEqual, true)
   195  		defer discoverSuit.cleanNamespace(namespace.Name.Value)
   196  
   197  		service := &apiservice.Service{
   198  			Name:      utils.NewStringValue("sid-test-xxx"),
   199  			Namespace: utils.NewStringValue(namespace.Name.Value),
   200  			Revision:  utils.NewStringValue("revision111"),
   201  			Owners:    utils.NewStringValue("owners111"),
   202  		}
   203  		serviceResp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
   204  		So(respSuccess(serviceResp), ShouldEqual, true)
   205  		defer discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue())
   206  		aliasResp := discoverSuit.createCommonAlias(serviceResp.Responses[0].Service, "", namespace.Name.Value, apiservice.AliasType_CL5SID)
   207  		So(respSuccess(aliasResp), ShouldEqual, false)
   208  		t.Logf("%s", aliasResp.GetInfo().GetValue())
   209  	})
   210  }
   211  
   212  // 并发测试
   213  func TestConcurrencyCreateSid(t *testing.T) {
   214  
   215  	discoverSuit := &DiscoverTestSuit{}
   216  	if err := discoverSuit.Initialize(); err != nil {
   217  		t.Fatal(err)
   218  	}
   219  	defer discoverSuit.Destroy()
   220  
   221  	_, serviceResp := discoverSuit.createCommonService(t, 234)
   222  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   223  
   224  	Convey("并发创建sid别名,sid不会重复", t, func() {
   225  		c := 20
   226  		var wg sync.WaitGroup
   227  		resultCh := make(chan *apiservice.Response, 1)
   228  		results := make([]*apiservice.Response, 0, 200)
   229  		shutdown := make(chan struct{})
   230  
   231  		go func() {
   232  			for {
   233  				select {
   234  				case result := <-resultCh:
   235  					results = append(results, result)
   236  				case <-shutdown:
   237  					t.Log("[Alias] concurrency function exit")
   238  					return
   239  				}
   240  			}
   241  		}()
   242  
   243  		for i := 0; i < c; i++ {
   244  			wg.Add(1)
   245  			go func(index int) {
   246  				defer func() {
   247  					t.Logf("[Alias] finish creating alias sid func index(%d)", index)
   248  					wg.Done()
   249  				}()
   250  				resp := discoverSuit.createCommonAlias(
   251  					serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   252  				resultCh <- resp
   253  			}(i)
   254  		}
   255  
   256  		wg.Wait()
   257  		time.Sleep(time.Second)
   258  		close(shutdown)
   259  
   260  		repeated := make(map[string]bool)
   261  		for i := 0; i < c; i++ {
   262  			resp := results[i]
   263  			So(respSuccess(resp), ShouldEqual, true)
   264  			defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.GetNamespace().GetValue())
   265  			So(isSid(resp.Alias.Alias.Value), ShouldEqual, true)
   266  			repeated[resp.Alias.Alias.Value] = true
   267  		}
   268  		// 检查是否重复,必须是200个
   269  		So(len(repeated), ShouldEqual, c)
   270  	})
   271  }
   272  
   273  // 异常测试
   274  func TestExceptCreateAlias(t *testing.T) {
   275  
   276  	discoverSuit := &DiscoverTestSuit{}
   277  	if err := discoverSuit.Initialize(); err != nil {
   278  		t.Fatal(err)
   279  	}
   280  	defer discoverSuit.Destroy()
   281  
   282  	_, serviceResp := discoverSuit.createCommonService(t, 345)
   283  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   284  
   285  	Convey("参数缺失,报错", t, func() {
   286  		noService := &apiservice.Service{}
   287  		resp := discoverSuit.createCommonAlias(
   288  			noService, "x1.x2.x3", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   289  		So(respSuccess(resp), ShouldEqual, false)
   290  
   291  		noService.Name = utils.NewStringValue("123")
   292  		resp = discoverSuit.createCommonAlias(
   293  			noService, "x1.x2.x3", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   294  		So(respSuccess(resp), ShouldEqual, false)
   295  
   296  		noService.Namespace = utils.NewStringValue("456")
   297  		resp = discoverSuit.createCommonAlias(
   298  			noService, "x1.x2.x3", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   299  		So(respSuccess(resp), ShouldEqual, false)
   300  
   301  		noService.Token = utils.NewStringValue("567")
   302  		resp = discoverSuit.createCommonAlias(noService, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   303  		So(respSuccess(resp), ShouldEqual, false)
   304  		t.Logf("return code: %d", resp.Code.Value)
   305  	})
   306  
   307  	Convey("不存在的源服务,报错", t, func() {
   308  		noService := &apiservice.Service{
   309  			Name:      utils.NewStringValue("my.service.2020.02.19"),
   310  			Namespace: utils.NewStringValue("123123"),
   311  			Token:     utils.NewStringValue("aaa"),
   312  		}
   313  		resp := discoverSuit.createCommonAlias(noService, "x1.x2.x3", noService.Namespace.GetValue(), apiservice.AliasType_DEFAULT)
   314  		So(respSuccess(resp), ShouldEqual, false)
   315  		t.Logf("return code: %d", resp.Code.Value)
   316  		So(resp.Code.Value, ShouldEqual, api.NotFoundService)
   317  	})
   318  
   319  	Convey("同名alias,报错", t, func() {
   320  		resp := discoverSuit.createCommonAlias(
   321  			serviceResp, "x1.x2.x3", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   322  		So(respSuccess(resp), ShouldEqual, true)
   323  		defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.GetNamespace().GetValue())
   324  
   325  		resp = discoverSuit.createCommonAlias(
   326  			serviceResp, "x1.x2.x3", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   327  		So(respSuccess(resp), ShouldEqual, false)
   328  		t.Logf("same alias return code: %d", resp.Code.Value)
   329  	})
   330  
   331  	Convey("目标服务已经是一个别名", t, func() {
   332  		resp := discoverSuit.createCommonAlias(
   333  			serviceResp, "x1.x2.x3.x4", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   334  		So(respSuccess(resp), ShouldEqual, true)
   335  		defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.GetNamespace().GetValue())
   336  
   337  		resp = discoverSuit.createCommonAlias(
   338  			&apiservice.Service{
   339  				Name:      utils.NewStringValue("x1.x2.x3.x4"),
   340  				Namespace: serviceResp.GetNamespace(),
   341  			}, "x1.x2.x3.x5", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   342  		So(respSuccess(resp), ShouldEqual, false)
   343  		assert.Equal(t, apimodel.Code_NotAllowCreateAliasForAlias, apimodel.Code(resp.GetCode().GetValue()))
   344  		t.Logf("same alias return code: %d", resp.Code.Value)
   345  	})
   346  
   347  	Convey("鉴权失败,报错", t, func() {
   348  		service := &apiservice.Service{
   349  			Name:      serviceResp.Name,
   350  			Namespace: serviceResp.Namespace,
   351  			Token:     utils.NewStringValue("123123123"),
   352  		}
   353  
   354  		oldCtx := discoverSuit.DefaultCtx
   355  
   356  		discoverSuit.DefaultCtx = context.Background()
   357  
   358  		defer func() {
   359  			discoverSuit.DefaultCtx = oldCtx
   360  		}()
   361  
   362  		resp := discoverSuit.createCommonAlias(service, "x1.x2.x3", service.Namespace.GetValue(), apiservice.AliasType_DEFAULT)
   363  		So(respSuccess(resp), ShouldEqual, false)
   364  		t.Logf("error token, return code: %d", resp.Code.Value)
   365  	})
   366  
   367  	Convey("指向的服务不存在(新接口)", t, func() {
   368  		_, serviceResp2 := discoverSuit.createCommonService(t, 2)
   369  		discoverSuit.cleanServiceName(serviceResp2.GetName().GetValue(), serviceResp2.GetNamespace().GetValue())
   370  		resp := discoverSuit.createCommonAlias(serviceResp2, "", serviceResp2.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   371  		if respSuccess(resp) {
   372  			t.Fatalf("error: %+v", resp)
   373  		}
   374  		t.Logf("%+v", resp)
   375  	})
   376  }
   377  
   378  // 别名修改的测试
   379  func TestUpdateServiceAlias(t *testing.T) {
   380  
   381  	discoverSuit := &DiscoverTestSuit{}
   382  	if err := discoverSuit.Initialize(); err != nil {
   383  		t.Fatal(err)
   384  	}
   385  	defer discoverSuit.Destroy()
   386  
   387  	_, serviceResp := discoverSuit.createCommonService(t, 3)
   388  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   389  	Convey("修改别名负责人", t, func() {
   390  		resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   391  		So(respSuccess(resp), ShouldEqual, true)
   392  		defer discoverSuit.cleanServiceName(resp.GetAlias().GetAlias().GetValue(), serviceResp.GetNamespace().GetValue())
   393  
   394  		// 修改别名负责人
   395  		req := &apiservice.ServiceAlias{
   396  			Service:        resp.GetAlias().GetService(),
   397  			Namespace:      resp.GetAlias().GetNamespace(),
   398  			Alias:          resp.GetAlias().GetAlias(),
   399  			AliasNamespace: resp.GetAlias().GetNamespace(),
   400  			Owners:         utils.NewStringValue("alias-owner-new"),
   401  			ServiceToken:   resp.GetAlias().GetServiceToken(),
   402  		}
   403  
   404  		repeatedResp := discoverSuit.DiscoverServer().UpdateServiceAlias(discoverSuit.DefaultCtx, req)
   405  		So(respSuccess(repeatedResp), ShouldEqual, true)
   406  
   407  		query := map[string]string{
   408  			"alias":     req.GetAlias().GetValue(),
   409  			"namespace": req.GetNamespace().GetValue(),
   410  		}
   411  		aliasResponse := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   412  		// 判断负责人是否一致
   413  		So(aliasResponse.GetAliases()[0].GetOwners().GetValue(), ShouldEqual, "alias-owner-new")
   414  		t.Logf("pass, owner is %v", aliasResponse.GetAliases()[0].GetOwners().GetValue())
   415  	})
   416  
   417  	Convey("修改指向服务", t, func() {
   418  		resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   419  		So(respSuccess(resp), ShouldEqual, true)
   420  		defer discoverSuit.cleanServiceName(resp.GetAlias().GetAlias().GetValue(), serviceResp.GetNamespace().GetValue())
   421  
   422  		// 创建新的服务
   423  		_, serviceResp2 := discoverSuit.createCommonService(t, 4)
   424  		defer discoverSuit.cleanServiceName(serviceResp2.GetName().GetValue(), serviceResp2.GetNamespace().GetValue())
   425  
   426  		// 修改别名指向
   427  		req := &apiservice.ServiceAlias{
   428  			Service:        serviceResp2.GetName(),
   429  			Namespace:      serviceResp2.GetNamespace(),
   430  			Alias:          resp.GetAlias().GetAlias(),
   431  			AliasNamespace: serviceResp2.GetNamespace(),
   432  			Owners:         resp.GetAlias().GetOwners(),
   433  			Comment:        resp.GetAlias().GetComment(),
   434  			ServiceToken:   resp.GetAlias().GetServiceToken(),
   435  		}
   436  
   437  		repeatedResp := discoverSuit.DiscoverServer().UpdateServiceAlias(discoverSuit.DefaultCtx, req)
   438  		So(respSuccess(repeatedResp), ShouldEqual, true)
   439  
   440  		query := map[string]string{
   441  			"alias":     req.GetAlias().GetValue(),
   442  			"namespace": req.GetNamespace().GetValue(),
   443  		}
   444  		aliasResponse := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   445  		// 判断指向服务是否一致
   446  		So(aliasResponse.GetAliases()[0].GetService().GetValue(), ShouldEqual, serviceResp2.GetName().GetValue())
   447  		t.Logf("pass, service is %v", aliasResponse.GetAliases()[0].GetService().GetValue())
   448  	})
   449  
   450  	Convey("要指向的服务不存在", t, func() {
   451  		resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   452  		So(respSuccess(resp), ShouldEqual, true)
   453  		defer discoverSuit.cleanServiceName(resp.GetAlias().GetAlias().GetValue(), serviceResp.GetNamespace().GetValue())
   454  
   455  		// 创建新的服务并删除
   456  		_, serviceResp2 := discoverSuit.createCommonService(t, 4)
   457  		discoverSuit.cleanServiceName(serviceResp2.GetName().GetValue(), serviceResp2.GetNamespace().GetValue())
   458  
   459  		// 修改别名指向
   460  		req := &apiservice.ServiceAlias{
   461  			Service:      serviceResp2.GetName(),
   462  			Namespace:    serviceResp2.GetNamespace(),
   463  			Alias:        resp.GetAlias().GetAlias(),
   464  			Owners:       resp.GetAlias().GetOwners(),
   465  			Comment:      resp.GetAlias().GetComment(),
   466  			ServiceToken: resp.GetAlias().GetServiceToken(),
   467  		}
   468  		repeatedResp := discoverSuit.DiscoverServer().UpdateServiceAlias(discoverSuit.DefaultCtx, req)
   469  		if respSuccess(repeatedResp) {
   470  			t.Fatalf("error: %+v", repeatedResp)
   471  		}
   472  		t.Logf("%+v", repeatedResp)
   473  	})
   474  
   475  	Convey("鉴权失败", t, func() {
   476  		resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   477  		So(respSuccess(resp), ShouldEqual, true)
   478  		defer discoverSuit.cleanServiceName(resp.GetAlias().GetAlias().GetValue(), serviceResp.GetNamespace().GetValue())
   479  		// 修改service token
   480  		req := resp.GetAlias()
   481  		req.ServiceToken = utils.NewStringValue("")
   482  
   483  		repeatedResp := discoverSuit.DiscoverServer().UpdateServiceAlias(context.Background(), req)
   484  
   485  		if respSuccess(repeatedResp) {
   486  			t.Fatalf("error: %+v", repeatedResp)
   487  		}
   488  		t.Logf("%+v", repeatedResp)
   489  	})
   490  }
   491  
   492  // 别名删除
   493  func TestDeleteServiceAlias(t *testing.T) {
   494  
   495  	discoverSuit := &DiscoverTestSuit{}
   496  	if err := discoverSuit.Initialize(); err != nil {
   497  		t.Fatal(err)
   498  	}
   499  	defer discoverSuit.Destroy()
   500  
   501  	_, serviceResp := discoverSuit.createCommonService(t, 201)
   502  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   503  	Convey("通过服务别名删除接口可以直接删除别名", t, func() {
   504  		resp := discoverSuit.createCommonAlias(serviceResp, serviceResp.Name.GetValue()+"_alias", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_DEFAULT)
   505  		So(respSuccess(resp), ShouldEqual, true)
   506  		defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, resp.Alias.AliasNamespace.Value)
   507  		discoverSuit.removeCommonServiceAliases(t, []*apiservice.ServiceAlias{resp.Alias})
   508  
   509  		query := map[string]string{"name": resp.Alias.Alias.Value}
   510  		queryResp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, query)
   511  		So(respSuccess(queryResp), ShouldEqual, true)
   512  		So(len(queryResp.Services), ShouldEqual, 0)
   513  	})
   514  
   515  	Convey("通过ctx带上token,可以删除别名成功", t, func() {
   516  		resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   517  		So(respSuccess(resp), ShouldEqual, true)
   518  		defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.Namespace.Value)
   519  
   520  		ctx := context.WithValue(discoverSuit.DefaultCtx, utils.StringContext("polaris-token"),
   521  			"polaris@12345678")
   522  		So(respSuccess(discoverSuit.DiscoverServer().DeleteServiceAliases(ctx, []*apiservice.ServiceAlias{resp.Alias})), ShouldEqual, true)
   523  	})
   524  
   525  }
   526  
   527  // 服务实例与服务路由关联测试
   528  func TestServiceAliasRelated(t *testing.T) {
   529  
   530  	discoverSuit := &DiscoverTestSuit{}
   531  	if err := discoverSuit.Initialize(); err != nil {
   532  		t.Fatal(err)
   533  	}
   534  	defer discoverSuit.Destroy()
   535  
   536  	_, serviceResp := discoverSuit.createCommonService(t, 202)
   537  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   538  	resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   539  	if !respSuccess(resp) {
   540  		t.Fatalf("errror")
   541  	}
   542  	defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.Namespace.Value)
   543  	Convey("实例新建,不允许为别名新建实例", t, func() {
   544  		instance := &apiservice.Instance{
   545  			Service:      resp.Alias.Alias,
   546  			Namespace:    serviceResp.Namespace,
   547  			ServiceToken: serviceResp.Token,
   548  			Host:         utils.NewStringValue("1.12.123.132"),
   549  			Port:         utils.NewUInt32Value(8080),
   550  		}
   551  		instanceResp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instance})
   552  		So(respSuccess(instanceResp), ShouldEqual, false)
   553  		t.Logf("alias create instance ret code(%d), msg(%s)",
   554  			instanceResp.Code.Value, instanceResp.Info.Value)
   555  	})
   556  	Convey("实例Discover,别名查询实例,返回源服务的实例信息", t, func() {
   557  		_, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 123)
   558  		defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue())
   559  		_ = discoverSuit.DiscoverServer().Cache().TestUpdate()
   560  		service := &apiservice.Service{Name: resp.Alias.Alias, Namespace: resp.Alias.Namespace}
   561  		disResp := discoverSuit.DiscoverServer().ServiceInstancesCache(discoverSuit.DefaultCtx, service)
   562  		So(respSuccess(disResp), ShouldEqual, true)
   563  		So(len(disResp.Instances), ShouldEqual, 1)
   564  	})
   565  	Convey("路由新建,不允许为别名新建路由", t, func() {
   566  		routing := &apitraffic.Routing{
   567  			Service:      resp.Alias.Alias,
   568  			Namespace:    resp.Alias.Namespace,
   569  			ServiceToken: serviceResp.Token,
   570  			Inbounds:     make([]*apitraffic.Route, 0),
   571  		}
   572  		routingResp := discoverSuit.DiscoverServer().CreateRoutingConfigs(discoverSuit.DefaultCtx, []*apitraffic.Routing{routing})
   573  		So(respSuccess(routingResp), ShouldEqual, false)
   574  		t.Logf("create routing ret code(%d), info(%s)", routingResp.Code.Value, routingResp.Info.Value)
   575  	})
   576  	// Convey("路由Discover,别名查询路由,返回源服务的路由信息", t, func() {
   577  	// 	discoverSuit.createCommonRoutingConfig(t, serviceResp, 1, 0) // in=1, out=0
   578  	// 	defer discoverSuit.cleanCommonRoutingConfig(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   579  
   580  	// 	time.Sleep(discoverSuit.updateCacheInterval)
   581  	// 	service := &apiservice.Service{Name: resp.Alias.Alias, Namespace: resp.Alias.Namespace}
   582  	// 	disResp := discoverSuit.DiscoverServer().GetRoutingConfigWithCache(discoverSuit.DefaultCtx, service)
   583  	// 	So(respSuccess(disResp), ShouldEqual, true)
   584  	// 	So(len(disResp.Routing.Inbounds), ShouldEqual, 1)
   585  	// 	So(len(disResp.Routing.Outbounds), ShouldEqual, 0)
   586  	// })
   587  }
   588  
   589  // 测试获取别名列表
   590  func TestGetServiceAliases(t *testing.T) {
   591  
   592  	discoverSuit := &DiscoverTestSuit{}
   593  	if err := discoverSuit.Initialize(); err != nil {
   594  		t.Fatal(err)
   595  	}
   596  	defer discoverSuit.Destroy()
   597  
   598  	_, serviceResp := discoverSuit.createCommonService(t, 203)
   599  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   600  
   601  	var aliases []*apiservice.Response
   602  	count := 5
   603  	for i := 0; i < count; i++ {
   604  		resp := discoverSuit.createCommonAlias(serviceResp, "", serviceResp.GetNamespace().GetValue(), apiservice.AliasType_CL5SID)
   605  		if !respSuccess(resp) {
   606  			t.Fatalf("error: %+v", resp)
   607  		}
   608  		defer discoverSuit.cleanServiceName(resp.Alias.Alias.Value, serviceResp.Namespace.Value)
   609  		aliases = append(aliases, resp)
   610  	}
   611  
   612  	Convey("可以查询到全量别名", t, func() {
   613  		resp := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, nil)
   614  		So(respSuccess(resp), ShouldEqual, true)
   615  		So(len(resp.Aliases), ShouldBeGreaterThanOrEqualTo, count)
   616  		So(resp.Amount.Value, ShouldBeGreaterThanOrEqualTo, count)
   617  	})
   618  	Convey("offset,limit测试", t, func() {
   619  		query := map[string]string{"offset": "0", "limit": "100"}
   620  		resp := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   621  		So(respSuccess(resp), ShouldEqual, true)
   622  		So(len(resp.Aliases), ShouldBeGreaterThanOrEqualTo, count)
   623  		So(resp.Amount.Value, ShouldBeGreaterThanOrEqualTo, count)
   624  
   625  		query["limit"] = "0"
   626  		resp = discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   627  		So(respSuccess(resp), ShouldEqual, true)
   628  		So(len(resp.Aliases), ShouldEqual, 0)
   629  		So(resp.Amount.Value, ShouldBeGreaterThanOrEqualTo, count)
   630  	})
   631  	Convey("不合法的过滤条件", t, func() {
   632  		query := map[string]string{"xxx": "1", "limit": "100"}
   633  		resp := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   634  		So(respSuccess(resp), ShouldEqual, false)
   635  	})
   636  	Convey("过滤条件可以生效", t, func() {
   637  		query := map[string]string{
   638  			"alias":     aliases[2].Alias.Alias.Value,
   639  			"service":   serviceResp.Name.Value,
   640  			"namespace": serviceResp.Namespace.Value,
   641  		}
   642  		resp := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   643  		So(respSuccess(resp), ShouldEqual, true)
   644  		So(len(resp.Aliases), ShouldEqual, 1)
   645  		So(resp.Amount.Value, ShouldEqual, 1)
   646  	})
   647  	Convey("找不到别名", t, func() {
   648  		query := map[string]string{"alias": "x1.1.x2.x3"}
   649  		resp := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   650  		So(respSuccess(resp), ShouldEqual, true)
   651  		So(len(resp.Aliases), ShouldEqual, 0)
   652  		So(resp.Amount.Value, ShouldEqual, 0)
   653  	})
   654  	// Convey("支持owner过滤", t, func() {
   655  	// 	query := map[string]string{"owner": "service-owner-203"}
   656  	// 	resp := discoverSuit.DiscoverServer().GetServiceAliases(discoverSuit.DefaultCtx, query)
   657  	// 	So(respSuccess(resp), ShouldEqual, true)
   658  	// 	So(len(resp.Aliases), ShouldEqual, count)
   659  	// 	So(resp.Amount.Value, ShouldEqual, count)
   660  	// })
   661  }
   662  
   663  // test对serviceAlias字段进行校验
   664  func TestCheckServiceAliasFieldLen(t *testing.T) {
   665  
   666  	discoverSuit := &DiscoverTestSuit{}
   667  	if err := discoverSuit.Initialize(); err != nil {
   668  		t.Fatal(err)
   669  	}
   670  	defer discoverSuit.Destroy()
   671  
   672  	serviceAlias := &apiservice.ServiceAlias{
   673  		Service:        utils.NewStringValue("test-123"),
   674  		Namespace:      utils.NewStringValue("Production"),
   675  		Alias:          utils.NewStringValue("0"),
   676  		AliasNamespace: utils.NewStringValue("Production"),
   677  		Type:           apiservice.AliasType_DEFAULT,
   678  		Owners:         utils.NewStringValue("alias-owner"),
   679  		Comment:        utils.NewStringValue("comment"),
   680  	}
   681  	t.Run("服务名超长", func(t *testing.T) {
   682  		str := genSpecialStr(129)
   683  		oldService := serviceAlias.Service
   684  		serviceAlias.Service = utils.NewStringValue(str)
   685  		resp := discoverSuit.DiscoverServer().CreateServiceAlias(discoverSuit.DefaultCtx, serviceAlias)
   686  		serviceAlias.Service = oldService
   687  		if resp.Code.Value != api.InvalidServiceName {
   688  			t.Fatalf("%+v", resp)
   689  		}
   690  	})
   691  	t.Run("命名空间超长", func(t *testing.T) {
   692  		str := genSpecialStr(129)
   693  		oldNamespace := serviceAlias.Namespace
   694  		serviceAlias.Namespace = utils.NewStringValue(str)
   695  		resp := discoverSuit.DiscoverServer().CreateServiceAlias(discoverSuit.DefaultCtx, serviceAlias)
   696  		serviceAlias.Namespace = oldNamespace
   697  		if resp.Code.Value != api.InvalidNamespaceName {
   698  			t.Fatalf("%+v", resp)
   699  		}
   700  	})
   701  	t.Run("别名超长", func(t *testing.T) {
   702  		str := genSpecialStr(129)
   703  		oldAlias := serviceAlias.Alias
   704  		serviceAlias.Alias = utils.NewStringValue(str)
   705  		resp := discoverSuit.DiscoverServer().CreateServiceAlias(discoverSuit.DefaultCtx, serviceAlias)
   706  		serviceAlias.Alias = oldAlias
   707  		if resp.Code.Value != api.InvalidServiceAlias {
   708  			t.Fatalf("%+v", resp)
   709  		}
   710  	})
   711  	t.Run("服务别名comment超长", func(t *testing.T) {
   712  		str := genSpecialStr(1025)
   713  		oldComment := serviceAlias.Comment
   714  		serviceAlias.Comment = utils.NewStringValue(str)
   715  		resp := discoverSuit.DiscoverServer().CreateServiceAlias(discoverSuit.DefaultCtx, serviceAlias)
   716  		serviceAlias.Comment = oldComment
   717  		if resp.Code.Value != api.InvalidServiceAliasComment {
   718  			t.Fatalf("%+v", resp)
   719  		}
   720  	})
   721  	// t.Run("服务owner超长", func(t *testing.T) {
   722  	// 	str := genSpecialStr(1025)
   723  	// 	oldOwner := serviceAlias.Owners
   724  	// 	serviceAlias.Owners = utils.NewStringValue(str)
   725  	// 	resp := discoverSuit.DiscoverServer().CreateServiceAlias(discoverSuit.DefaultCtx, serviceAlias)
   726  	// 	serviceAlias.Owners = oldOwner
   727  	// 	if resp.Code.Value != api.InvalidServiceAliasOwners {
   728  	// 		t.Fatalf("%+v", resp)
   729  	// 	}
   730  	// })
   731  }
   732  
   733  // test测试别名的命名空间与服务名不一样
   734  func TestServiceAliasDifferentNamespace(t *testing.T) {
   735  
   736  	discoverSuit := &DiscoverTestSuit{}
   737  	if err := discoverSuit.Initialize(); err != nil {
   738  		t.Fatal(err)
   739  	}
   740  	defer discoverSuit.Destroy()
   741  
   742  	_, serviceResp := discoverSuit.createCommonService(t, 203)
   743  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   744  	Convey("正常创建不一样命名空间的非Sid的别名", t, func() {
   745  		alias := fmt.Sprintf("alias.%d", time.Now().Unix())
   746  		resp := discoverSuit.createCommonAlias(serviceResp, alias, defaultAliasNs, apiservice.AliasType_DEFAULT)
   747  		defer discoverSuit.cleanServiceName(alias, defaultAliasNs)
   748  		So(respSuccess(resp), ShouldEqual, true)
   749  		So(resp.Alias.Alias.Value, ShouldEqual, alias)
   750  	})
   751  }