github.com/polarismesh/polaris@v1.17.8/service/service_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  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"strconv"
    26  	"sync"
    27  	"testing"
    28  	"time"
    29  
    30  	"github.com/golang/mock/gomock"
    31  	apimodel "github.com/polarismesh/specification/source/go/api/v1/model"
    32  	apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage"
    33  	"github.com/smartystreets/goconvey/convey"
    34  	"github.com/stretchr/testify/assert"
    35  	"google.golang.org/protobuf/types/known/wrapperspb"
    36  
    37  	"github.com/polarismesh/polaris/auth"
    38  	"github.com/polarismesh/polaris/cache"
    39  	api "github.com/polarismesh/polaris/common/api/v1"
    40  	"github.com/polarismesh/polaris/common/model"
    41  	"github.com/polarismesh/polaris/common/utils"
    42  	"github.com/polarismesh/polaris/namespace"
    43  	"github.com/polarismesh/polaris/service"
    44  	"github.com/polarismesh/polaris/store"
    45  	"github.com/polarismesh/polaris/store/mock"
    46  )
    47  
    48  // 测试新增服务
    49  func TestCreateService(t *testing.T) {
    50  
    51  	t.Run("正常创建服务", func(t *testing.T) {
    52  		discoverSuit := &DiscoverTestSuit{}
    53  		if err := discoverSuit.Initialize(); err != nil {
    54  			t.Fatal(err)
    55  		}
    56  		serviceReq, serviceResp := discoverSuit.createCommonService(t, 9)
    57  
    58  		t.Cleanup(func() {
    59  			discoverSuit.cleanAllService()
    60  			discoverSuit.Destroy()
    61  		})
    62  
    63  		if serviceResp.GetName().GetValue() == serviceReq.GetName().GetValue() &&
    64  			serviceResp.GetNamespace().GetValue() == serviceReq.GetNamespace().GetValue() &&
    65  			serviceResp.GetToken().GetValue() != "" {
    66  			t.Logf("pass")
    67  		} else {
    68  			t.Fatalf("error: %+v", serviceResp)
    69  		}
    70  	})
    71  
    72  	t.Run("创建重复名字的服务,会返回失败", func(t *testing.T) {
    73  		discoverSuit := &DiscoverTestSuit{}
    74  		if err := discoverSuit.Initialize(); err != nil {
    75  			t.Fatal(err)
    76  		}
    77  
    78  		serviceReq, _ := discoverSuit.createCommonService(t, 9)
    79  		t.Cleanup(func() {
    80  			discoverSuit.cleanAllService()
    81  			discoverSuit.Destroy()
    82  		})
    83  
    84  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceReq})
    85  		if !respSuccess(resp) {
    86  			t.Logf("pass: %s", resp.GetInfo().GetValue())
    87  		} else {
    88  			t.Fatalf("error")
    89  		}
    90  	})
    91  
    92  	t.Run("创建服务,删除,再次创建,可以正常创建", func(t *testing.T) {
    93  		discoverSuit := &DiscoverTestSuit{}
    94  		if err := discoverSuit.Initialize(); err != nil {
    95  			t.Fatal(err)
    96  		}
    97  
    98  		serviceReq, serviceResp := discoverSuit.createCommonService(t, 100)
    99  		t.Cleanup(func() {
   100  			discoverSuit.cleanAllService()
   101  			discoverSuit.Destroy()
   102  		})
   103  
   104  		req := &apiservice.Service{
   105  			Name:      utils.NewStringValue(serviceResp.GetName().GetValue()),
   106  			Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()),
   107  			Token:     utils.NewStringValue(serviceResp.GetToken().GetValue()),
   108  		}
   109  		discoverSuit.removeCommonServices(t, []*apiservice.Service{req})
   110  
   111  		if resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceReq}); !respSuccess(resp) {
   112  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   113  		}
   114  
   115  		t.Logf("pass")
   116  	})
   117  	t.Run("并发创建不同服务", func(t *testing.T) {
   118  		discoverSuit := &DiscoverTestSuit{}
   119  		if err := discoverSuit.Initialize(); err != nil {
   120  			t.Fatal(err)
   121  		}
   122  		t.Cleanup(func() {
   123  			discoverSuit.cleanAllService()
   124  			discoverSuit.Destroy()
   125  		})
   126  
   127  		var wg sync.WaitGroup
   128  		for i := 0; i < 50; i++ {
   129  			wg.Add(1)
   130  			go func(index int) {
   131  				defer wg.Done()
   132  				serviceReq, _ := discoverSuit.createCommonService(t, index)
   133  				discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   134  			}(i)
   135  		}
   136  		wg.Wait()
   137  	})
   138  	t.Run("并发创建相同服务", func(t *testing.T) {
   139  		discoverSuit := &DiscoverTestSuit{}
   140  		if err := discoverSuit.Initialize(); err != nil {
   141  			t.Fatal(err)
   142  		}
   143  		t.Cleanup(func() {
   144  			discoverSuit.cleanAllService()
   145  			discoverSuit.Destroy()
   146  		})
   147  
   148  		var wg sync.WaitGroup
   149  		for i := 0; i < 50; i++ {
   150  			wg.Add(1)
   151  			go func(_ int) {
   152  				defer wg.Done()
   153  				serviceReq := genMainService(1)
   154  				resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceReq})
   155  
   156  				if resp.GetCode().GetValue() == uint32(apimodel.Code_ExistedResource) {
   157  					assert.True(t, len(resp.GetResponses()[0].GetService().GetId().GetValue()) > 0)
   158  				}
   159  			}(i)
   160  		}
   161  		wg.Wait()
   162  	})
   163  	t.Run("命名空间不存在,可以自动创建服务", func(t *testing.T) {
   164  		discoverSuit := &DiscoverTestSuit{}
   165  		if err := discoverSuit.Initialize(); err != nil {
   166  			t.Fatal(err)
   167  		}
   168  		t.Cleanup(func() {
   169  			discoverSuit.cleanAllService()
   170  			discoverSuit.Destroy()
   171  		})
   172  
   173  		service := &apiservice.Service{
   174  			Name:      utils.NewStringValue("abc"),
   175  			Namespace: utils.NewStringValue(utils.NewUUID()),
   176  			Owners:    utils.NewStringValue("my"),
   177  		}
   178  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
   179  		if !respSuccess(resp) {
   180  			t.Fatalf("error")
   181  		}
   182  		t.Logf("pass: %s", resp.GetInfo().GetValue())
   183  	})
   184  	t.Run("创建服务,metadata个数太多,报错", func(t *testing.T) {
   185  		discoverSuit := &DiscoverTestSuit{}
   186  		if err := discoverSuit.Initialize(); err != nil {
   187  			t.Fatal(err)
   188  		}
   189  		t.Cleanup(func() {
   190  			discoverSuit.cleanAllService()
   191  			discoverSuit.Destroy()
   192  		})
   193  
   194  		svc := &apiservice.Service{
   195  			Name:      utils.NewStringValue("999"),
   196  			Namespace: utils.NewStringValue("Polaris"),
   197  			Owners:    utils.NewStringValue("my"),
   198  		}
   199  		svc.Metadata = make(map[string]string)
   200  		for i := 0; i < service.MaxMetadataLength+1; i++ {
   201  			svc.Metadata[fmt.Sprintf("aa-%d", i)] = "value"
   202  		}
   203  		if resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{svc}); !respSuccess(resp) {
   204  			t.Logf("%s", resp.GetInfo().GetValue())
   205  		} else {
   206  			t.Fatalf("error")
   207  		}
   208  	})
   209  }
   210  
   211  // delete services
   212  func TestRemoveServices(t *testing.T) {
   213  
   214  	discoverSuit := &DiscoverTestSuit{}
   215  	if err := discoverSuit.Initialize(); err != nil {
   216  		t.Fatal(err)
   217  	}
   218  	defer discoverSuit.Destroy()
   219  
   220  	t.Run("删除单个服务,删除成功", func(t *testing.T) {
   221  		serviceReq, serviceResp := discoverSuit.createCommonService(t, 59)
   222  		defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   223  
   224  		req := &apiservice.Service{
   225  			Name:      utils.NewStringValue(serviceResp.GetName().GetValue()),
   226  			Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()),
   227  			Token:     utils.NewStringValue(serviceResp.GetToken().GetValue()),
   228  		}
   229  
   230  		// wait for data cache
   231  		time.Sleep(time.Second * 2)
   232  		discoverSuit.removeCommonServices(t, []*apiservice.Service{req})
   233  		out := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{"name": req.GetName().GetValue()})
   234  		if !respSuccess(out) {
   235  			t.Fatalf(out.GetInfo().GetValue())
   236  		}
   237  		if len(out.GetServices()) != 0 {
   238  			t.Fatalf("error: %d", len(out.GetServices()))
   239  		}
   240  	})
   241  
   242  	t.Run("删除多个服务,删除成功", func(t *testing.T) {
   243  		var reqs []*apiservice.Service
   244  		for i := 0; i < 100; i++ {
   245  			serviceReq, serviceResp := discoverSuit.createCommonService(t, i)
   246  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   247  			req := &apiservice.Service{
   248  				Name:      utils.NewStringValue(serviceResp.GetName().GetValue()),
   249  				Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()),
   250  				Token:     utils.NewStringValue(serviceResp.GetToken().GetValue()),
   251  			}
   252  			reqs = append(reqs, req)
   253  		}
   254  
   255  		// wait for data cache
   256  		time.Sleep(time.Second * 2)
   257  		discoverSuit.removeCommonServices(t, reqs)
   258  	})
   259  
   260  	t.Run("创建一个服务,马上删除,可以正常删除", func(t *testing.T) {
   261  		serviceReq, serviceResp := discoverSuit.createCommonService(t, 19)
   262  		defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   263  
   264  		req := &apiservice.Service{
   265  			Name:      utils.NewStringValue(serviceResp.GetName().GetValue()),
   266  			Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()),
   267  			Token:     utils.NewStringValue(serviceResp.GetToken().GetValue()),
   268  		}
   269  		discoverSuit.removeCommonServices(t, []*apiservice.Service{req})
   270  	})
   271  	// TODO 需要具体排查为什么在 github-action 无法跑过
   272  	// t.Run("创建服务和实例,删除服务,删除失败", func(t *testing.T) {
   273  	// 	serviceReq, serviceResp := discoverSuit.createCommonService(t, 19)
   274  	// 	defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   275  
   276  	// 	_, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 100)
   277  	// 	defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue())
   278  
   279  	// 	resp := discoverSuit.DiscoverServer().DeleteServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceResp})
   280  	// 	if !respSuccess(resp) {
   281  	// 		t.Logf("pass: %s", resp.GetInfo().GetValue())
   282  	// 	} else {
   283  	// 		t.Fatalf("error: %s", resp.GetInfo().GetValue())
   284  	// 	}
   285  	// })
   286  
   287  	t.Run("并发删除服务", func(t *testing.T) {
   288  		var wg sync.WaitGroup
   289  		for i := 0; i < 20; i++ {
   290  			serviceReq, serviceResp := discoverSuit.createCommonService(t, i)
   291  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   292  			req := &apiservice.Service{
   293  				Name:      utils.NewStringValue(serviceResp.GetName().GetValue()),
   294  				Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()),
   295  				Token:     utils.NewStringValue(serviceResp.GetToken().GetValue()),
   296  			}
   297  
   298  			wg.Add(1)
   299  			go func(reqs []*apiservice.Service) {
   300  				defer wg.Done()
   301  				discoverSuit.removeCommonServices(t, reqs)
   302  			}([]*apiservice.Service{req})
   303  		}
   304  		wg.Wait()
   305  	})
   306  }
   307  
   308  // 关联测试
   309  func TestDeleteService2(t *testing.T) {
   310  
   311  	discoverSuit := &DiscoverTestSuit{}
   312  	if err := discoverSuit.Initialize(); err != nil {
   313  		t.Fatal(err)
   314  	}
   315  	defer discoverSuit.Destroy()
   316  
   317  	t.Run("重复删除服务,返回成功", func(t *testing.T) {
   318  		serviceReq, serviceResp := discoverSuit.createCommonService(t, 20)
   319  		defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   320  
   321  		discoverSuit.removeCommonServices(t, []*apiservice.Service{serviceResp})
   322  		discoverSuit.removeCommonServices(t, []*apiservice.Service{serviceResp})
   323  	})
   324  	t.Run("存在别名的情况下,删除服务会失败", func(t *testing.T) {
   325  		serviceReq, serviceResp := discoverSuit.createCommonService(t, 20)
   326  		defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   327  
   328  		aliasResp1 := discoverSuit.createCommonAlias(serviceResp, "", defaultAliasNs, apiservice.AliasType_CL5SID)
   329  		defer discoverSuit.cleanServiceName(aliasResp1.Alias.Alias.Value, serviceResp.Namespace.Value)
   330  		aliasResp2 := discoverSuit.createCommonAlias(serviceResp, "", defaultAliasNs, apiservice.AliasType_CL5SID)
   331  		defer discoverSuit.cleanServiceName(aliasResp2.Alias.Alias.Value, serviceResp.Namespace.Value)
   332  
   333  		// 删除服务
   334  		resp := discoverSuit.DiscoverServer().DeleteServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceResp})
   335  		if respSuccess(resp) {
   336  			t.Fatalf("error")
   337  		}
   338  		t.Logf("pass: %s", resp.GetInfo().GetValue())
   339  	})
   340  }
   341  
   342  // 测试批量获取服务负责人
   343  func TestGetServiceOwner(t *testing.T) {
   344  
   345  	discoverSuit := &DiscoverTestSuit{}
   346  	if err := discoverSuit.Initialize(); err != nil {
   347  		t.Fatal(err)
   348  	}
   349  	defer discoverSuit.Destroy()
   350  
   351  	t.Run("服务个数为0,返回错误", func(t *testing.T) {
   352  		var reqs []*apiservice.Service
   353  		if resp := discoverSuit.DiscoverServer().GetServiceOwner(discoverSuit.DefaultCtx, reqs); !respSuccess(resp) {
   354  			t.Logf("pass: %s", resp.GetInfo().GetValue())
   355  		} else {
   356  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   357  		}
   358  	})
   359  
   360  	t.Run("服务个数超过100,返回错误", func(t *testing.T) {
   361  		reqs := make([]*apiservice.Service, 0, 101)
   362  		for i := 0; i < 101; i++ {
   363  			req := &apiservice.Service{
   364  				Namespace: utils.NewStringValue("Test"),
   365  				Name:      utils.NewStringValue("test"),
   366  			}
   367  			reqs = append(reqs, req)
   368  		}
   369  		if resp := discoverSuit.DiscoverServer().GetServiceOwner(discoverSuit.DefaultCtx, reqs); !respSuccess(resp) {
   370  			t.Logf("pass: %s", resp.GetInfo().GetValue())
   371  		} else {
   372  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   373  		}
   374  	})
   375  
   376  	t.Run("查询100个超长服务名的服务负责人,数据库不会报错", func(t *testing.T) {
   377  		reqs := make([]*apiservice.Service, 0, 100)
   378  		for i := 0; i < 100; i++ {
   379  			req := &apiservice.Service{
   380  				Namespace: utils.NewStringValue("Development"),
   381  				Name:      utils.NewStringValue(genSpecialStr(128)),
   382  			}
   383  			reqs = append(reqs, req)
   384  		}
   385  		if resp := discoverSuit.DiscoverServer().GetServiceOwner(discoverSuit.DefaultCtx, reqs); !respSuccess(resp) {
   386  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   387  		}
   388  		t.Log("pass")
   389  	})
   390  }
   391  
   392  // 测试获取服务函数
   393  func TestGetService(t *testing.T) {
   394  
   395  	discoverSuit := &DiscoverTestSuit{}
   396  	if err := discoverSuit.Initialize(); err != nil {
   397  		t.Fatal(err)
   398  	}
   399  	defer discoverSuit.Destroy()
   400  
   401  	t.Run("查询服务列表,可以正常返回", func(t *testing.T) {
   402  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{})
   403  		if !respSuccess(resp) {
   404  			t.Fatalf("error: %s", resp.Info.GetValue())
   405  		}
   406  	})
   407  	t.Run("查询服务列表,只有limit和offset,可以正常返回预计个数的服务", func(t *testing.T) {
   408  		total := 20
   409  		reqs := make([]*apiservice.Service, 0, total)
   410  		for i := 0; i < total; i++ {
   411  			serviceReq, _ := discoverSuit.createCommonService(t, i+10)
   412  			reqs = append(reqs, serviceReq)
   413  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   414  		}
   415  
   416  		// 创建完,直接查询
   417  		filters := map[string]string{"offset": "0", "limit": "100"}
   418  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   419  		if !respSuccess(resp) {
   420  			t.Fatalf("error: %s", resp.Info.GetValue())
   421  		}
   422  
   423  		if resp.GetSize().GetValue() >= uint32(total) && resp.GetSize().GetValue() <= 100 {
   424  			t.Logf("pass")
   425  		} else {
   426  			t.Fatalf("error: %d %d", resp.GetSize().GetValue(), total)
   427  		}
   428  	})
   429  
   430  	t.Run("查询服务列表,没有filter,只回复默认的service", func(t *testing.T) {
   431  		total := 10
   432  		for i := 0; i < total; i++ {
   433  			serviceReq, _ := discoverSuit.createCommonService(t, i+10)
   434  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   435  		}
   436  
   437  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{})
   438  		if !respSuccess(resp) {
   439  			t.Fatalf("error: %s", resp.Info.GetValue())
   440  		}
   441  		if resp.GetSize().GetValue() >= 10 {
   442  			t.Logf("pass")
   443  		} else {
   444  			t.Fatalf("error: %d", resp.GetSize().GetValue())
   445  		}
   446  	})
   447  	t.Run("查询服务列表,只能查询到源服务,无法查询到别名", func(t *testing.T) {
   448  		total := 10
   449  		for i := 0; i < total; i++ {
   450  			_, serviceResp := discoverSuit.createCommonService(t, i+102)
   451  			defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   452  			aliasResp := discoverSuit.createCommonAlias(serviceResp, "", defaultAliasNs, apiservice.AliasType_CL5SID)
   453  			defer discoverSuit.cleanServiceName(aliasResp.Alias.Alias.Value, serviceResp.Namespace.Value)
   454  		}
   455  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{"business": "business-102"})
   456  		if !respSuccess(resp) {
   457  			t.Fatalf("error: %s", resp.Info.GetValue())
   458  		}
   459  		if resp.GetSize().GetValue() != 1 {
   460  			t.Fatalf("error: %d", resp.GetSize().GetValue())
   461  		}
   462  	})
   463  }
   464  
   465  // 测试获取服务列表,参数校验
   466  func TestGetServices2(t *testing.T) {
   467  
   468  	discoverSuit := &DiscoverTestSuit{}
   469  	if err := discoverSuit.Initialize(); err != nil {
   470  		t.Fatal(err)
   471  	}
   472  	defer discoverSuit.Destroy()
   473  
   474  	t.Run("查询服务列表,limit有最大为100的限制", func(t *testing.T) {
   475  		total := 101
   476  		for i := 0; i < total; i++ {
   477  			serviceReq, _ := discoverSuit.createCommonService(t, i+10)
   478  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   479  		}
   480  
   481  		filters := map[string]string{"offset": "0", "limit": "600"}
   482  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   483  		if !respSuccess(resp) {
   484  			t.Fatalf("error: %s", resp.Info.GetValue())
   485  		}
   486  		if resp.GetSize().GetValue() == service.QueryMaxLimit {
   487  			t.Logf("pass")
   488  		} else {
   489  			t.Fatalf("error: %d", resp.GetSize().GetValue())
   490  		}
   491  	})
   492  	t.Run("查询服务列表,offset参数不为int,返回错误", func(t *testing.T) {
   493  		filters := map[string]string{"offset": "abc", "limit": "200"}
   494  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   495  		if !respSuccess(resp) {
   496  			t.Logf("pass: %s", resp.Info.GetValue())
   497  		} else {
   498  			t.Fatalf("error")
   499  		}
   500  	})
   501  	t.Run("查询服务列表,limit参数不为int,返回错误", func(t *testing.T) {
   502  		filters := map[string]string{"offset": "0", "limit": "ss"}
   503  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   504  		if !respSuccess(resp) {
   505  			t.Logf("pass: %s", resp.Info.GetValue())
   506  		} else {
   507  			t.Fatalf("error")
   508  		}
   509  	})
   510  	t.Run("查询服务列表,offset参数为负数,返回错误", func(t *testing.T) {
   511  		filters := map[string]string{"offset": "-100", "limit": "10"}
   512  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   513  		if !respSuccess(resp) {
   514  			t.Logf("pass: %s", resp.Info.GetValue())
   515  		} else {
   516  			t.Fatalf("error")
   517  		}
   518  	})
   519  	t.Run("查询服务列表,limit参数为负数,返回错误", func(t *testing.T) {
   520  		filters := map[string]string{"offset": "100", "limit": "-10"}
   521  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   522  		if !respSuccess(resp) {
   523  			t.Logf("pass: %s", resp.Info.GetValue())
   524  		} else {
   525  			t.Fatalf("error")
   526  		}
   527  	})
   528  	t.Run("查询服务列表,单独提供port参数,返回错误", func(t *testing.T) {
   529  		filters := map[string]string{"port": "100"}
   530  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   531  		if !respSuccess(resp) {
   532  			t.Logf("pass: %s", resp.Info.GetValue())
   533  		} else {
   534  			t.Fatalf("error")
   535  		}
   536  	})
   537  	t.Run("查询服务列表,port参数有误,返回错误", func(t *testing.T) {
   538  		filters := map[string]string{"port": "p100", "host": "127.0.0.1"}
   539  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   540  		if !respSuccess(resp) {
   541  			t.Logf("pass: %s", resp.Info.GetValue())
   542  		} else {
   543  			t.Fatalf("error")
   544  		}
   545  	})
   546  }
   547  
   548  // 有基础的过滤条件的查询服务列表
   549  func TestGetService3(t *testing.T) {
   550  
   551  	discoverSuit := &DiscoverTestSuit{}
   552  	if err := discoverSuit.Initialize(); err != nil {
   553  		t.Fatal(err)
   554  	}
   555  	defer discoverSuit.Destroy()
   556  
   557  	t.Run("根据服务名,可以正常过滤", func(t *testing.T) {
   558  		var reqs []*apiservice.Service
   559  		serviceReq, _ := discoverSuit.createCommonService(t, 100)
   560  		reqs = append(reqs, serviceReq)
   561  		defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   562  
   563  		namespaceReq, _ := discoverSuit.createCommonNamespace(t, 100)
   564  		defer discoverSuit.cleanNamespace(namespaceReq.GetName().GetValue())
   565  
   566  		serviceReq.Namespace = utils.NewStringValue(namespaceReq.GetName().GetValue())
   567  		if resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceReq}); !respSuccess(resp) {
   568  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   569  		}
   570  		reqs = append(reqs, serviceReq)
   571  		defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   572  
   573  		name := serviceReq.GetName().GetValue()
   574  		filters := map[string]string{"offset": "0", "limit": "10", "name": name}
   575  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   576  		if !respSuccess(resp) {
   577  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   578  		}
   579  
   580  		discoverSuit.CheckGetService(t, reqs, resp.GetServices())
   581  		t.Logf("pass")
   582  	})
   583  
   584  	t.Run("多重过滤条件,可以生效", func(t *testing.T) {
   585  		total := 10
   586  		var name, namespace string
   587  		for i := 0; i < total; i++ {
   588  			serviceReq, _ := discoverSuit.createCommonService(t, 100)
   589  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   590  			if i == 5 {
   591  				name = serviceReq.GetName().GetValue()
   592  				namespace = serviceReq.GetNamespace().GetValue()
   593  			}
   594  		}
   595  		filters := map[string]string{"offset": "0", "limit": "10", "name": name, "namespace": namespace}
   596  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   597  		if !respSuccess(resp) {
   598  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   599  		}
   600  		if len(resp.Services) != 1 {
   601  			t.Fatalf("error: %d", len(resp.Services))
   602  		}
   603  	})
   604  
   605  	t.Run("businessr过滤条件会生效", func(t *testing.T) {
   606  		total := 60
   607  		for i := 0; i < total; i++ {
   608  			serviceReq, _ := discoverSuit.createCommonService(t, i+10)
   609  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   610  		}
   611  
   612  		filters := map[string]string{"offset": "0", "limit": "100", "business": "business-60"}
   613  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   614  		if !respSuccess(resp) {
   615  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   616  		}
   617  		if len(resp.Services) != 1 {
   618  			b, _ := json.Marshal(resp.Services)
   619  			t.Logf("[error] services : %s", string(b))
   620  			t.Fatalf("error: %d", len(resp.Services))
   621  		}
   622  	})
   623  }
   624  
   625  // 异常场景
   626  func TestGetServices4(t *testing.T) {
   627  
   628  	discoverSuit := &DiscoverTestSuit{}
   629  	if err := discoverSuit.Initialize(); err != nil {
   630  		t.Fatal(err)
   631  	}
   632  	defer discoverSuit.Destroy()
   633  
   634  	t.Run("查询服务列表,新建一批服务,删除部分,再查询,可以过滤掉删除的", func(t *testing.T) {
   635  		total := 50
   636  		for i := 0; i < total; i++ {
   637  			serviceReq, serviceResp := discoverSuit.createCommonService(t, i+5)
   638  			defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue())
   639  			if i%2 == 0 {
   640  				discoverSuit.removeCommonServices(t, []*apiservice.Service{serviceResp})
   641  			}
   642  		}
   643  
   644  		query := map[string]string{
   645  			"offset": "0",
   646  			"limit":  "100",
   647  			"name":   "test-service-*",
   648  		}
   649  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, query)
   650  		if !respSuccess(resp) {
   651  			t.Fatalf("error: %s", resp.Info.GetValue())
   652  		}
   653  		if resp.GetSize().GetValue() == uint32(total/2) {
   654  			t.Logf("pass")
   655  		} else {
   656  			t.Fatalf("error: %d", resp.GetSize().GetValue())
   657  		}
   658  	})
   659  	// 新建几个服务,不同metadata
   660  	t.Run("根据metadata可以过滤services", func(t *testing.T) {
   661  		service1 := genMainService(1)
   662  		service1.Metadata = map[string]string{
   663  			"key1": "value1",
   664  			"key2": "value2",
   665  			"key3": "value3",
   666  		}
   667  		service2 := genMainService(2)
   668  		service2.Metadata = map[string]string{
   669  			"key2": "value2",
   670  			"key3": "value3",
   671  		}
   672  		service3 := genMainService(3)
   673  		service3.Metadata = map[string]string{"key3": "value3"}
   674  		if resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service1, service2, service3}); !respSuccess(resp) {
   675  			t.Fatalf("error: %+v", resp)
   676  		}
   677  		defer discoverSuit.cleanServiceName(service1.GetName().GetValue(), service1.GetNamespace().GetValue())
   678  		defer discoverSuit.cleanServiceName(service2.GetName().GetValue(), service2.GetNamespace().GetValue())
   679  		defer discoverSuit.cleanServiceName(service3.GetName().GetValue(), service3.GetNamespace().GetValue())
   680  
   681  		resps := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{"keys": "key3", "values": "value3"})
   682  		if len(resps.GetServices()) != 3 && resps.GetAmount().GetValue() != 3 {
   683  			t.Fatalf("error: %d", len(resps.GetServices()))
   684  		}
   685  		resps = discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{"keys": "key2", "values": "value2"})
   686  		if len(resps.GetServices()) != 2 && resps.GetAmount().GetValue() != 2 {
   687  			t.Fatalf("error: %d", len(resps.GetServices()))
   688  		}
   689  		resps = discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{"keys": "key1", "values": "value1"})
   690  		if len(resps.GetServices()) != 1 && resps.GetAmount().GetValue() != 1 {
   691  			t.Fatalf("error: %d", len(resps.GetServices()))
   692  		}
   693  		resps = discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{"keys": "key1", "values": "value2"})
   694  		if len(resps.GetServices()) != 0 && resps.GetAmount().GetValue() != 0 {
   695  			t.Fatalf("error: %d", len(resps.GetServices()))
   696  		}
   697  	})
   698  }
   699  
   700  // 联合查询场景
   701  func TestGetServices5(t *testing.T) {
   702  	t.SkipNow()
   703  	discoverSuit := &DiscoverTestSuit{}
   704  	if err := discoverSuit.Initialize(); err != nil {
   705  		t.Fatal(err)
   706  	}
   707  	defer discoverSuit.Destroy()
   708  
   709  	getServiceCheck := func(resp *apiservice.BatchQueryResponse, amount, size uint32) {
   710  		t.Logf("gocheck resp: %v", resp)
   711  		convey.So(respSuccess(resp), convey.ShouldEqual, true)
   712  		convey.So(resp.GetAmount().GetValue(), convey.ShouldEqual, amount)
   713  		convey.So(resp.GetSize().GetValue(), convey.ShouldEqual, size)
   714  	}
   715  	convey.Convey("支持host查询到服务", t, func() {
   716  		_, serviceResp := discoverSuit.createCommonService(t, 200)
   717  		defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   718  		instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 100)
   719  		defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue())
   720  		instanceReq, instanceResp = discoverSuit.createCommonInstance(t, serviceResp, 101)
   721  		defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue())
   722  		query := map[string]string{
   723  			"owner": "service-owner-200",
   724  			"host":  instanceReq.GetHost().GetValue(),
   725  		}
   726  		convey.Convey("check-1", func() { getServiceCheck(discoverSuit.DiscoverServer().GetServices(context.Background(), query), 1, 1) })
   727  
   728  		// 同host的实例,对应一个服务,那么返回值也是一个
   729  		instanceReq.Port.Value = 999
   730  		resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq})
   731  		convey.So(respSuccess(resp), convey.ShouldEqual, true)
   732  		defer discoverSuit.cleanInstance(resp.Responses[0].Instance.GetId().GetValue())
   733  		convey.Convey("check-2", func() { getServiceCheck(discoverSuit.DiscoverServer().GetServices(context.Background(), query), 1, 1) })
   734  	})
   735  	convey.Convey("支持host和port配合查询服务", t, func() {
   736  		host1 := "127.0.0.1"
   737  		port1 := uint32(8081)
   738  		host2 := "127.0.0.2"
   739  		port2 := uint32(8082)
   740  		_, serviceResp1 := discoverSuit.createCommonService(t, 200)
   741  		defer discoverSuit.cleanServiceName(serviceResp1.GetName().GetValue(), serviceResp1.GetNamespace().GetValue())
   742  		_, instanceResp1 := discoverSuit.addHostPortInstance(t, serviceResp1, host1, port1)
   743  		defer discoverSuit.cleanInstance(instanceResp1.GetId().GetValue())
   744  		_, serviceResp2 := discoverSuit.createCommonService(t, 300)
   745  		defer discoverSuit.cleanServiceName(serviceResp2.GetName().GetValue(), serviceResp2.GetNamespace().GetValue())
   746  		_, instanceResp2 := discoverSuit.addHostPortInstance(t, serviceResp2, host1, port2)
   747  		defer discoverSuit.cleanInstance(instanceResp2.GetId().GetValue())
   748  		_, serviceResp3 := discoverSuit.createCommonService(t, 400)
   749  		defer discoverSuit.cleanServiceName(serviceResp3.GetName().GetValue(), serviceResp3.GetNamespace().GetValue())
   750  		_, instanceResp3 := discoverSuit.addHostPortInstance(t, serviceResp3, host2, port1)
   751  		defer discoverSuit.cleanInstance(instanceResp3.GetId().GetValue())
   752  		_, serviceResp4 := discoverSuit.createCommonService(t, 500)
   753  		defer discoverSuit.cleanServiceName(serviceResp4.GetName().GetValue(), serviceResp4.GetNamespace().GetValue())
   754  		_, instanceResp4 := discoverSuit.addHostPortInstance(t, serviceResp4, host2, port2)
   755  		defer discoverSuit.cleanInstance(instanceResp4.GetId().GetValue())
   756  
   757  		query := map[string]string{
   758  			"host": host1,
   759  			"port": strconv.Itoa(int(port1)),
   760  		}
   761  		convey.Convey("check-1-1", func() {
   762  			getServiceCheck(
   763  				discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, query), 1, 1)
   764  		})
   765  		query["host"] = host1 + "," + host2
   766  		convey.Convey("check-2-1", func() {
   767  			getServiceCheck(
   768  				discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, query), 2, 2)
   769  		})
   770  		query["port"] = fmt.Sprintf("%d,%d", port1, port2)
   771  		convey.Convey("check-2-2", func() {
   772  			getServiceCheck(
   773  				discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, query), 4, 4)
   774  		})
   775  	})
   776  	convey.Convey("多个服务,对应同个host,返回多个服务", t, func() {
   777  		count := 10
   778  		var instance *apiservice.Instance
   779  		for i := 0; i < count; i++ {
   780  			_, serviceResp := discoverSuit.createCommonService(t, i)
   781  			defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   782  			_, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 100)
   783  			defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue())
   784  			instance = instanceResp
   785  			_, instanceResp = discoverSuit.createCommonInstance(t, serviceResp, 202)
   786  			defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue())
   787  		}
   788  		query := map[string]string{
   789  			"host":  instance.GetHost().GetValue(),
   790  			"limit": "5",
   791  		}
   792  		convey.Convey("check-1", func() {
   793  			getServiceCheck(
   794  				discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, query), uint32(count), 5)
   795  		})
   796  	})
   797  }
   798  
   799  // 模糊匹配测试
   800  func TestGetService6(t *testing.T) {
   801  	discoverSuit := &DiscoverTestSuit{}
   802  	if err := discoverSuit.Initialize(); err != nil {
   803  		t.Fatal(err)
   804  	}
   805  	defer discoverSuit.Destroy()
   806  	t.Run("namespace模糊匹配过滤条件会生效", func(t *testing.T) {
   807  		total := 60
   808  		for i := 0; i < total; i++ {
   809  			_, serviceResp := discoverSuit.createCommonService(t, i+100)
   810  			defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   811  		}
   812  
   813  		filters := map[string]string{"offset": "0",
   814  			"limit":     "100",
   815  			"namespace": "*ef*"}
   816  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   817  		if !respSuccess(resp) {
   818  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   819  		}
   820  		if len(resp.Services) != total {
   821  			t.Fatalf("error: %d", len(resp.Services))
   822  		}
   823  
   824  		filters = map[string]string{"offset": "0",
   825  			"limit":     "100",
   826  			"namespace": "def*"}
   827  		resp = discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   828  		if !respSuccess(resp) {
   829  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   830  		}
   831  		if len(resp.Services) != total {
   832  			t.Fatalf("error: %d", len(resp.Services))
   833  		}
   834  	})
   835  
   836  	t.Run("service模糊匹配过滤条件会生效", func(t *testing.T) {
   837  		total := 60
   838  		for i := 0; i < total; i++ {
   839  			_, serviceResp := discoverSuit.createCommonService(t, i+200)
   840  			defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   841  		}
   842  
   843  		filters := map[string]string{"offset": "0",
   844  			"limit": "100",
   845  			"name":  "*est-service-21*"}
   846  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   847  		if !respSuccess(resp) {
   848  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   849  		}
   850  		if len(resp.Services) != 10 {
   851  			t.Fatalf("error: %d", len(resp.Services))
   852  		}
   853  	})
   854  
   855  	t.Run("instance_keys和instance_values模糊匹配过滤条件会生效", func(t *testing.T) {
   856  		_, serviceResp := discoverSuit.createCommonService(t, 999)
   857  		defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   858  		total := 10
   859  		for i := 0; i < total; i++ {
   860  			_, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i+100)
   861  			defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue())
   862  		}
   863  
   864  		filters := map[string]string{
   865  			"offset":          "0",
   866  			"limit":           "100",
   867  			"instance_keys":   "2my-meta,my-meta-a1",
   868  			"instance_values": "my-meta-100,111*",
   869  		}
   870  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   871  		if !respSuccess(resp) {
   872  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   873  		}
   874  		if len(resp.Services) != 1 {
   875  			t.Fatalf("error: %d", len(resp.Services))
   876  		}
   877  		if resp.Services[0].TotalInstanceCount.Value != uint32(total) {
   878  			t.Fatalf("error: %d", resp.Services[0].TotalInstanceCount.Value)
   879  		}
   880  
   881  		filters = map[string]string{"offset": "0",
   882  			"limit":           "100",
   883  			"instance_keys":   "2my-meta,my-meta-a1,my-1meta-o3",
   884  			"instance_values": "my-meta-100,1111,not-exists",
   885  		}
   886  		resp = discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   887  		if !respSuccess(resp) {
   888  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   889  		}
   890  		if len(resp.Services) != 0 {
   891  			t.Fatalf("error: %d", len(resp.Services))
   892  		}
   893  	})
   894  
   895  	t.Run("instance_keys和instance_values长度不相等会报错", func(t *testing.T) {
   896  		filters := map[string]string{"offset": "0",
   897  			"limit":           "100",
   898  			"instance_keys":   "2my-meta,my-meta-a1",
   899  			"instance_values": "my-meta-100,1111,oneMore",
   900  		}
   901  		resp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, filters)
   902  		if resp.Code.Value != api.InvalidParameter {
   903  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   904  		}
   905  	})
   906  }
   907  
   908  // 测试更新服务
   909  func TestUpdateService(t *testing.T) {
   910  
   911  	discoverSuit := &DiscoverTestSuit{}
   912  	if err := discoverSuit.Initialize(); err != nil {
   913  		t.Fatal(err)
   914  	}
   915  	defer discoverSuit.Destroy()
   916  
   917  	_, serviceResp := discoverSuit.createCommonService(t, 200)
   918  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
   919  	t.Run("正常更新服务,所有属性都生效", func(t *testing.T) {
   920  		updateReq := &apiservice.Service{
   921  			Name:      serviceResp.Name,
   922  			Namespace: serviceResp.Namespace,
   923  			Metadata: map[string]string{
   924  				"new-key":   "1",
   925  				"new-key-2": "2",
   926  				"new-key-3": "3",
   927  			},
   928  			Ports:      utils.NewStringValue("new-ports"),
   929  			Business:   utils.NewStringValue("new-business"),
   930  			Department: utils.NewStringValue("new-business"),
   931  			CmdbMod1:   utils.NewStringValue("new-cmdb-mod1"),
   932  			CmdbMod2:   utils.NewStringValue("new-cmdb-mo2"),
   933  			CmdbMod3:   utils.NewStringValue("new-cmdb-mod3"),
   934  			Comment:    utils.NewStringValue("new-comment"),
   935  			Owners:     utils.NewStringValue("new-owner"),
   936  			Token:      serviceResp.Token,
   937  		}
   938  		resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{updateReq})
   939  		if !respSuccess(resp) {
   940  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   941  		}
   942  
   943  		// get service
   944  		query := map[string]string{
   945  			"name":      updateReq.GetName().GetValue(),
   946  			"namespace": updateReq.GetNamespace().GetValue(),
   947  		}
   948  		services := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, query)
   949  		if !respSuccess(services) {
   950  			t.Fatalf("error: %s", services.GetInfo().GetValue())
   951  		}
   952  		if services.GetSize().GetValue() != 1 {
   953  			t.Fatalf("error: %d", services.GetSize().GetValue())
   954  		}
   955  
   956  		serviceCheck(t, updateReq, services.GetServices()[0])
   957  	})
   958  	t.Run("更新服务,metadata数据个数太多,报错", func(t *testing.T) {
   959  		serviceResp.Metadata = make(map[string]string)
   960  		for i := 0; i < service.MaxMetadataLength+1; i++ {
   961  			serviceResp.Metadata[fmt.Sprintf("update-%d", i)] = "abc"
   962  		}
   963  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceResp}); !respSuccess(resp) {
   964  			t.Logf("pass: %s", resp.GetInfo().GetValue())
   965  		} else {
   966  			t.Fatalf("error")
   967  		}
   968  	})
   969  	t.Run("更新服务,metadata为空,长度为0,则删除所有metadata", func(t *testing.T) {
   970  		serviceResp.Metadata = make(map[string]string)
   971  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceResp}); !respSuccess(resp) {
   972  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
   973  		}
   974  		getResp := discoverSuit.DiscoverServer().GetServices(discoverSuit.DefaultCtx, map[string]string{"name": serviceResp.Name.Value})
   975  		if !respSuccess(getResp) {
   976  			t.Fatalf("error: %s", getResp.GetInfo().GetValue())
   977  		}
   978  		if len(getResp.Services[0].Metadata) != 0 {
   979  			t.Fatalf("error: %d", len(getResp.Services[0].Metadata))
   980  		}
   981  	})
   982  	t.Run("更新服务,不允许更新别名", func(t *testing.T) {
   983  		aliasResp := discoverSuit.createCommonAlias(serviceResp, "update.service.alias.xxx", defaultAliasNs, apiservice.AliasType_DEFAULT)
   984  		defer discoverSuit.cleanServiceName(aliasResp.Alias.Alias.Value, serviceResp.Namespace.Value)
   985  
   986  		aliasService := &apiservice.Service{
   987  			Name:       aliasResp.Alias.Alias,
   988  			Namespace:  serviceResp.Namespace,
   989  			Department: utils.NewStringValue("123"),
   990  			Token:      serviceResp.Token,
   991  		}
   992  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{aliasService}); respSuccess(resp) {
   993  			t.Fatalf("error: update alias success")
   994  		} else {
   995  			t.Logf("update alias return: %s", resp.GetInfo().GetValue())
   996  		}
   997  	})
   998  }
   999  
  1000  // 服务更新,noChange测试
  1001  func TestNoNeedUpdateService(t *testing.T) {
  1002  
  1003  	discoverSuit := &DiscoverTestSuit{}
  1004  	if err := discoverSuit.Initialize(); err != nil {
  1005  		t.Fatal(err)
  1006  	}
  1007  	defer discoverSuit.Destroy()
  1008  
  1009  	_, serviceResp := discoverSuit.createCommonService(t, 500)
  1010  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
  1011  	t.Run("数据没有任意变更,返回不需要变更", func(t *testing.T) {
  1012  		resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceResp})
  1013  		if resp.GetCode().GetValue() != api.NoNeedUpdate {
  1014  			t.Fatalf("error: %+v", resp)
  1015  		}
  1016  	})
  1017  	req := &apiservice.Service{
  1018  		Name:      serviceResp.Name,
  1019  		Namespace: serviceResp.Namespace,
  1020  		Token:     serviceResp.Token,
  1021  	}
  1022  	t.Run("metadata为空,不需要变更", func(t *testing.T) {
  1023  		req.Metadata = nil
  1024  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{req}); resp.GetCode().GetValue() != api.NoNeedUpdate {
  1025  			t.Fatalf("error: %+v", resp)
  1026  		}
  1027  		req.Comment = serviceResp.Comment
  1028  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{req}); resp.GetCode().GetValue() != api.NoNeedUpdate {
  1029  			t.Fatalf("error: %+v", resp)
  1030  		}
  1031  	})
  1032  	t.Run("metadata不为空,但是没变更,也不需要更新", func(t *testing.T) {
  1033  		req.Metadata = serviceResp.Metadata
  1034  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{req}); resp.GetCode().GetValue() != api.NoNeedUpdate {
  1035  			t.Fatalf("error: %+v", resp)
  1036  		}
  1037  	})
  1038  	t.Run("其他字段更新,metadata没有更新,不需要更新metadata", func(t *testing.T) {
  1039  		req.Metadata = serviceResp.Metadata
  1040  		req.Comment = utils.NewStringValue("1357986420")
  1041  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{req}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1042  			t.Fatalf("error: %+v", resp)
  1043  		}
  1044  	})
  1045  	t.Run("只有一个字段变更,service就执行变更操作", func(t *testing.T) {
  1046  		baseReq := apiservice.Service{
  1047  			Name:      serviceResp.Name,
  1048  			Namespace: serviceResp.Namespace,
  1049  			Token:     serviceResp.Token,
  1050  		}
  1051  
  1052  		r := baseReq
  1053  		r.Ports = utils.NewStringValue("90909090")
  1054  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1055  			t.Fatalf("error: %+v", resp)
  1056  		}
  1057  
  1058  		r = baseReq
  1059  		r.Business = utils.NewStringValue("new-business")
  1060  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1061  			t.Fatalf("error: %+v", resp)
  1062  		}
  1063  
  1064  		r = baseReq
  1065  		r.Department = utils.NewStringValue("new-department-1")
  1066  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1067  			t.Fatalf("error: %+v", resp)
  1068  		}
  1069  
  1070  		r = baseReq
  1071  		r.CmdbMod1 = utils.NewStringValue("new-CmdbMod1-1")
  1072  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1073  			t.Fatalf("error: %+v", resp)
  1074  		}
  1075  
  1076  		r = baseReq
  1077  		r.CmdbMod2 = utils.NewStringValue("new-CmdbMod2-1")
  1078  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1079  			t.Fatalf("error: %+v", resp)
  1080  		}
  1081  
  1082  		r = baseReq
  1083  		r.CmdbMod3 = utils.NewStringValue("new-CmdbMod3-1")
  1084  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1085  			t.Fatalf("error: %+v", resp)
  1086  		}
  1087  
  1088  		r = baseReq
  1089  		r.Comment = utils.NewStringValue("new-Comment-1")
  1090  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1091  			t.Fatalf("error: %+v", resp)
  1092  		}
  1093  
  1094  		r = baseReq
  1095  		r.Owners = utils.NewStringValue("new-Owners-1")
  1096  		if resp := discoverSuit.DiscoverServer().UpdateServices(discoverSuit.DefaultCtx, []*apiservice.Service{&r}); resp.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1097  			t.Fatalf("error: %+v", resp)
  1098  		}
  1099  	})
  1100  }
  1101  
  1102  // 测试serviceToken相关的操作
  1103  func TestServiceToken(t *testing.T) {
  1104  
  1105  	discoverSuit := &DiscoverTestSuit{}
  1106  	if err := discoverSuit.Initialize(); err != nil {
  1107  		t.Fatal(err)
  1108  	}
  1109  	defer discoverSuit.Destroy()
  1110  
  1111  	_, serviceResp := discoverSuit.createCommonService(t, 200)
  1112  	defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue())
  1113  	t.Run("可以正常获取serviceToken", func(t *testing.T) {
  1114  		req := &apiservice.Service{
  1115  			Name:      serviceResp.GetName(),
  1116  			Namespace: serviceResp.GetNamespace(),
  1117  			Token:     serviceResp.GetToken(),
  1118  		}
  1119  
  1120  		resp := discoverSuit.DiscoverServer().GetServiceToken(discoverSuit.DefaultCtx, req)
  1121  		if !respSuccess(resp) {
  1122  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
  1123  		}
  1124  		if resp.GetService().GetToken().GetValue() != serviceResp.GetToken().GetValue() {
  1125  			t.Fatalf("error")
  1126  		}
  1127  	})
  1128  
  1129  	t.Run("获取别名的token,返回源服务的token", func(t *testing.T) {
  1130  		aliasResp := discoverSuit.createCommonAlias(serviceResp, fmt.Sprintf("get.token.xxx-%s", utils.NewUUID()[:8]), defaultAliasNs, apiservice.AliasType_DEFAULT)
  1131  		defer discoverSuit.cleanServiceName(aliasResp.Alias.Alias.Value, serviceResp.Namespace.Value)
  1132  		t.Logf("%+v", aliasResp)
  1133  
  1134  		req := &apiservice.Service{
  1135  			Name:      aliasResp.Alias.Alias,
  1136  			Namespace: aliasResp.Alias.AliasNamespace,
  1137  			Token:     serviceResp.GetToken(),
  1138  		}
  1139  		t.Logf("%+v", req)
  1140  		if resp := discoverSuit.DiscoverServer().GetServiceToken(discoverSuit.DefaultCtx, req); !respSuccess(resp) {
  1141  			t.Fatalf("error: %s", resp.GetInfo().GetValue())
  1142  		} else if resp.GetService().GetToken().GetValue() != serviceResp.GetToken().GetValue() {
  1143  			t.Fatalf("error")
  1144  		}
  1145  	})
  1146  
  1147  	t.Run("可以正常更新serviceToken", func(t *testing.T) {
  1148  		resp := discoverSuit.DiscoverServer().UpdateServiceToken(discoverSuit.DefaultCtx, serviceResp)
  1149  		if !respSuccess(resp) {
  1150  			t.Fatalf("error :%s", resp.GetInfo().GetValue())
  1151  		}
  1152  		if resp.GetService().GetToken().GetValue() == serviceResp.GetToken().GetValue() {
  1153  			t.Fatalf("error: %s %s", resp.GetService().GetToken().GetValue(),
  1154  				serviceResp.GetToken().GetValue())
  1155  		}
  1156  		serviceResp.Token.Value = resp.Service.Token.Value // set token
  1157  	})
  1158  
  1159  	t.Run("alias不允许更新token", func(t *testing.T) {
  1160  		aliasResp := discoverSuit.createCommonAlias(serviceResp, "update.token.xxx", defaultAliasNs, apiservice.AliasType_DEFAULT)
  1161  		defer discoverSuit.cleanServiceName(aliasResp.Alias.Alias.Value, serviceResp.Namespace.Value)
  1162  
  1163  		req := &apiservice.Service{
  1164  			Name:      aliasResp.Alias.Alias,
  1165  			Namespace: serviceResp.Namespace,
  1166  			Token:     serviceResp.Token,
  1167  		}
  1168  		if resp := discoverSuit.DiscoverServer().UpdateServiceToken(discoverSuit.DefaultCtx, req); respSuccess(resp) {
  1169  			t.Fatalf("error")
  1170  		}
  1171  	})
  1172  }
  1173  
  1174  // 测试response格式化
  1175  func TestFormatBatchWriteResponse(t *testing.T) {
  1176  	t.Run("同样的错误码,返回一个错误码4XX", func(t *testing.T) {
  1177  		responses := api.NewBatchWriteResponse(apimodel.Code_ExecuteSuccess)
  1178  		for i := 0; i < 10; i++ {
  1179  			api.Collect(responses, api.NewResponse(apimodel.Code_NotFoundService))
  1180  		}
  1181  
  1182  		responses = api.FormatBatchWriteResponse(responses)
  1183  		if responses.GetCode().GetValue() != uint32(apimodel.Code_NotFoundService) {
  1184  			t.Fatalf("%+v", responses)
  1185  		}
  1186  	})
  1187  	t.Run("同样的错误码,返回一个错误码5XX", func(t *testing.T) {
  1188  		responses := api.NewBatchWriteResponse(apimodel.Code_ExecuteSuccess)
  1189  		for i := 0; i < 10; i++ {
  1190  			api.Collect(responses, api.NewResponse(apimodel.Code_StoreLayerException))
  1191  		}
  1192  
  1193  		responses = api.FormatBatchWriteResponse(responses)
  1194  		if responses.GetCode().GetValue() != uint32(apimodel.Code_StoreLayerException) {
  1195  			t.Fatalf("%+v", responses)
  1196  		}
  1197  	})
  1198  	t.Run("有5XX和2XX,返回5XX", func(t *testing.T) {
  1199  		responses := api.NewBatchWriteResponse(apimodel.Code_ExecuteSuccess)
  1200  		api.Collect(responses, api.NewResponse(apimodel.Code_ExecuteSuccess))
  1201  		api.Collect(responses, api.NewResponse(apimodel.Code_NotFoundNamespace))
  1202  		api.Collect(responses, api.NewResponse(apimodel.Code_ParseRateLimitException))
  1203  		api.Collect(responses, api.NewResponse(apimodel.Code_ParseException))
  1204  		responses = api.FormatBatchWriteResponse(responses)
  1205  		if responses.GetCode().GetValue() != api.ExecuteException {
  1206  			t.Fatalf("%+v", responses)
  1207  		}
  1208  	})
  1209  	t.Run("没有5XX,有4XX,返回4XX", func(t *testing.T) {
  1210  		responses := api.NewBatchWriteResponse(apimodel.Code_ExecuteSuccess)
  1211  		api.Collect(responses, api.NewResponse(apimodel.Code_ExecuteSuccess))
  1212  		api.Collect(responses, api.NewResponse(apimodel.Code_NotFoundNamespace))
  1213  		api.Collect(responses, api.NewResponse(apimodel.Code_NoNeedUpdate))
  1214  		api.Collect(responses, api.NewResponse(apimodel.Code_InvalidInstanceID))
  1215  		api.Collect(responses, api.NewResponse(apimodel.Code_ExecuteSuccess))
  1216  		responses = api.FormatBatchWriteResponse(responses)
  1217  		if responses.GetCode().GetValue() != api.BadRequest {
  1218  			t.Fatalf("%+v", responses)
  1219  		}
  1220  	})
  1221  	t.Run("全是2XX", func(t *testing.T) {
  1222  		responses := api.NewBatchWriteResponse(apimodel.Code_ExecuteSuccess)
  1223  		api.Collect(responses, api.NewResponse(apimodel.Code_ExecuteSuccess))
  1224  		api.Collect(responses, api.NewResponse(apimodel.Code_NoNeedUpdate))
  1225  		api.Collect(responses, api.NewResponse(apimodel.Code_DataNoChange))
  1226  		api.Collect(responses, api.NewResponse(apimodel.Code_NoNeedUpdate))
  1227  		api.Collect(responses, api.NewResponse(apimodel.Code_ExecuteSuccess))
  1228  		responses = api.FormatBatchWriteResponse(responses)
  1229  		if responses.GetCode().GetValue() != uint32(apimodel.Code_ExecuteSuccess) {
  1230  			t.Fatalf("%+v", responses)
  1231  		}
  1232  	})
  1233  }
  1234  
  1235  // test对service字段进行校验
  1236  func TestCheckServiceFieldLen(t *testing.T) {
  1237  
  1238  	discoverSuit := &DiscoverTestSuit{}
  1239  	if err := discoverSuit.Initialize(); err != nil {
  1240  		t.Fatal(err)
  1241  	}
  1242  	defer discoverSuit.Destroy()
  1243  
  1244  	service := genMainService(400)
  1245  	t.Run("服务名超长", func(t *testing.T) {
  1246  		str := genSpecialStr(129)
  1247  		oldName := service.Name
  1248  		service.Name = utils.NewStringValue(str)
  1249  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1250  		service.Name = oldName
  1251  		if resp.Code.Value != api.InvalidServiceName {
  1252  			t.Fatalf("%+v", resp)
  1253  		}
  1254  	})
  1255  	t.Run("命名空间超长", func(t *testing.T) {
  1256  		str := genSpecialStr(129)
  1257  		oldNameSpace := service.Namespace
  1258  		service.Namespace = utils.NewStringValue(str)
  1259  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1260  		service.Namespace = oldNameSpace
  1261  		if resp.Code.Value != api.InvalidNamespaceName {
  1262  			t.Fatalf("%+v", resp)
  1263  		}
  1264  	})
  1265  	t.Run("Metadata超长", func(t *testing.T) {
  1266  		str := genSpecialStr(129)
  1267  		oldMetadata := service.Metadata
  1268  		oldMetadata[str] = str
  1269  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1270  		service.Metadata = make(map[string]string)
  1271  		if resp.Code.Value != api.InvalidMetadata {
  1272  			t.Fatalf("%+v", resp)
  1273  		}
  1274  	})
  1275  	t.Run("服务ports超长", func(t *testing.T) {
  1276  		str := genSpecialStr(8193)
  1277  		oldPort := service.Ports
  1278  		service.Ports = utils.NewStringValue(str)
  1279  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1280  		service.Ports = oldPort
  1281  		if resp.Code.Value != api.InvalidServicePorts {
  1282  			t.Fatalf("%+v", resp)
  1283  		}
  1284  	})
  1285  	t.Run("服务Business超长", func(t *testing.T) {
  1286  		str := genSpecialStr(129)
  1287  		oldBusiness := service.Business
  1288  		service.Business = utils.NewStringValue(str)
  1289  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1290  		service.Business = oldBusiness
  1291  		if resp.Code.Value != api.InvalidServiceBusiness {
  1292  			t.Fatalf("%+v", resp)
  1293  		}
  1294  	})
  1295  	t.Run("服务-部门超长", func(t *testing.T) {
  1296  		str := genSpecialStr(1025)
  1297  		oldDepartment := service.Department
  1298  		service.Department = utils.NewStringValue(str)
  1299  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1300  		service.Department = oldDepartment
  1301  		if resp.Code.Value != api.InvalidServiceDepartment {
  1302  			t.Fatalf("%+v", resp)
  1303  		}
  1304  	})
  1305  	t.Run("服务cmdb超长", func(t *testing.T) {
  1306  		str := genSpecialStr(1025)
  1307  		oldCMDB := service.CmdbMod1
  1308  		service.CmdbMod1 = utils.NewStringValue(str)
  1309  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1310  		service.CmdbMod1 = oldCMDB
  1311  		if resp.Code.Value != api.InvalidServiceCMDB {
  1312  			t.Fatalf("%+v", resp)
  1313  		}
  1314  	})
  1315  	t.Run("服务comment超长", func(t *testing.T) {
  1316  		str := genSpecialStr(1025)
  1317  		oldComment := service.Comment
  1318  		service.Comment = utils.NewStringValue(str)
  1319  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1320  		service.Comment = oldComment
  1321  		if resp.Code.Value != api.InvalidServiceComment {
  1322  			t.Fatalf("%+v", resp)
  1323  		}
  1324  	})
  1325  	t.Run("服务token超长", func(t *testing.T) {
  1326  		str := genSpecialStr(2049)
  1327  		oldToken := service.Token
  1328  		service.Token = utils.NewStringValue(str)
  1329  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1330  		service.Token = oldToken
  1331  		if resp.Code.Value != api.InvalidServiceToken {
  1332  			t.Fatalf("%+v", resp)
  1333  		}
  1334  	})
  1335  	t.Run("检测字段为空指针", func(t *testing.T) {
  1336  		oldName := service.Name
  1337  		service.Name = nil
  1338  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1339  		service.Name = oldName
  1340  		if resp.Code.Value != api.InvalidServiceName {
  1341  			t.Fatalf("%+v", resp)
  1342  		}
  1343  	})
  1344  	t.Run("检测字段为空", func(t *testing.T) {
  1345  		oldName := service.Name
  1346  		service.Name = utils.NewStringValue("")
  1347  		resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{service})
  1348  		service.Name = oldName
  1349  		if resp.Code.Value != api.InvalidServiceName {
  1350  			t.Fatalf("%+v", resp)
  1351  		}
  1352  	})
  1353  }
  1354  
  1355  func TestConcurrencyCreateSameService(t *testing.T) {
  1356  	ctrl := gomock.NewController(t)
  1357  	ctx, cancel := context.WithCancel(context.Background())
  1358  
  1359  	t.Cleanup(func() {
  1360  		cancel()
  1361  		ctrl.Finish()
  1362  	})
  1363  
  1364  	createMockResource := func() (*service.Server, *mock.MockStore) {
  1365  		var (
  1366  			err      error
  1367  			cacheMgr *cache.CacheManager
  1368  			nsSvr    namespace.NamespaceOperateServer
  1369  		)
  1370  
  1371  		mockStore := mock.NewMockStore(ctrl)
  1372  		mockStore.EXPECT().GetMoreNamespaces(gomock.Any()).Return([]*model.Namespace{
  1373  			&model.Namespace{
  1374  				Name: "mock_ns",
  1375  			},
  1376  		}, nil)
  1377  		mockStore.EXPECT().GetUnixSecond(gomock.Any()).Return(time.Now().Unix(), nil).AnyTimes()
  1378  		cacheMgr, err = cache.TestCacheInitialize(ctx, &cache.Config{
  1379  			Open: true,
  1380  			Resources: []cache.ConfigEntry{
  1381  				{
  1382  					Name: "namespace",
  1383  				},
  1384  			},
  1385  		}, mockStore)
  1386  		assert.NoError(t, err)
  1387  
  1388  		userMgn, strategyMgn, err := auth.TestInitialize(ctx, &auth.Config{}, mockStore, cacheMgr)
  1389  		assert.NoError(t, err)
  1390  
  1391  		nsSvr, err = namespace.TestInitialize(ctx, &namespace.Config{
  1392  			AutoCreate: true,
  1393  		}, mockStore, cacheMgr, userMgn, strategyMgn)
  1394  		assert.NoError(t, err)
  1395  
  1396  		svr := service.TestNewServer(mockStore, nsSvr, cacheMgr)
  1397  		return svr, mockStore
  1398  	}
  1399  
  1400  	var (
  1401  		req = &apiservice.Service{
  1402  			Namespace: &wrapperspb.StringValue{
  1403  				Value: "test_ns",
  1404  			},
  1405  			Name: &wrapperspb.StringValue{
  1406  				Value: "test_svc",
  1407  			},
  1408  		}
  1409  	)
  1410  
  1411  	t.Run("正常创建服务", func(t *testing.T) {
  1412  		svr, mockStore := createMockResource()
  1413  
  1414  		mockStore.EXPECT().GetNamespace(gomock.Any()).Return(&model.Namespace{
  1415  			Name: "mock_ns",
  1416  		}, nil).AnyTimes()
  1417  		mockStore.EXPECT().GetService(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes()
  1418  		mockStore.EXPECT().AddService(gomock.Any()).Return(nil).AnyTimes()
  1419  
  1420  		resp := svr.CreateService(context.TODO(), req)
  1421  		assert.Equal(t, apimodel.Code_ExecuteSuccess, apimodel.Code(resp.GetCode().GetValue()))
  1422  		assert.True(t, len(resp.GetService().GetId().GetValue()) > 0)
  1423  	})
  1424  
  1425  	t.Run("正常创建服务-目标服务已存在", func(t *testing.T) {
  1426  		svr, mockStore := createMockResource()
  1427  		mockStore.EXPECT().GetNamespace(gomock.Any()).Return(&model.Namespace{
  1428  			Name: "mock_ns",
  1429  		}, nil).AnyTimes()
  1430  		mockStore.EXPECT().GetService(gomock.Any(), gomock.Any()).Return(&model.Service{
  1431  			ID: "mock_svc_id",
  1432  		}, nil).AnyTimes()
  1433  
  1434  		resp := svr.CreateService(context.TODO(), req)
  1435  		assert.Equal(t, apimodel.Code_ExistedResource, apimodel.Code(resp.GetCode().GetValue()))
  1436  		assert.True(t, len(resp.GetService().GetId().GetValue()) > 0)
  1437  	})
  1438  
  1439  	t.Run("正常创建服务-存储层主键冲突", func(t *testing.T) {
  1440  		svr, mockStore := createMockResource()
  1441  		mockStore.EXPECT().GetNamespace(gomock.Any()).Return(&model.Namespace{
  1442  			Name: "mock_ns",
  1443  		}, nil).AnyTimes()
  1444  
  1445  		var (
  1446  			execTime  int32
  1447  			mockSvcId = "mock_svc_id"
  1448  		)
  1449  
  1450  		mockStore.EXPECT().GetService(gomock.Any(), gomock.Any()).DoAndReturn(func(_, _ string) (*model.Service, error) {
  1451  			execTime++
  1452  			if execTime == 1 {
  1453  				return nil, nil
  1454  			}
  1455  			if execTime == 2 {
  1456  				return &model.Service{ID: mockSvcId}, nil
  1457  			}
  1458  			return nil, errors.New("run to many times")
  1459  		}).AnyTimes()
  1460  		mockStore.EXPECT().AddService(gomock.Any()).
  1461  			Return(store.NewStatusError(store.DuplicateEntryErr, "mock duplicate error")).AnyTimes()
  1462  
  1463  		resp := svr.CreateService(context.TODO(), req)
  1464  		assert.Equal(t, apimodel.Code_ExistedResource, apimodel.Code(resp.GetCode().GetValue()))
  1465  		assert.Equal(t, mockSvcId, resp.GetService().GetId().GetValue())
  1466  	})
  1467  }