github.com/polarismesh/polaris@v1.17.8/service/instance_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 "math/rand" 24 "strconv" 25 "strings" 26 "sync" 27 "sync/atomic" 28 "testing" 29 "time" 30 31 "github.com/golang/protobuf/proto" 32 apimodel "github.com/polarismesh/specification/source/go/api/v1/model" 33 apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage" 34 . "github.com/smartystreets/goconvey/convey" 35 "github.com/stretchr/testify/assert" 36 "google.golang.org/protobuf/types/known/wrapperspb" 37 38 api "github.com/polarismesh/polaris/common/api/v1" 39 "github.com/polarismesh/polaris/common/model" 40 "github.com/polarismesh/polaris/common/utils" 41 "github.com/polarismesh/polaris/service" 42 "github.com/polarismesh/polaris/store" 43 ) 44 45 // 测试新建实例 46 func TestCreateInstance(t *testing.T) { 47 48 discoverSuit := &DiscoverTestSuit{} 49 if err := discoverSuit.Initialize(); err != nil { 50 t.Fatal(err) 51 } 52 defer discoverSuit.Destroy() 53 54 _, serviceResp := discoverSuit.createCommonService(t, 100) 55 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 56 57 t.Run("正常创建实例-服务没有提前创建", func(t *testing.T) { 58 svr := discoverSuit.OriginDiscoverServer().(*service.Server) 59 bc := svr.GetBatchController() 60 svr.MockBatchController(nil) 61 defer func() { 62 svr.MockBatchController(bc) 63 }() 64 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, &apiservice.Service{ 65 Name: utils.NewStringValue("test-nocreate-service"), 66 Namespace: utils.NewStringValue(service.DefaultNamespace), 67 }, 1000) 68 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 69 70 if instanceResp.GetId().GetValue() != "" { 71 t.Logf("pass: %s", instanceResp.GetId().GetValue()) 72 } else { 73 t.Fatalf("error") 74 } 75 76 if instanceResp.GetNamespace().GetValue() == instanceReq.GetNamespace().GetValue() && 77 instanceResp.GetService().GetValue() == instanceReq.GetService().GetValue() { 78 t.Logf("pass") 79 } else { 80 t.Fatalf("error: %+v", instanceResp) 81 } 82 }) 83 84 t.Run("正常创建实例-服务已创建", func(t *testing.T) { 85 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 1000) 86 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 87 88 if instanceResp.GetId().GetValue() != "" { 89 t.Logf("pass: %s", instanceResp.GetId().GetValue()) 90 } else { 91 t.Fatalf("error") 92 } 93 94 if instanceResp.GetNamespace().GetValue() == instanceReq.GetNamespace().GetValue() && 95 instanceResp.GetService().GetValue() == instanceReq.GetService().GetValue() { 96 t.Logf("pass") 97 } else { 98 t.Fatalf("error: %+v", instanceResp) 99 } 100 }) 101 102 t.Run("重复注册,会覆盖已存在的资源", func(t *testing.T) { 103 req, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 1000) 104 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 105 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{req}) 106 if respSuccess(resp) { 107 t.Logf("pass: %+v", resp) 108 } else { 109 t.Fatalf("error: %+v", resp) 110 } 111 if resp.Responses[0].Instance.GetId().GetValue() == "" { 112 t.Fatalf("error: %+v", resp) 113 } 114 // 强制先update一次,规避上一次的数据查询结果 115 discoverSuit.DiscoverServer().Cache().TestUpdate() 116 discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{}) 117 }) 118 119 t.Run("instance有metadata个数和字符要求的限制", func(t *testing.T) { 120 instanceReq := &apiservice.Instance{ 121 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 122 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 123 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 124 Host: utils.NewStringValue("123"), 125 Port: utils.NewUInt32Value(456), 126 Metadata: make(map[string]string), 127 } 128 for i := 0; i < service.MaxMetadataLength+1; i++ { 129 instanceReq.Metadata[fmt.Sprintf("%d", i)] = fmt.Sprintf("%d", i) 130 } 131 if resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); respSuccess(resp) { 132 t.Fatalf("error") 133 } else { 134 t.Logf("pass: %s", resp.GetInfo().GetValue()) 135 } 136 }) 137 t.Run("healthcheck为空测试", func(t *testing.T) { 138 instanceReq := &apiservice.Instance{ 139 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 140 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 141 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 142 Host: utils.NewStringValue("aaaaaaaaaaaaaa"), 143 Port: utils.NewUInt32Value(456), 144 HealthCheck: &apiservice.HealthCheck{}, 145 } 146 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 147 if !respSuccess(resp) { 148 t.Fatalf("error: %+v", resp) 149 } 150 defer discoverSuit.cleanInstance(resp.Responses[0].GetInstance().GetId().GetValue()) 151 152 discoverSuit.cleanInstance(resp.Responses[0].GetInstance().GetId().GetValue()) 153 instanceReq.HealthCheck = &apiservice.HealthCheck{ 154 Heartbeat: &apiservice.HeartbeatHealthCheck{}, 155 } 156 resp = discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 157 if !respSuccess(resp) { 158 t.Fatalf("error: %+v", resp) 159 } 160 // 强制先update一次,规避上一次的数据查询结果 161 discoverSuit.DiscoverServer().Cache().TestUpdate() 162 getResp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{"host": instanceReq.GetHost().GetValue()}) 163 assert.True(t, getResp.GetCode().GetValue() == api.ExecuteSuccess) 164 t.Logf("%+v", getResp) 165 if getResp.GetInstances()[0].HealthCheck.Type != apiservice.HealthCheck_HEARTBEAT { 166 t.Fatalf("error") 167 } 168 if getResp.GetInstances()[0].HealthCheck.Heartbeat.Ttl.Value != service.DefaultTLL { 169 t.Fatalf("error") 170 } 171 }) 172 t.Run("instance可以提供id,以覆盖server生成id的逻辑", func(t *testing.T) { 173 const providedInstanceId = "instance-provided-id" 174 instanceReq := &apiservice.Instance{ 175 Id: utils.NewStringValue(providedInstanceId), 176 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 177 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 178 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 179 Host: utils.NewStringValue("123"), 180 Port: utils.NewUInt32Value(456), 181 } 182 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 183 assert.True(t, resp.GetCode().GetValue() == api.ExecuteSuccess) 184 if resp.Responses[0].GetInstance().GetId().GetValue() != providedInstanceId { 185 t.Fatalf("error") 186 } else { 187 t.Logf("pass: %s", resp.GetInfo().GetValue()) 188 } 189 }) 190 } 191 192 // 测试异常场景 193 func TestCreateInstanceWithNoService(t *testing.T) { 194 195 discoverSuit := &DiscoverTestSuit{} 196 if err := discoverSuit.Initialize(); err != nil { 197 t.Fatal(err) 198 } 199 defer discoverSuit.Destroy() 200 201 t.Run("无权限注册,可以捕获正常的错误", func(t *testing.T) { 202 serviceReq := genMainService(900) 203 serviceReq.Namespace = utils.NewStringValue("test-auth-namespace") 204 discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue()) 205 206 resp := discoverSuit.DiscoverServer().CreateServices(discoverSuit.DefaultCtx, []*apiservice.Service{serviceReq}) 207 if !respSuccess(resp) { 208 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 209 } 210 serviceResp := resp.Responses[0].GetService() 211 212 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 213 var reqs []*apiservice.Instance 214 reqs = append(reqs, &apiservice.Instance{ 215 Service: serviceResp.Name, 216 Namespace: serviceResp.Namespace, 217 ServiceToken: serviceResp.Token, 218 Host: utils.NewStringValue("1111"), 219 Port: utils.NewUInt32Value(0), 220 }) 221 reqs = append(reqs, &apiservice.Instance{ 222 Service: serviceResp.Name, 223 Namespace: serviceResp.Namespace, 224 ServiceToken: utils.NewStringValue("error token"), 225 Host: utils.NewStringValue("1111"), 226 Port: utils.NewUInt32Value(1), 227 }) 228 229 oldCtx := discoverSuit.DefaultCtx 230 discoverSuit.DefaultCtx = context.Background() 231 232 defer func() { 233 discoverSuit.DefaultCtx = oldCtx 234 }() 235 236 // 等待一段时间的刷新 237 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 238 239 resps := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, reqs) 240 if respSuccess(resps) { 241 t.Fatalf("error : %s", resps.GetInfo().GetValue()) 242 } 243 if resps.Responses[0].GetCode().GetValue() != api.NotAllowedAccess { 244 t.Fatalf("error: %d %s", resps.Responses[0].GetCode().GetValue(), resps.Responses[0].GetInfo().GetValue()) 245 } 246 }) 247 } 248 249 // 并发注册 250 func TestCreateInstance2(t *testing.T) { 251 252 discoverSuit := &DiscoverTestSuit{} 253 if err := discoverSuit.Initialize(); err != nil { 254 t.Fatal(err) 255 } 256 defer discoverSuit.Destroy() 257 258 t.Run("并发注册,可以正常注册", func(t *testing.T) { 259 var serviceResps []*apiservice.Service 260 for i := 0; i < 10; i++ { 261 _, serviceResp := discoverSuit.createCommonService(t, i) 262 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 263 serviceResps = append(serviceResps, serviceResp) 264 } 265 266 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 267 total := 20 268 var wg sync.WaitGroup 269 start := time.Now() 270 errs := make(chan error) 271 for i := 0; i < total; i++ { 272 wg.Add(1) 273 go func(index int) { 274 defer wg.Done() 275 var req *apiservice.Instance 276 var resp *apiservice.Instance 277 req, resp = discoverSuit.createCommonInstance(t, serviceResps[index%10], index) 278 for c := 0; c < 10; c++ { 279 if updateResp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{req}); !respSuccess(updateResp) { 280 errs <- fmt.Errorf("error: %+v", updateResp) 281 return 282 } 283 } 284 discoverSuit.removeCommonInstance(t, serviceResps[index%10], resp.GetId().GetValue()) 285 discoverSuit.cleanInstance(resp.GetId().GetValue()) 286 }(i) 287 } 288 289 go func() { 290 wg.Wait() 291 close(errs) 292 }() 293 294 for err := range errs { 295 if err != nil { 296 t.Fatal(err) 297 } 298 } 299 t.Logf("consume: %v", time.Since(start)) 300 }) 301 } 302 303 // 并发更新同一个实例 304 func TestUpdateInstanceManyTimes(t *testing.T) { 305 306 discoverSuit := &DiscoverTestSuit{} 307 if err := discoverSuit.Initialize(); err != nil { 308 t.Fatal(err) 309 } 310 defer discoverSuit.Destroy() 311 312 _, serviceResp := discoverSuit.createCommonService(t, 100) 313 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 314 315 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 10) 316 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 317 318 var wg sync.WaitGroup 319 errs := make(chan error) 320 for i := 0; i < 64; i++ { 321 wg.Add(1) 322 go func(index int) { 323 defer wg.Done() 324 for c := 0; c < 16; c++ { 325 marshalVal, err := proto.Marshal(instanceReq) 326 if err != nil { 327 errs <- err 328 return 329 } 330 331 ret := &apiservice.Instance{} 332 proto.Unmarshal(marshalVal, ret) 333 334 ret.Weight.Value = uint32(rand.Int() % 32767) 335 if updateResp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(updateResp) { 336 errs <- fmt.Errorf("error: %+v", updateResp) 337 return 338 } 339 } 340 }(i) 341 } 342 go func() { 343 wg.Wait() 344 close(errs) 345 }() 346 347 for err := range errs { 348 if err != nil { 349 t.Fatal(err) 350 } 351 } 352 } 353 354 func TestGetInstancesById(t *testing.T) { 355 discoverSuit := &DiscoverTestSuit{} 356 if err := discoverSuit.Initialize(); err != nil { 357 t.Fatal(err) 358 } 359 defer discoverSuit.Destroy() 360 361 _, svc := discoverSuit.createCommonService(t, 1) 362 defer discoverSuit.cleanServiceName(svc.GetName().GetValue(), svc.GetNamespace().GetValue()) 363 var instances []*apiservice.Instance 364 var reqInstances []*apiservice.Instance 365 defer func() { 366 for _, entry := range instances { 367 discoverSuit.cleanInstance(entry.GetId().GetValue()) 368 } 369 }() 370 371 idPrefix := "prefix-" 372 prefixCount := 5 373 idSuffix := "-suffix" 374 suffixCount := 3 375 for i := 0; i < prefixCount; i++ { 376 req, instance := discoverSuit.createCommonInstanceById( 377 t, svc, i, fmt.Sprintf("%s%d", idPrefix, i)) 378 instances = append(instances, instance) 379 reqInstances = append(reqInstances, req) 380 } 381 for i := 0; i < suffixCount; i++ { 382 req, instance := discoverSuit.createCommonInstanceById( 383 t, svc, i, fmt.Sprintf("%d%s", i, idSuffix)) 384 instances = append(instances, instance) 385 reqInstances = append(reqInstances, req) 386 } 387 t.Run("根据精准匹配ID进行获取实例", func(t *testing.T) { 388 instId := fmt.Sprintf("%s%d", idPrefix, 0) 389 // 强制先update一次,规避上一次的数据查询结果 390 discoverSuit.DiscoverServer().Cache().TestUpdate() 391 out := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{"id": instId}) 392 assert.True(t, respSuccess(out)) 393 assert.Equal(t, 1, len(out.GetInstances())) 394 //instance := out.GetInstances()[0] 395 for _, instance := range out.GetInstances() { 396 assert.Equal(t, instId, instance.GetId().GetValue()) 397 assert.Equal(t, svc.GetNamespace().GetValue(), instance.GetNamespace().GetValue()) 398 assert.Equal(t, svc.GetName().GetValue(), instance.GetService().GetValue()) 399 } 400 }) 401 t.Run("根据前缀匹配ID进行获取实例", func(t *testing.T) { 402 instId := fmt.Sprintf("%s%s", idPrefix, "*") 403 // 强制先update一次,规避上一次的数据查询结果 404 discoverSuit.DiscoverServer().Cache().TestUpdate() 405 out := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{"id": instId}) 406 assert.True(t, respSuccess(out)) 407 assert.Equal(t, prefixCount, len(out.GetInstances())) 408 for _, instance := range out.GetInstances() { 409 assert.True(t, strings.HasPrefix(instance.GetId().GetValue(), idPrefix)) 410 assert.Equal(t, svc.GetNamespace().GetValue(), instance.GetNamespace().GetValue()) 411 assert.Equal(t, svc.GetName().GetValue(), instance.GetService().GetValue()) 412 } 413 }) 414 t.Run("根据后缀匹配ID进行获取实例", func(t *testing.T) { 415 instId := fmt.Sprintf("%s%s", "*", idSuffix) 416 // 强制先update一次,规避上一次的数据查询结果 417 discoverSuit.DiscoverServer().Cache().TestUpdate() 418 out := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{"id": instId}) 419 assert.True(t, respSuccess(out)) 420 assert.Equal(t, suffixCount, len(out.GetInstances())) 421 for _, instance := range out.GetInstances() { 422 assert.True(t, strings.HasSuffix(instance.GetId().GetValue(), idSuffix)) 423 assert.Equal(t, svc.GetNamespace().GetValue(), instance.GetNamespace().GetValue()) 424 assert.Equal(t, svc.GetName().GetValue(), instance.GetService().GetValue()) 425 } 426 }) 427 } 428 429 // 测试获取实例 430 func TestGetInstances(t *testing.T) { 431 discoverSuit := &DiscoverTestSuit{} 432 if err := discoverSuit.Initialize(); err != nil { 433 t.Fatal(err) 434 } 435 defer discoverSuit.Destroy() 436 t.Run("可以正常获取到实例信息", func(t *testing.T) { 437 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() // 为了防止影响,每个函数需要把缓存的内容清空 438 _, serviceResp := discoverSuit.createCommonService(t, 320) 439 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 440 441 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 442 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 30) 443 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 444 445 // 需要等待一会,等本地缓存更新 446 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 447 req := &apiservice.Service{ 448 Name: utils.NewStringValue(instanceResp.GetService().GetValue()), 449 Namespace: utils.NewStringValue(instanceResp.GetNamespace().GetValue()), 450 } 451 resp := discoverSuit.DiscoverServer().ServiceInstancesCache(discoverSuit.DefaultCtx, req) 452 if !respSuccess(resp) { 453 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 454 } 455 456 discoverSuit.discoveryCheck(t, req, resp) 457 458 if len(resp.Instances) != 1 { 459 t.Fatalf("error : %d", len(resp.Instances)) 460 } 461 462 instanceCheck(t, instanceReq, resp.GetInstances()[0]) 463 t.Logf("pass: %+v", resp.GetInstances()[0]) 464 }) 465 t.Run("注册实例,查询实例列表,实例反注册,revision会改变", func(t *testing.T) { 466 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() // 为了防止影响,每个函数需要把缓存的内容清空 467 _, serviceResp := discoverSuit.createCommonService(t, 100) 468 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 469 470 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 90) 471 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 472 473 // 需要等待一会,等本地缓存更新 474 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 475 resp := discoverSuit.DiscoverServer().ServiceInstancesCache(discoverSuit.DefaultCtx, serviceResp) 476 if !respSuccess(resp) { 477 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 478 } 479 revision := resp.GetService().GetRevision() 480 481 // 再注册一个实例,revision会改变 482 _, instanceResp = discoverSuit.createCommonInstance(t, serviceResp, 100) 483 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 484 485 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 486 resp = discoverSuit.DiscoverServer().ServiceInstancesCache(discoverSuit.DefaultCtx, serviceResp) 487 if !respSuccess(resp) { 488 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 489 } 490 491 if revision == resp.GetService().GetRevision() { 492 t.Fatalf("error") 493 } 494 t.Logf("%s, %s", revision, resp.GetService().GetRevision()) 495 }) 496 } 497 498 // 测试获取多个实例 499 func TestGetInstances1(t *testing.T) { 500 501 discoverSuit := &DiscoverTestSuit{} 502 if err := discoverSuit.Initialize(); err != nil { 503 t.Fatal(err) 504 } 505 defer discoverSuit.Destroy() 506 507 discover := func(t *testing.T, service *apiservice.Service, check func(cnt int) bool) *apiservice.DiscoverResponse { 508 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 509 time.Sleep(discoverSuit.UpdateCacheInterval()) 510 resp := discoverSuit.DiscoverServer().ServiceInstancesCache(discoverSuit.DefaultCtx, service) 511 if !respSuccess(resp) { 512 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 513 } 514 discoverSuit.discoveryCheck(t, service, resp) 515 if !check(len(resp.Instances)) { 516 t.Fatalf("error : check instance cnt fail, acutal : %d", len(resp.Instances)) 517 } 518 return resp 519 } 520 t.Run("注册并反注册多个实例,可以正常获取", func(t *testing.T) { 521 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() // 为了防止影响,每个函数需要把缓存的内容清空 522 _, serviceResp := discoverSuit.createCommonService(t, 320) 523 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 524 525 var ids []string 526 for i := 0; i < 10; i++ { 527 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i) 528 ids = append(ids, instanceResp.GetId().GetValue()) 529 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 530 } 531 discover(t, serviceResp, func(cnt int) bool { 532 return cnt == 10 533 }) 534 535 // 反注册一部分 536 for i := 1; i < 6; i++ { 537 discoverSuit.removeCommonInstance(t, serviceResp, ids[i]) 538 } 539 540 discover(t, serviceResp, func(cnt int) bool { 541 return cnt >= 5 542 }) 543 }) 544 t.Run("传递revision, revision有变化则有数据,否则无数据返回", func(t *testing.T) { 545 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() // 为了防止影响,每个函数需要把缓存的内容清空 546 _, serviceResp := discoverSuit.createCommonService(t, 100) 547 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 548 for i := 0; i < 5; i++ { 549 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i) 550 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 551 } 552 firstResp := discover(t, serviceResp, func(cnt int) bool { 553 return 5 == cnt 554 }) 555 556 serviceResp.Revision = firstResp.Service.GetRevision() 557 if resp := discoverSuit.DiscoverServer().ServiceInstancesCache(discoverSuit.DefaultCtx, serviceResp); !respSuccess(resp) { 558 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 559 } else { 560 if len(resp.Instances) != 0 { 561 t.Fatalf("error: %d", len(resp.Instances)) 562 } 563 t.Logf("%+v", resp) 564 } 565 566 // 多注册一个实例,revision发生改变 567 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 20) 568 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 569 discover(t, serviceResp, func(cnt int) bool { 570 return 6 == cnt || cnt == 5 571 }) 572 573 }) 574 } 575 576 // 反注册测试 577 func TestRemoveInstance(t *testing.T) { 578 579 discoverSuit := &DiscoverTestSuit{} 580 if err := discoverSuit.Initialize(); err != nil { 581 t.Fatal(err) 582 } 583 defer discoverSuit.Destroy() 584 585 _, serviceResp := discoverSuit.createCommonService(t, 15) 586 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 587 t.Run("实例创建完马上反注册,可以成功", func(t *testing.T) { 588 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 88) 589 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 590 591 discoverSuit.removeCommonInstance(t, serviceResp, instanceResp.GetId().GetValue()) 592 t.Logf("pass") 593 }) 594 595 t.Run("注册完实例,反注册,再注册,可以成功", func(t *testing.T) { 596 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 888) 597 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 598 599 discoverSuit.removeCommonInstance(t, serviceResp, instanceResp.GetId().GetValue()) 600 _, instanceResp = discoverSuit.createCommonInstance(t, serviceResp, 888) 601 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 602 t.Logf("pass") 603 }) 604 t.Run("重复反注册,返回成功", func(t *testing.T) { 605 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 999) 606 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 607 608 discoverSuit.removeCommonInstance(t, serviceResp, instanceResp.GetId().GetValue()) 609 discoverSuit.removeCommonInstance(t, serviceResp, instanceResp.GetId().GetValue()) 610 }) 611 t.Run("反注册,获取不到心跳信息", func(t *testing.T) { 612 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 1111) 613 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 614 615 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 616 discoverSuit.HeartBeat(t, serviceResp, instanceResp.GetId().GetValue()) 617 resp := discoverSuit.GetLastHeartBeat(t, serviceResp, instanceResp.GetId().GetValue()) 618 if !respSuccess(resp) { 619 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 620 } 621 622 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 623 discoverSuit.removeCommonInstance(t, serviceResp, instanceResp.GetId().GetValue()) 624 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 625 resp = discoverSuit.GetLastHeartBeat(t, serviceResp, instanceResp.GetId().GetValue()) 626 if !respNotFound(resp) { 627 t.Fatalf("heart beat resp should be not found, but got %v", resp) 628 } 629 t.Logf("pass") 630 }) 631 } 632 633 // 测试从数据库拉取实例信息 634 func TestListInstances(t *testing.T) { 635 636 discoverSuit := &DiscoverTestSuit{} 637 if err := discoverSuit.Initialize(); err != nil { 638 t.Fatal(err) 639 } 640 defer discoverSuit.Destroy() 641 642 t.Run("list实例列表,返回的数据字段都存在", func(t *testing.T) { 643 _, serviceResp := discoverSuit.createCommonService(t, 1156) 644 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 645 646 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 200) 647 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 648 649 query := map[string]string{"offset": "0", "limit": "100"} 650 query["host"] = instanceReq.GetHost().GetValue() 651 query["port"] = strconv.FormatUint(uint64(instanceReq.GetPort().GetValue()), 10) 652 653 // 强制先update一次,规避上一次的数据查询结果 654 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 655 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 656 if !respSuccess(resp) { 657 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 658 } 659 if len(resp.Instances) != 1 { 660 t.Fatalf("error: %d", len(resp.Instances)) 661 } 662 663 instanceCheck(t, instanceReq, resp.Instances[0]) 664 }) 665 t.Run("list实例列表,offset和limit能正常工作", func(t *testing.T) { 666 _, serviceResp := discoverSuit.createCommonService(t, 115) 667 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 668 669 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 670 total := 50 671 var responses []*apiservice.Instance 672 for i := 0; i < total; i++ { 673 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i+1) 674 responses = append(responses, instanceResp) 675 } 676 defer func() { 677 for _, resp := range responses { 678 discoverSuit.cleanInstance(resp.GetId().GetValue()) 679 } 680 }() 681 682 // host 不存在,查不出任何实例 683 query := map[string]string{"offset": "10", "limit": "20", "host": "127.0.0.1"} 684 685 // 强制先update一次,规避上一次的数据查询结果 686 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 687 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 688 if !respSuccess(resp) { 689 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 690 } 691 assert.Equal(t, 0, len(resp.Instances)) 692 693 // 不带条件查询 694 query = map[string]string{"offset": "10", "limit": "20"} 695 696 // 强制先update一次,规避上一次的数据查询结果 697 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 698 resp = discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 699 if !respSuccess(resp) { 700 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 701 } 702 assert.Equal(t, 20, len(resp.Instances)) 703 }) 704 705 t.Run("list全部实例列表", func(t *testing.T) { 706 _, serviceResp := discoverSuit.createCommonService(t, 116) 707 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 708 709 time.Sleep(discoverSuit.UpdateCacheInterval()) 710 total := 100 711 var responses []*apiservice.Instance 712 for i := 0; i < total; i++ { 713 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i+1) 714 responses = append(responses, instanceResp) 715 } 716 defer func() { 717 for _, resp := range responses { 718 discoverSuit.cleanInstance(resp.GetId().GetValue()) 719 } 720 }() 721 722 query := map[string]string{"offset": "0", "limit": "200"} 723 724 // 强制先update一次,规避上一次的数据查询结果 725 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 726 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 727 if !respSuccess(resp) { 728 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 729 } 730 assert.Equal(t, total, len(resp.Instances)) 731 }) 732 733 t.Run("list实例列表,可以进行正常字段过滤", func(t *testing.T) { 734 // 先任意找几个实例字段过滤 735 _, serviceResp := discoverSuit.createCommonService(t, 200) 736 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 737 738 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 739 total := 10 740 instance := new(apiservice.Instance) 741 for i := 0; i < total; i++ { 742 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i+1) 743 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 744 instance = instanceResp 745 } 746 747 host := instance.GetHost().GetValue() 748 port := strconv.FormatUint(uint64(instance.GetPort().GetValue()), 10) 749 query := map[string]string{"limit": "20", "host": host, "port": port} 750 751 // 强制先update一次,规避上一次的数据查询结果 752 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 753 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 754 if !respSuccess(resp) { 755 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 756 } 757 if len(resp.Instances) == 1 { 758 t.Logf("pass") 759 } 760 }) 761 } 762 763 // 测试list实例列表 764 func TestListInstances1(t *testing.T) { 765 checkAmountAndSize := func(t *testing.T, resp *apiservice.BatchQueryResponse, expect int, size int) { 766 if !respSuccess(resp) { 767 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 768 } 769 if resp.GetAmount().GetValue() != uint32(expect) { 770 t.Fatalf("error: %d", resp.GetAmount().GetValue()) 771 } 772 if len(resp.Instances) != size { 773 t.Fatalf("error: %d", len(resp.Instances)) 774 } 775 } 776 777 t.Run("list实例,使用service和namespace过滤", func(t *testing.T) { 778 discoverSuit := &DiscoverTestSuit{} 779 if err := discoverSuit.Initialize(); err != nil { 780 t.Fatal(err) 781 } 782 defer discoverSuit.Destroy() 783 784 // 先任意找几个实例字段过滤 785 _, serviceResp := discoverSuit.createCommonService(t, 800) 786 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 787 total := 102 788 for i := 0; i < total; i++ { 789 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i+2) 790 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 791 } 792 query := map[string]string{ 793 "offset": "0", 794 "limit": "100", 795 "service": serviceResp.GetName().GetValue(), 796 "namespace": serviceResp.GetNamespace().GetValue(), 797 } 798 799 // 强制先update一次,规避上一次的数据查询结果 800 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 801 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 802 checkAmountAndSize(t, resp, total, 100) 803 }) 804 805 t.Run("list实例,先删除实例,再查询会过滤删除的", func(t *testing.T) { 806 discoverSuit := &DiscoverTestSuit{} 807 if err := discoverSuit.Initialize(); err != nil { 808 t.Fatal(err) 809 } 810 defer discoverSuit.Destroy() 811 812 // 先任意找几个实例字段过滤 813 _, serviceResp := discoverSuit.createCommonService(t, 800) 814 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 815 total := 50 816 for i := 0; i < total; i++ { 817 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, i+2) 818 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 819 if i%2 == 0 { 820 discoverSuit.removeCommonInstance(t, serviceResp, instanceResp.GetId().GetValue()) 821 } 822 } 823 824 query := map[string]string{ 825 "service": serviceResp.GetName().GetValue(), 826 "namespace": serviceResp.GetNamespace().GetValue(), 827 } 828 829 // 强制先update一次,规避上一次的数据查询结果 830 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 831 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 832 checkAmountAndSize(t, resp, total/2, total/2) 833 834 }) 835 t.Run("true和false测试", func(t *testing.T) { 836 discoverSuit := &DiscoverTestSuit{} 837 if err := discoverSuit.Initialize(); err != nil { 838 t.Fatal(err) 839 } 840 defer discoverSuit.Destroy() 841 842 // 先任意找几个实例字段过滤 843 _, serviceResp := discoverSuit.createCommonService(t, 800) 844 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 845 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 10) 846 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 847 848 query := map[string]string{ 849 "service": serviceResp.GetName().GetValue(), 850 "namespace": serviceResp.GetNamespace().GetValue(), 851 "isolate": "false", 852 "healthy": "false", 853 } 854 // 强制先update一次,规避上一次的数据查询结果 855 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 856 857 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 1, 1) 858 859 query["isolate"] = "true" 860 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 0, 0) 861 862 query["isolate"] = "false" 863 query["healthy"] = "true" 864 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 0, 0) 865 866 query["isolate"] = "0" 867 query["healthy"] = "0" 868 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 1, 1) 869 870 query["health_status"] = "1" 871 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 1, 1) 872 873 query["health_status"] = "0" 874 delete(query, "healthy") 875 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 1, 1) 876 877 query["health_status"] = "1" 878 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 0, 0) 879 }) 880 t.Run("metadata条件测试", func(t *testing.T) { 881 discoverSuit := &DiscoverTestSuit{} 882 if err := discoverSuit.Initialize(); err != nil { 883 t.Fatal(err) 884 } 885 defer discoverSuit.Destroy() 886 887 // 先任意找几个实例字段过滤 888 _, serviceResp := discoverSuit.createCommonService(t, 800) 889 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 890 _, instanceResp1 := discoverSuit.createCommonInstance(t, serviceResp, 10) 891 defer discoverSuit.cleanInstance(instanceResp1.GetId().GetValue()) 892 _, instanceResp2 := discoverSuit.createCommonInstance(t, serviceResp, 20) 893 defer discoverSuit.cleanInstance(instanceResp2.GetId().GetValue()) 894 // 只返回第一个实例的查询 895 query := map[string]string{ 896 "service": serviceResp.GetName().GetValue(), 897 "namespace": serviceResp.GetNamespace().GetValue(), 898 "keys": "internal-personal-xxx", 899 "values": "internal-personal-xxx_10", 900 } 901 // 强制先update一次,规避上一次的数据查询结果 902 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 903 904 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 1, 1) 905 // 使用共同的元数据查询,返回两个实例 906 query = map[string]string{ 907 "service": serviceResp.GetName().GetValue(), 908 "namespace": serviceResp.GetNamespace().GetValue(), 909 "keys": "my-meta-a1", 910 "values": "1111", 911 } 912 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 2, 2) 913 // 使用不存在的元数据查询,返回零个实例 914 query = map[string]string{ 915 "service": serviceResp.GetName().GetValue(), 916 "namespace": serviceResp.GetNamespace().GetValue(), 917 "keys": "nokey", 918 "values": "novalue", 919 } 920 checkAmountAndSize(t, discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query), 0, 0) 921 }) 922 t.Run("metadata只有key或者value,返回错误", func(t *testing.T) { 923 discoverSuit := &DiscoverTestSuit{} 924 if err := discoverSuit.Initialize(); err != nil { 925 t.Fatal(err) 926 } 927 defer discoverSuit.Destroy() 928 929 // 先任意找几个实例字段过滤 930 _, serviceResp := discoverSuit.createCommonService(t, 800) 931 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 932 query := map[string]string{ 933 "service": serviceResp.GetName().GetValue(), 934 "namespace": serviceResp.GetNamespace().GetValue(), 935 "keys": "internal-personal-xxx", 936 } 937 // 强制先update一次,规避上一次的数据查询结果 938 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 939 940 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 941 if resp.GetCode().GetValue() != api.InvalidQueryInsParameter { 942 t.Fatalf("resp is %v, not InvalidQueryInsParameter", resp) 943 } 944 query = map[string]string{ 945 "service": serviceResp.GetName().GetValue(), 946 "namespace": serviceResp.GetNamespace().GetValue(), 947 "values": "internal-personal-xxx", 948 } 949 resp = discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 950 if resp.GetCode().GetValue() != api.InvalidQueryInsParameter { 951 t.Fatalf("resp is %v, not InvalidQueryInsParameter", resp) 952 } 953 }) 954 } 955 956 // 测试list实例列表 957 func TestListInstances2(t *testing.T) { 958 checkAmountAndSize := func(t *testing.T, resp *apiservice.BatchQueryResponse, expect int, size int) { 959 if !respSuccess(resp) { 960 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 961 } 962 if resp.GetAmount().GetValue() != uint32(expect) { 963 t.Fatalf("error: %d", resp.GetAmount().GetValue()) 964 } 965 if len(resp.Instances) != size { 966 t.Fatalf("error: %d", len(resp.Instances)) 967 } 968 } 969 970 t.Run("list实例,使用namespace,可以进行模糊匹配过滤", func(t *testing.T) { 971 discoverSuit := &DiscoverTestSuit{} 972 if err := discoverSuit.Initialize(); err != nil { 973 t.Fatal(err) 974 } 975 defer discoverSuit.Destroy() 976 977 // 先任意找几个实例字段过滤 978 _, serviceResp := discoverSuit.createCommonService(t, 800) 979 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 980 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 1001) 981 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 982 query := map[string]string{ 983 "offset": "0", 984 "limit": "100", 985 "namespace": "*fau*", 986 "keys": "my-meta-a1", 987 "values": "1111", 988 } 989 990 // 强制先update一次,规避上一次的数据查询结果 991 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 992 993 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 994 checkAmountAndSize(t, resp, 1, 1) 995 }) 996 997 t.Run("list实例,使用namespace,可以进行前缀匹配过滤", func(t *testing.T) { 998 discoverSuit := &DiscoverTestSuit{} 999 if err := discoverSuit.Initialize(); err != nil { 1000 t.Fatal(err) 1001 } 1002 defer discoverSuit.Destroy() 1003 1004 // 先任意找几个实例字段过滤 1005 _, serviceResp := discoverSuit.createCommonService(t, 800) 1006 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1007 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 1002) 1008 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1009 query := map[string]string{ 1010 "offset": "0", 1011 "limit": "100", 1012 "namespace": "defau*", 1013 "keys": "my-meta-a1", 1014 "values": "1111", 1015 } 1016 1017 // 强制先update一次,规避上一次的数据查询结果 1018 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1019 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 1020 checkAmountAndSize(t, resp, 1, 1) 1021 1022 query = map[string]string{ 1023 "offset": "0", 1024 "limit": "100", 1025 "namespace": "defauxxxx*", 1026 "keys": "my-meta-a1", 1027 "values": "1111", 1028 } 1029 resp = discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 1030 checkAmountAndSize(t, resp, 0, 0) 1031 }) 1032 1033 t.Run("list实例,使用namespace,service可选", func(t *testing.T) { 1034 discoverSuit := &DiscoverTestSuit{} 1035 if err := discoverSuit.Initialize(); err != nil { 1036 t.Fatal(err) 1037 } 1038 defer discoverSuit.Destroy() 1039 1040 // 先任意找几个实例字段过滤 1041 _, serviceResp := discoverSuit.createCommonService(t, 800) 1042 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1043 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 1003) 1044 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1045 query := map[string]string{ 1046 "offset": "0", 1047 "limit": "100", 1048 "service": serviceResp.GetName().GetValue(), 1049 "keys": "my-meta-a1", 1050 "values": "1111", 1051 } 1052 // 强制先update一次,规避上一次的数据查询结果 1053 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1054 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 1055 checkAmountAndSize(t, resp, 1, 1) 1056 1057 query = map[string]string{ 1058 "offset": "0", 1059 "limit": "100", 1060 "namespace": serviceResp.GetNamespace().GetValue(), 1061 "keys": "my-meta-a1", 1062 "values": "1111", 1063 } 1064 resp = discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 1065 checkAmountAndSize(t, resp, 1, 1) 1066 }) 1067 } 1068 1069 // 测试地域获取 1070 func TestInstancesContainLocation(t *testing.T) { 1071 1072 discoverSuit := &DiscoverTestSuit{} 1073 if err := discoverSuit.Initialize(); err != nil { 1074 t.Fatal(err) 1075 } 1076 defer discoverSuit.Destroy() 1077 1078 locationCheck := func(lhs *apimodel.Location, rhs *apimodel.Location) { 1079 if lhs.GetRegion().GetValue() != rhs.GetRegion().GetValue() { 1080 t.Fatalf("error: %v, %v", lhs, rhs) 1081 } 1082 if lhs.GetZone().GetValue() != rhs.GetZone().GetValue() { 1083 t.Fatalf("error: %v, %v", lhs, rhs) 1084 } 1085 if lhs.GetCampus().GetValue() != rhs.GetCampus().GetValue() { 1086 t.Fatalf("error: %v, %v", lhs, rhs) 1087 } 1088 } 1089 1090 _, service := discoverSuit.createCommonService(t, 123) 1091 defer discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue()) 1092 1093 instance := &apiservice.Instance{ 1094 Service: service.GetName(), 1095 Namespace: service.GetNamespace(), 1096 ServiceToken: service.GetToken(), 1097 Host: utils.NewStringValue("123456"), 1098 Port: utils.NewUInt32Value(9090), 1099 Location: &apimodel.Location{ 1100 Region: utils.NewStringValue("region1"), 1101 Zone: utils.NewStringValue("zone1"), 1102 Campus: utils.NewStringValue("campus1"), 1103 }, 1104 } 1105 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instance}) 1106 if !respSuccess(resp) { 1107 t.Fatalf("error: %+v", resp) 1108 } 1109 defer discoverSuit.cleanInstance(resp.Responses[0].GetInstance().GetId().GetValue()) 1110 1111 // 强制先update一次,规避上一次的数据查询结果 1112 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1113 getResp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{ 1114 "service": instance.GetService().GetValue(), "namespace": instance.GetNamespace().GetValue(), 1115 }) 1116 if !respSuccess(getResp) { 1117 t.Fatalf("error: %+v", getResp) 1118 } 1119 getInstances := getResp.GetInstances() 1120 if len(getInstances) != 1 { 1121 t.Fatalf("error: %d", len(getInstances)) 1122 } 1123 t.Logf("%v", getInstances[0]) 1124 locationCheck(instance.GetLocation(), getInstances[0].GetLocation()) 1125 1126 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1127 discoverResp := discoverSuit.DiscoverServer().ServiceInstancesCache(discoverSuit.DefaultCtx, service) 1128 if len(discoverResp.GetInstances()) != 1 { 1129 t.Fatalf("error: %d", len(discoverResp.GetInstances())) 1130 } 1131 t.Logf("%v", discoverResp.GetInstances()[0]) 1132 locationCheck(instance.GetLocation(), discoverResp.GetInstances()[0].GetLocation()) 1133 } 1134 1135 // 测试实例更新 1136 func TestUpdateInstance(t *testing.T) { 1137 1138 discoverSuit := &DiscoverTestSuit{} 1139 if err := discoverSuit.Initialize(); err != nil { 1140 t.Fatal(err) 1141 } 1142 defer discoverSuit.Destroy() 1143 1144 _, serviceResp := discoverSuit.createCommonService(t, 123) 1145 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1146 1147 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 22) 1148 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1149 t.Run("更新实例,所有属性都可以生效", func(t *testing.T) { 1150 // update 1151 instanceReq.Protocol = utils.NewStringValue("update-protocol") 1152 instanceReq.Version = utils.NewStringValue("update-version") 1153 instanceReq.Priority = utils.NewUInt32Value(30) 1154 instanceReq.Weight = utils.NewUInt32Value(500) 1155 instanceReq.Healthy = utils.NewBoolValue(false) 1156 instanceReq.Isolate = utils.NewBoolValue(true) 1157 instanceReq.LogicSet = utils.NewStringValue("update-logic-set") 1158 instanceReq.HealthCheck = &apiservice.HealthCheck{ 1159 Type: apiservice.HealthCheck_HEARTBEAT, 1160 Heartbeat: &apiservice.HeartbeatHealthCheck{ 1161 Ttl: utils.NewUInt32Value(6), 1162 }, 1163 } 1164 instanceReq.Metadata = map[string]string{ 1165 "internal-personal-xxx": "internal-personal-xxx_2412323", 1166 "tencent": "1111", 1167 "yyyy": "2222", 1168 } 1169 instanceReq.ServiceToken = serviceResp.Token 1170 1171 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1172 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1173 } 1174 1175 // 查询数据 1176 query := map[string]string{ 1177 "host": instanceReq.GetHost().GetValue(), 1178 "port": strconv.FormatUint(uint64(instanceReq.GetPort().GetValue()), 10), 1179 } 1180 // 强制先update一次,规避上一次的数据查询结果 1181 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1182 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 1183 if !respSuccess(resp) { 1184 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1185 } 1186 if len(resp.GetInstances()) != 1 { 1187 t.Fatalf("error: %d", len(resp.GetInstances())) 1188 } 1189 1190 instanceReq.Service = instanceResp.Service 1191 instanceReq.Namespace = instanceResp.Namespace 1192 instanceCheck(t, instanceReq, resp.Instances[0]) 1193 }) 1194 t.Run("实例只更新metadata,revision也会发生改变", func(t *testing.T) { 1195 instanceReq.Metadata = map[string]string{ 1196 "new-metadata": "new-value", 1197 } 1198 1199 serviceName := serviceResp.GetName().GetValue() 1200 namespaceName := serviceResp.GetNamespace().GetValue() 1201 firstInstances := discoverSuit.getInstancesWithService(t, serviceName, namespaceName, 1) 1202 1203 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1204 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1205 } 1206 1207 secondInstances := discoverSuit.getInstancesWithService(t, serviceName, namespaceName, 1) 1208 if firstInstances[0].GetRevision().GetValue() != secondInstances[0].GetRevision().GetValue() { 1209 t.Logf("pass %s, %s", 1210 firstInstances[0].GetRevision().GetValue(), secondInstances[0].GetRevision().GetValue()) 1211 } else { 1212 t.Fatalf("error") 1213 } 1214 1215 instanceCheck(t, instanceReq, secondInstances[0]) 1216 }) 1217 t.Run("metadata太长,update会报错", func(t *testing.T) { 1218 instanceReq.Metadata = make(map[string]string) 1219 for i := 0; i < service.MaxMetadataLength+1; i++ { 1220 instanceReq.Metadata[fmt.Sprintf("%d", i)] = "a" 1221 } 1222 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1223 t.Logf("pass: %s", resp.GetInfo().GetValue()) 1224 } else { 1225 t.Fatalf("error") 1226 } 1227 }) 1228 } 1229 1230 /** 1231 * @brief 根据ip修改隔离状态 1232 */ 1233 func TestUpdateIsolate(t *testing.T) { 1234 1235 discoverSuit := &DiscoverTestSuit{} 1236 if err := discoverSuit.Initialize(); err != nil { 1237 t.Fatal(err) 1238 } 1239 defer discoverSuit.Destroy() 1240 1241 _, serviceResp := discoverSuit.createCommonService(t, 111) 1242 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1243 t.Run("修改超过100个实例的隔离状态", func(t *testing.T) { 1244 instancesReq := make([]*apiservice.Instance, 0, 210) 1245 for i := 0; i < 210; i++ { 1246 instanceReq := &apiservice.Instance{ 1247 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 1248 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 1249 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 1250 Host: utils.NewStringValue("127.0.0.1"), 1251 Port: utils.NewUInt32Value(uint32(i)), 1252 } 1253 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 1254 if !respSuccess(resp) { 1255 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1256 } 1257 instancesReq = append(instancesReq, instanceReq) 1258 defer discoverSuit.cleanInstance(resp.Responses[0].GetInstance().GetId().GetValue()) 1259 } 1260 req := &apiservice.Instance{ 1261 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 1262 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 1263 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 1264 Host: utils.NewStringValue("127.0.0.1"), 1265 Isolate: utils.NewBoolValue(true), 1266 } 1267 if resp := discoverSuit.DiscoverServer().UpdateInstancesIsolate(discoverSuit.DefaultCtx, []*apiservice.Instance{req}); !respSuccess(resp) { 1268 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1269 } 1270 t.Log("pass") 1271 }) 1272 1273 t.Run("根据ip修改隔离状态", func(t *testing.T) { 1274 instanceNum := 20 1275 portNum := 2 1276 revisions := make(map[string]string, instanceNum) 1277 instancesReq := make([]*apiservice.Instance, 0, instanceNum) 1278 for i := 0; i < instanceNum/portNum; i++ { 1279 for j := 1; j <= portNum; j++ { 1280 instanceReq := &apiservice.Instance{ 1281 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 1282 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 1283 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 1284 Host: utils.NewStringValue(fmt.Sprintf("%d.%d.%d.%d", i, i, i, i)), 1285 Port: utils.NewUInt32Value(uint32(j)), 1286 Isolate: utils.NewBoolValue(false), 1287 Healthy: utils.NewBoolValue(true), 1288 Metadata: map[string]string{ 1289 "internal-personal-xxx": fmt.Sprintf("internal-personal-xxx_%d", i), 1290 }, 1291 } 1292 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 1293 if !respSuccess(resp) { 1294 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1295 } 1296 instanceReq.Isolate = utils.NewBoolValue(true) 1297 instancesReq = append(instancesReq, instanceReq) 1298 revisions[resp.Responses[0].GetInstance().GetId().GetValue()] = resp.Responses[0].GetInstance().GetRevision().GetValue() 1299 defer discoverSuit.cleanInstance(resp.Responses[0].GetInstance().GetId().GetValue()) 1300 } 1301 } 1302 1303 if resp := discoverSuit.DiscoverServer().UpdateInstancesIsolate(discoverSuit.DefaultCtx, instancesReq); !respSuccess(resp) { 1304 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1305 } 1306 1307 // 强制先update一次,规避上一次的数据查询结果 1308 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1309 // 检查隔离状态和revision是否改变 1310 for i := 0; i < instanceNum/portNum; i++ { 1311 filter := map[string]string{ 1312 "service": serviceResp.GetName().GetValue(), 1313 "namespace": serviceResp.GetNamespace().GetValue(), 1314 "host": fmt.Sprintf("%d.%d.%d.%d", i, i, i, i), 1315 } 1316 1317 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, filter) 1318 if !respSuccess(resp) { 1319 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1320 } 1321 1322 if len(resp.GetInstances()) != portNum { 1323 t.Fatalf("error: %d", len(resp.GetInstances())) 1324 } 1325 1326 actualInstances := resp.GetInstances() 1327 for _, instance := range actualInstances { 1328 if !instance.GetIsolate().GetValue() || 1329 instance.GetRevision().GetValue() == revisions[instance.GetId().GetValue()] { 1330 t.Fatalf("error instance is %+v", instance) 1331 } 1332 } 1333 } 1334 t.Log("pass") 1335 }) 1336 1337 t.Run("并发更新", func(t *testing.T) { 1338 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 123) 1339 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1340 1341 var wg sync.WaitGroup 1342 errs := make(chan error) 1343 for i := 0; i < 64; i++ { 1344 wg.Add(1) 1345 go func(index int) { 1346 defer wg.Done() 1347 for c := 0; c < 16; c++ { 1348 instanceReq.Isolate = utils.NewBoolValue(true) 1349 if resp := discoverSuit.DiscoverServer().UpdateInstancesIsolate(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1350 errs <- fmt.Errorf("error: %+v", resp) 1351 return 1352 } 1353 } 1354 }(i) 1355 } 1356 go func() { 1357 wg.Wait() 1358 close(errs) 1359 }() 1360 1361 for err := range errs { 1362 if err != nil { 1363 t.Fatal(err) 1364 } 1365 } 1366 t.Log("pass") 1367 }) 1368 1369 t.Run("若隔离状态相同,则不需要更新", func(t *testing.T) { 1370 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 456) 1371 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1372 1373 resp := discoverSuit.DiscoverServer().UpdateInstancesIsolate(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 1374 if resp.GetCode().GetValue() == api.NoNeedUpdate { 1375 t.Logf("pass: %s", resp.GetInfo().GetValue()) 1376 } else { 1377 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1378 } 1379 }) 1380 } 1381 1382 /** 1383 * @brief 根据ip删除服务实例 1384 */ 1385 func TestDeleteInstanceByHost(t *testing.T) { 1386 1387 discoverSuit := &DiscoverTestSuit{} 1388 if err := discoverSuit.Initialize(); err != nil { 1389 t.Fatal(err) 1390 } 1391 defer discoverSuit.Destroy() 1392 1393 _, serviceResp := discoverSuit.createCommonService(t, 222) 1394 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1395 1396 t.Run("根据ip删除服务实例", func(t *testing.T) { 1397 instanceNum := 20 1398 portNum := 2 1399 instancesReq := make([]*apiservice.Instance, 0, instanceNum) 1400 for i := 0; i < instanceNum/portNum; i++ { 1401 for j := 1; j <= portNum; j++ { 1402 instanceReq := &apiservice.Instance{ 1403 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 1404 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 1405 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 1406 Host: utils.NewStringValue(fmt.Sprintf("%d.%d.%d.%d", i, i, i, i)), 1407 Port: utils.NewUInt32Value(uint32(j)), 1408 } 1409 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 1410 if !respSuccess(resp) { 1411 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1412 } 1413 instancesReq = append(instancesReq, instanceReq) 1414 defer discoverSuit.cleanInstance(resp.Responses[0].GetInstance().GetId().GetValue()) 1415 } 1416 } 1417 1418 if resp := discoverSuit.DiscoverServer().DeleteInstancesByHost(discoverSuit.DefaultCtx, instancesReq); !respSuccess(resp) { 1419 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1420 } 1421 1422 // 检查隔离状态和revision是否改变 1423 discoverSuit.getInstancesWithService(t, 1424 serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue(), 0) 1425 t.Log("pass") 1426 }) 1427 1428 t.Run("删除超过100个实例", func(t *testing.T) { 1429 instancesReq := make([]*apiservice.Instance, 0, 210) 1430 for i := 0; i < 210; i++ { 1431 instanceReq := &apiservice.Instance{ 1432 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 1433 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 1434 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 1435 Host: utils.NewStringValue("127.0.0.2"), 1436 Port: utils.NewUInt32Value(uint32(i)), 1437 } 1438 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 1439 if !respSuccess(resp) { 1440 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1441 } 1442 instancesReq = append(instancesReq, instanceReq) 1443 defer discoverSuit.cleanInstance(resp.Responses[0].GetInstance().GetId().GetValue()) 1444 } 1445 req := &apiservice.Instance{ 1446 ServiceToken: utils.NewStringValue(serviceResp.GetToken().GetValue()), 1447 Service: utils.NewStringValue(serviceResp.GetName().GetValue()), 1448 Namespace: utils.NewStringValue(serviceResp.GetNamespace().GetValue()), 1449 Host: utils.NewStringValue("127.0.0.1"), 1450 Isolate: utils.NewBoolValue(true), 1451 } 1452 if resp := discoverSuit.DiscoverServer().DeleteInstancesByHost(discoverSuit.DefaultCtx, []*apiservice.Instance{req}); !respSuccess(resp) { 1453 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1454 } 1455 t.Log("pass") 1456 }) 1457 } 1458 1459 // 测试enable_health_check 1460 func TestUpdateHealthCheck(t *testing.T) { 1461 1462 discoverSuit := &DiscoverTestSuit{} 1463 if err := discoverSuit.Initialize(); err != nil { 1464 t.Fatal(err) 1465 } 1466 defer discoverSuit.Destroy() 1467 1468 getAndCheck := func(t *testing.T, req *apiservice.Instance) { 1469 query := map[string]string{ 1470 "host": req.GetHost().GetValue(), 1471 "port": strconv.FormatUint(uint64(req.GetPort().GetValue()), 10), 1472 } 1473 // 强制先update一次,规避上一次的数据查询结果 1474 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1475 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 1476 if !respSuccess(resp) { 1477 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1478 } 1479 if len(resp.GetInstances()) != 1 { 1480 t.Fatalf("error: %d", len(resp.GetInstances())) 1481 } 1482 t.Logf("%+v", resp.Instances[0]) 1483 1484 instanceCheck(t, req, resp.Instances[0]) 1485 } 1486 _, serviceResp := discoverSuit.createCommonService(t, 321) 1487 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1488 1489 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 10) 1490 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1491 instanceReq.ServiceToken = serviceResp.Token 1492 t.Run("health_check可以随意关闭", func(t *testing.T) { 1493 // 打开 -> 打开 1494 instanceReq.Weight = utils.NewUInt32Value(300) 1495 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1496 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1497 } 1498 getAndCheck(t, instanceReq) 1499 1500 // 打开-> 关闭 1501 instanceReq.EnableHealthCheck = utils.NewBoolValue(false) 1502 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1503 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1504 } 1505 instanceReq.HealthCheck = nil 1506 getAndCheck(t, instanceReq) 1507 1508 // 关闭 -> 关闭 1509 instanceReq.Weight = utils.NewUInt32Value(200) 1510 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1511 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1512 } 1513 getAndCheck(t, instanceReq) 1514 1515 // 关闭 -> 打开 1516 instanceReq.EnableHealthCheck = utils.NewBoolValue(true) 1517 instanceReq.HealthCheck = &apiservice.HealthCheck{ 1518 Type: apiservice.HealthCheck_HEARTBEAT, 1519 Heartbeat: &apiservice.HeartbeatHealthCheck{ 1520 Ttl: utils.NewUInt32Value(8), 1521 }, 1522 } 1523 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1524 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1525 } 1526 getAndCheck(t, instanceReq) 1527 }) 1528 t.Run("healthcheck为空的异常测试", func(t *testing.T) { 1529 instanceReq.HealthCheck = &apiservice.HealthCheck{ 1530 Heartbeat: &apiservice.HeartbeatHealthCheck{ 1531 Ttl: utils.NewUInt32Value(0), 1532 }, 1533 } 1534 if resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}); !respSuccess(resp) { 1535 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1536 } 1537 instanceReq.HealthCheck = &apiservice.HealthCheck{ 1538 Type: apiservice.HealthCheck_HEARTBEAT, 1539 Heartbeat: &apiservice.HeartbeatHealthCheck{ 1540 Ttl: utils.NewUInt32Value(service.DefaultTLL), 1541 }, 1542 } 1543 getAndCheck(t, instanceReq) 1544 }) 1545 } 1546 1547 // 测试删除实例 1548 func TestDeleteInstance(t *testing.T) { 1549 1550 discoverSuit := &DiscoverTestSuit{} 1551 if err := discoverSuit.Initialize(); err != nil { 1552 t.Fatal(err) 1553 } 1554 defer discoverSuit.Destroy() 1555 1556 _, serviceResp := discoverSuit.createCommonService(t, 123) 1557 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1558 1559 getInstance := func(t *testing.T, s *apiservice.Service, expect int) []*apiservice.Instance { 1560 filters := map[string]string{"service": s.GetName().GetValue(), "namespace": s.GetNamespace().GetValue()} 1561 // 强制先update一次,规避上一次的数据查询结果 1562 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1563 getResp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, filters) 1564 if !respSuccess(getResp) { 1565 t.Fatalf("error") 1566 } 1567 if len(getResp.GetInstances()) != expect { 1568 t.Fatalf("error") 1569 } 1570 return getResp.GetInstances() 1571 } 1572 1573 t.Run("可以通过ID删除实例", func(t *testing.T) { 1574 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 10) 1575 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1576 discoverSuit.removeCommonInstance(t, serviceResp, instanceResp.GetId().GetValue()) 1577 1578 getInstance(t, serviceResp, 0) 1579 }) 1580 t.Run("可以通过四元组删除实例", func(t *testing.T) { 1581 req := &apiservice.Instance{ 1582 ServiceToken: serviceResp.GetToken(), 1583 Service: serviceResp.GetName(), 1584 Namespace: serviceResp.GetNamespace(), 1585 Host: utils.NewStringValue("abc"), 1586 Port: utils.NewUInt32Value(8080), 1587 } 1588 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{req}) 1589 if !respSuccess(resp) { 1590 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 1591 } 1592 instanceResp := resp.Responses[0].GetInstance() 1593 t.Logf("%+v", getInstance(t, serviceResp, 1)) 1594 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1595 1596 discoverSuit.removeInstanceWithAttrs(t, serviceResp, instanceResp) 1597 getInstance(t, serviceResp, 0) 1598 }) 1599 t.Run("可以通过五元组删除实例", func(t *testing.T) { 1600 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 55) 1601 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1602 1603 discoverSuit.removeInstanceWithAttrs(t, serviceResp, instanceResp) 1604 getInstance(t, serviceResp, 0) 1605 }) 1606 } 1607 1608 // 批量创建服务实例 1609 // 步骤: 1610 // 1. n个服务,每个服务m个服务实例 1611 // 2. n个协程同时发请求 1612 func TestBatchCreateInstances(t *testing.T) { 1613 1614 discoverSuit := &DiscoverTestSuit{} 1615 if err := discoverSuit.Initialize(); err != nil { 1616 t.Fatal(err) 1617 } 1618 defer discoverSuit.Destroy() 1619 1620 Convey("批量创建服务", t, func() { 1621 n := 32 1622 m := 128 1623 var services []*apiservice.Service 1624 for i := 0; i < n; i++ { 1625 _, service := discoverSuit.createCommonService(t, i) 1626 services = append(services, service) 1627 } 1628 defer discoverSuit.cleanServices(services) 1629 1630 var wg sync.WaitGroup 1631 idCh := make(chan string, n*m) 1632 for i := 0; i < n; i++ { 1633 wg.Add(1) 1634 go func(index int) { 1635 defer wg.Done() 1636 for j := 0; j < m; j++ { 1637 _, instance := discoverSuit.createCommonInstance(t, services[index], j) 1638 idCh <- instance.GetId().GetValue() 1639 } 1640 }(i) 1641 } 1642 1643 var deleteCount int32 1644 for i := 0; i < n; i++ { 1645 go func() { 1646 for id := range idCh { 1647 discoverSuit.cleanInstance(id) 1648 atomic.AddInt32(&deleteCount, 1) 1649 } 1650 }() 1651 } 1652 1653 wg.Wait() 1654 for { 1655 count := atomic.LoadInt32(&deleteCount) 1656 if count == int32(n*m) { 1657 return 1658 } 1659 t.Logf("%d", count) 1660 time.Sleep(time.Second * 1) 1661 } 1662 1663 }) 1664 } 1665 1666 // 测试批量接口返回的顺序 1667 func TestCreateInstancesOrder(t *testing.T) { 1668 1669 discoverSuit := &DiscoverTestSuit{} 1670 if err := discoverSuit.Initialize(); err != nil { 1671 t.Fatal(err) 1672 } 1673 defer discoverSuit.Destroy() 1674 1675 t.Run("测试批量接口返回的顺序与发送的数据一致", func(t *testing.T) { 1676 _, service := discoverSuit.createCommonService(t, 123) 1677 defer discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue()) 1678 var instances []*apiservice.Instance 1679 for j := 0; j < 10; j++ { 1680 instances = append(instances, &apiservice.Instance{ 1681 Service: service.GetName(), 1682 Namespace: service.GetNamespace(), 1683 ServiceToken: service.GetToken(), 1684 Host: utils.NewStringValue("a.b.c.d"), 1685 Port: utils.NewUInt32Value(uint32(j)), 1686 }) 1687 } 1688 1689 resps := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, instances) 1690 if !respSuccess(resps) { 1691 t.Fatalf("error: %+v", resps) 1692 } 1693 for i, resp := range resps.GetResponses() { 1694 if resp.GetInstance().GetPort().GetValue() != instances[i].GetPort().GetValue() { 1695 t.Fatalf("error") 1696 } 1697 discoverSuit.cleanInstance(resp.GetInstance().GetId().GetValue()) 1698 } 1699 }) 1700 } 1701 1702 // 测试批量删除实例 1703 func TestBatchDeleteInstances(t *testing.T) { 1704 1705 discoverSuit := &DiscoverTestSuit{} 1706 if err := discoverSuit.Initialize(); err != nil { 1707 t.Fatal(err) 1708 } 1709 defer discoverSuit.Destroy() 1710 1711 _, service := discoverSuit.createCommonService(t, 234) 1712 defer discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue()) 1713 createInstances := func(t *testing.T) ([]*apiservice.Instance, *apiservice.BatchWriteResponse) { 1714 var instances []*apiservice.Instance 1715 for j := 0; j < 100; j++ { 1716 instances = append(instances, &apiservice.Instance{ 1717 Service: service.GetName(), 1718 Namespace: service.GetNamespace(), 1719 ServiceToken: service.GetToken(), 1720 Host: utils.NewStringValue("a.b.c.d"), 1721 Port: utils.NewUInt32Value(uint32(j)), 1722 }) 1723 } 1724 resps := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, instances) 1725 if !respSuccess(resps) { 1726 t.Fatalf("error: %+v", resps) 1727 } 1728 return instances, resps 1729 } 1730 t.Run("测试batch删除实例,单个接口", func(t *testing.T) { 1731 _, resps := createInstances(t) 1732 var wg sync.WaitGroup 1733 errs := make(chan error) 1734 for _, resp := range resps.GetResponses() { 1735 wg.Add(1) 1736 go func(instance *apiservice.Instance) { 1737 defer func() { 1738 discoverSuit.cleanInstance(instance.GetId().GetValue()) 1739 wg.Done() 1740 }() 1741 req := &apiservice.Instance{Id: instance.Id, ServiceToken: service.Token} 1742 if out := discoverSuit.DiscoverServer().DeleteInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{req}); !respSuccess(out) { 1743 errs <- fmt.Errorf("error: %+v", out) 1744 return 1745 } 1746 }(resp.GetInstance()) 1747 } 1748 go func() { 1749 wg.Wait() 1750 close(errs) 1751 }() 1752 1753 for err := range errs { 1754 if err != nil { 1755 t.Fatal(err) 1756 } 1757 } 1758 }) 1759 t.Run("测试batch删除实例,批量接口", func(t *testing.T) { 1760 instances, instancesResp := createInstances(t) 1761 // 删除body的token,测试header的token是否可行 1762 for _, instance := range instances { 1763 instance.ServiceToken = nil 1764 instance.Id = nil 1765 } 1766 ctx := context.WithValue(discoverSuit.DefaultCtx, utils.StringContext("polaris-token"), service.GetToken().GetValue()) 1767 if out := discoverSuit.DiscoverServer().DeleteInstances(ctx, instances); !respSuccess(out) { 1768 t.Fatalf("error: %+v", out) 1769 } else { 1770 t.Logf("%+v", out) 1771 } 1772 // 强制先update一次,规避上一次的数据查询结果 1773 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1774 resps := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{ 1775 "service": service.GetName().GetValue(), 1776 "namespace": service.GetNamespace().GetValue(), 1777 }) 1778 if !respSuccess(resps) { 1779 t.Fatalf("error: %+v", resps) 1780 } 1781 if len(resps.GetInstances()) != 0 { 1782 t.Fatalf("error : %d", len(resps.GetInstances())) 1783 } 1784 for _, entry := range instancesResp.GetResponses() { 1785 discoverSuit.cleanInstance(entry.GetInstance().GetId().GetValue()) 1786 } 1787 }) 1788 } 1789 1790 // 验证成功创建和删除实例的response 1791 func TestInstanceResponse(t *testing.T) { 1792 1793 discoverSuit := &DiscoverTestSuit{} 1794 if err := discoverSuit.Initialize(); err != nil { 1795 t.Fatal(err) 1796 } 1797 defer discoverSuit.Destroy() 1798 1799 _, service := discoverSuit.createCommonService(t, 234) 1800 defer discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue()) 1801 create := func() (*apiservice.Instance, *apiservice.Instance) { 1802 ins := &apiservice.Instance{ 1803 Service: service.GetName(), 1804 Namespace: service.GetNamespace(), 1805 ServiceToken: service.GetToken(), 1806 Host: utils.NewStringValue("a.b.c.d"), 1807 Port: utils.NewUInt32Value(uint32(100)), 1808 } 1809 resps := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 1810 if !respSuccess(resps) { 1811 t.Fatalf("error: %+v", resps) 1812 } 1813 return ins, resps.Responses[0].GetInstance() 1814 } 1815 t.Run("创建实例,返回的信息不能包括token,包括id", func(t *testing.T) { 1816 ins, respIns := create() 1817 defer discoverSuit.cleanInstance(respIns.GetId().GetValue()) 1818 t.Logf("%+v", respIns) 1819 if respIns.GetService().GetValue() != ins.GetService().GetValue() || 1820 respIns.GetNamespace().GetValue() != ins.GetNamespace().GetValue() || 1821 respIns.GetHost().GetValue() != ins.GetHost().GetValue() || 1822 respIns.GetPort().GetValue() != ins.GetPort().GetValue() || 1823 respIns.GetId().GetValue() == "" || respIns.GetServiceToken().GetValue() != "" { 1824 t.Fatalf("error") 1825 } 1826 }) 1827 t.Run("删除实例,返回的信息包括req,不增加信息", func(t *testing.T) { 1828 req, resp := create() 1829 defer discoverSuit.cleanInstance(resp.GetId().GetValue()) 1830 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1831 resps := discoverSuit.DiscoverServer().DeleteInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{req}) 1832 if !respSuccess(resps) { 1833 t.Fatalf("error: %+v", resps) 1834 } 1835 respIns := resps.GetResponses()[0].GetInstance() 1836 if respIns.GetId().GetValue() != "" || respIns.GetService() != req.GetService() || 1837 respIns.GetNamespace() != req.GetNamespace() || respIns.GetHost() != req.GetHost() || 1838 respIns.GetPort() != req.GetPort() || respIns.GetServiceToken() != req.GetServiceToken() { 1839 t.Fatalf("error") 1840 } 1841 t.Logf("pass") 1842 }) 1843 } 1844 1845 // 测试实例创建与删除的异常场景2 1846 func TestCreateInstancesBadCase2(t *testing.T) { 1847 1848 discoverSuit := &DiscoverTestSuit{} 1849 if err := discoverSuit.Initialize(); err != nil { 1850 t.Fatal(err) 1851 } 1852 defer discoverSuit.Destroy() 1853 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 1854 1855 _, service := discoverSuit.createCommonService(t, 123) 1856 defer discoverSuit.cleanServiceName(service.GetName().GetValue(), service.GetNamespace().GetValue()) 1857 t.Run("重复多个一样的实例注册,其中一个成功,其他的失败", func(t *testing.T) { 1858 var instances []*apiservice.Instance 1859 for j := 0; j < 3; j++ { 1860 instances = append(instances, &apiservice.Instance{ 1861 Service: service.GetName(), 1862 Namespace: service.GetNamespace(), 1863 ServiceToken: service.GetToken(), 1864 Host: utils.NewStringValue("a.b.c.d"), 1865 Port: utils.NewUInt32Value(uint32(100)), 1866 }) 1867 } 1868 1869 resps := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, instances) 1870 t.Logf("%+v", resps) 1871 if respSuccess(resps) { 1872 t.Fatalf("error: %+v", resps) 1873 } 1874 for _, resp := range resps.GetResponses() { 1875 if resp.GetInstance().GetId().GetValue() != "" { 1876 discoverSuit.cleanInstance(resp.GetInstance().GetId().GetValue()) 1877 } 1878 } 1879 }) 1880 t.Run("重复发送同样实例的反注册请求,可以正常返回,一个成功,其他的失败", func(t *testing.T) { 1881 instance := &apiservice.Instance{ 1882 Service: service.GetName(), 1883 Namespace: service.GetNamespace(), 1884 ServiceToken: service.GetToken(), 1885 Host: utils.NewStringValue("a.b.c.d"), 1886 Port: utils.NewUInt32Value(uint32(100)), 1887 } 1888 resps := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instance}) 1889 if !respSuccess(resps) { 1890 t.Fatalf("error: %+v", resps) 1891 } 1892 defer discoverSuit.cleanInstance(resps.Responses[0].Instance.GetId().GetValue()) 1893 1894 delReqs := make([]*apiservice.Instance, 0, 10) 1895 for i := 0; i < 2; i++ { 1896 delReqs = append(delReqs, &apiservice.Instance{ 1897 Id: resps.Responses[0].Instance.GetId(), 1898 ServiceToken: service.GetToken(), 1899 }) 1900 } 1901 resps = discoverSuit.DiscoverServer().DeleteInstances(discoverSuit.DefaultCtx, delReqs) 1902 if respSuccess(resps) { 1903 t.Fatalf("error: %s", resps) 1904 } 1905 for _, resp := range resps.GetResponses() { 1906 if resp.GetCode().GetValue() != api.ExecuteSuccess && 1907 resp.GetCode().GetValue() != api.SameInstanceRequest { 1908 t.Fatalf("error: %+v", resp) 1909 } 1910 } 1911 }) 1912 } 1913 1914 // 测试instance,no need update 1915 func TestInstanceNoNeedUpdate(t *testing.T) { 1916 1917 discoverSuit := &DiscoverTestSuit{} 1918 if err := discoverSuit.Initialize(); err != nil { 1919 t.Fatal(err) 1920 } 1921 defer discoverSuit.Destroy() 1922 1923 _, serviceResp := discoverSuit.createCommonService(t, 222) 1924 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1925 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 222) 1926 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1927 Convey("instance没有变更,不需要更新", t, func() { 1928 resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 1929 So(resp.GetCode().GetValue(), ShouldEqual, api.NoNeedUpdate) 1930 }) 1931 Convey("metadata为空,不需要更新", t, func() { 1932 oldMeta := instanceReq.GetMetadata() 1933 instanceReq.Metadata = nil 1934 defer func() { instanceReq.Metadata = oldMeta }() 1935 resp := discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}) 1936 So(resp.GetCode().GetValue(), ShouldEqual, api.NoNeedUpdate) 1937 }) 1938 Convey("healthCheck为nil,不需要更新", t, func() { 1939 oldHealthCheck := instanceReq.GetHealthCheck() 1940 instanceReq.HealthCheck = nil 1941 defer func() { instanceReq.HealthCheck = oldHealthCheck }() 1942 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, 1943 []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.NoNeedUpdate) 1944 }) 1945 } 1946 1947 func TestUpdateInstanceField(t *testing.T) { 1948 discoverSuit := &DiscoverTestSuit{} 1949 if err := discoverSuit.Initialize(); err != nil { 1950 t.Fatal(err) 1951 } 1952 defer discoverSuit.Destroy() 1953 1954 _, serviceResp := discoverSuit.createCommonService(t, 181) 1955 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 1956 1957 _, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 181) 1958 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 1959 instId := instanceResp.GetId().GetValue() 1960 Convey("metadata变更", t, func() { 1961 request := &apiservice.Instance{Id: wrapperspb.String(instId)} 1962 request.Metadata = map[string]string{} 1963 So(discoverSuit.DiscoverServer().UpdateInstance( 1964 discoverSuit.DefaultCtx, request).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 1965 1966 request.Metadata = map[string]string{"123": "456", "789": "abc", "135": "246"} 1967 So(discoverSuit.DiscoverServer().UpdateInstance( 1968 discoverSuit.DefaultCtx, request).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 1969 1970 instance, err := discoverSuit.Storage.GetInstance(instId) 1971 So(err, ShouldBeNil) 1972 So(instance.Proto.Host.GetValue(), ShouldEqual, instanceResp.Host.GetValue()) 1973 }) 1974 1975 Convey("isolate变更", t, func() { 1976 request := &apiservice.Instance{Id: wrapperspb.String(instId)} 1977 request.Isolate = wrapperspb.Bool(true) 1978 So(discoverSuit.DiscoverServer().UpdateInstance( 1979 discoverSuit.DefaultCtx, request).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 1980 instance, err := discoverSuit.Storage.GetInstance(instId) 1981 So(err, ShouldBeNil) 1982 So(instance.Proto.Isolate.GetValue(), ShouldEqual, true) 1983 1984 request.Isolate = wrapperspb.Bool(false) 1985 So(discoverSuit.DiscoverServer().UpdateInstance( 1986 discoverSuit.DefaultCtx, request).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 1987 1988 instance, err = discoverSuit.Storage.GetInstance(instId) 1989 So(err, ShouldBeNil) 1990 So(instance.Proto.Isolate.GetValue(), ShouldEqual, false) 1991 }) 1992 1993 } 1994 1995 // 实例数据更新测试 1996 // 部分数据变更,触发更新 1997 func TestUpdateInstancesFiled(t *testing.T) { 1998 1999 discoverSuit := &DiscoverTestSuit{} 2000 if err := discoverSuit.Initialize(); err != nil { 2001 t.Fatal(err) 2002 } 2003 defer discoverSuit.Destroy() 2004 2005 _, serviceResp := discoverSuit.createCommonService(t, 555) 2006 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 2007 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 555) 2008 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 2009 Convey("metadata变更", t, func() { 2010 instanceReq.Metadata = map[string]string{} 2011 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2012 2013 instanceReq.Metadata = map[string]string{"123": "456", "789": "abc", "135": "246"} 2014 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2015 2016 instanceReq.Metadata["890"] = "678" 2017 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2018 2019 delete(instanceReq.Metadata, "135") 2020 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2021 }) 2022 Convey("healthCheck变更", t, func() { 2023 instanceReq.HealthCheck.Heartbeat.Ttl.Value = 33 2024 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2025 2026 instanceReq.EnableHealthCheck = utils.NewBoolValue(false) 2027 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2028 // 强制先update一次,规避上一次的数据查询结果 2029 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 2030 newInstanceResp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{ 2031 "service": serviceResp.GetName().GetValue(), 2032 "namespace": serviceResp.GetNamespace().GetValue(), 2033 }) 2034 So(newInstanceResp.GetInstances()[0].GetHealthCheck(), ShouldBeNil) 2035 instanceReq.HealthCheck = nil 2036 2037 instanceReq.EnableHealthCheck = utils.NewBoolValue(true) 2038 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.NoNeedUpdate) 2039 2040 instanceReq.HealthCheck = &apiservice.HealthCheck{ 2041 Type: apiservice.HealthCheck_HEARTBEAT, 2042 Heartbeat: &apiservice.HeartbeatHealthCheck{Ttl: utils.NewUInt32Value(50)}, 2043 } 2044 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2045 }) 2046 Convey("其他字段变更", t, func() { 2047 instanceReq.Protocol.Value = "new-protocol-1" 2048 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2049 2050 instanceReq.Version.Value = "new-version-1" 2051 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2052 2053 instanceReq.Priority.Value = 88 2054 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2055 2056 instanceReq.Weight.Value = 500 2057 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2058 2059 instanceReq.Healthy.Value = true 2060 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2061 2062 instanceReq.Isolate.Value = true 2063 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2064 2065 instanceReq.LogicSet.Value = "new-logic-set-1" 2066 So(discoverSuit.DiscoverServer().UpdateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{instanceReq}).GetCode().GetValue(), ShouldEqual, api.ExecuteSuccess) 2067 2068 // 强制先update一次,规避上一次的数据查询结果 2069 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 2070 newInstanceResp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, map[string]string{ 2071 "service": serviceResp.GetName().GetValue(), 2072 "namespace": serviceResp.GetNamespace().GetValue(), 2073 }) 2074 instanceCheck(t, newInstanceResp.GetInstances()[0], instanceReq) 2075 }) 2076 } 2077 2078 // 根据服务名获取实例列表并且做基础的判断 2079 func (d *DiscoverTestSuit) getInstancesWithService(t *testing.T, name string, namespace string, expectCount int) []*apiservice.Instance { 2080 2081 query := map[string]string{ 2082 "service": name, 2083 "namespace": namespace, 2084 } 2085 // 强制先update一次,规避上一次的数据查询结果 2086 _ = d.DiscoverServer().Cache().TestUpdate() 2087 resp := d.DiscoverServer().GetInstances(d.DefaultCtx, query) 2088 if !respSuccess(resp) { 2089 t.Fatalf("error: %s", resp.GetInfo().GetValue()) 2090 } 2091 2092 if len(resp.GetInstances()) != expectCount { 2093 t.Fatalf("error: %d", len(resp.GetInstances())) 2094 } 2095 2096 return resp.GetInstances() 2097 } 2098 2099 // test对instance字段进行校验 2100 func TestCheckInstanceFieldLen(t *testing.T) { 2101 2102 discoverSuit := &DiscoverTestSuit{} 2103 if err := discoverSuit.Initialize(); err != nil { 2104 t.Fatal(err) 2105 } 2106 defer discoverSuit.Destroy() 2107 2108 _, serviceResp := discoverSuit.createCommonService(t, 800) 2109 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 2110 ins := &apiservice.Instance{ 2111 ServiceToken: serviceResp.GetToken(), 2112 Service: serviceResp.GetName(), 2113 Namespace: serviceResp.GetNamespace(), 2114 Host: utils.NewStringValue("127.0.0.1"), 2115 Protocol: utils.NewStringValue("grpc"), 2116 Version: utils.NewStringValue("1.0.1"), 2117 LogicSet: utils.NewStringValue("sz"), 2118 Metadata: map[string]string{}, 2119 } 2120 2121 t.Run("服务名超长", func(t *testing.T) { 2122 str := genSpecialStr(129) 2123 oldName := ins.Service 2124 ins.Service = utils.NewStringValue(str) 2125 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2126 ins.Service = oldName 2127 if resp.Code.Value != api.InvalidServiceName { 2128 t.Fatalf("%+v", resp) 2129 } 2130 }) 2131 t.Run("host超长", func(t *testing.T) { 2132 str := genSpecialStr(129) 2133 oldHost := ins.Host 2134 ins.Host = utils.NewStringValue(str) 2135 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2136 ins.Host = oldHost 2137 if resp.Code.Value != api.InvalidInstanceHost { 2138 t.Fatalf("%+v", resp) 2139 } 2140 }) 2141 t.Run("protocol超长", func(t *testing.T) { 2142 str := genSpecialStr(129) 2143 oldProtocol := ins.Protocol 2144 ins.Protocol = utils.NewStringValue(str) 2145 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2146 ins.Protocol = oldProtocol 2147 if resp.Code.Value != api.InvalidInstanceProtocol { 2148 t.Fatalf("%+v", resp) 2149 } 2150 }) 2151 t.Run("version超长", func(t *testing.T) { 2152 str := genSpecialStr(129) 2153 oldVersion := ins.Version 2154 ins.Version = utils.NewStringValue(str) 2155 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2156 ins.Version = oldVersion 2157 if resp.Code.Value != api.InvalidInstanceVersion { 2158 t.Fatalf("%+v", resp) 2159 } 2160 }) 2161 t.Run("logicSet超长", func(t *testing.T) { 2162 str := genSpecialStr(129) 2163 oldLogicSet := ins.LogicSet 2164 ins.LogicSet = utils.NewStringValue(str) 2165 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2166 ins.LogicSet = oldLogicSet 2167 if resp.Code.Value != api.InvalidInstanceLogicSet { 2168 t.Fatalf("%+v", resp) 2169 } 2170 }) 2171 t.Run("metadata超长", func(t *testing.T) { 2172 str := genSpecialStr(129) 2173 oldMetadata := ins.Metadata 2174 oldMetadata[str] = str 2175 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2176 ins.Metadata = make(map[string]string) 2177 if resp.Code.Value != api.InvalidMetadata { 2178 t.Fatalf("%+v", resp) 2179 } 2180 }) 2181 t.Run("port超长", func(t *testing.T) { 2182 oldPort := ins.Port 2183 ins.Port = utils.NewUInt32Value(70000) 2184 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2185 ins.Port = oldPort 2186 if resp.Code.Value != api.InvalidInstancePort { 2187 t.Fatalf("%+v", resp) 2188 } 2189 }) 2190 t.Run("weight超长", func(t *testing.T) { 2191 oldWeight := ins.Weight 2192 ins.Weight = utils.NewUInt32Value(70000) 2193 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2194 ins.Weight = oldWeight 2195 if resp.Code.Value != api.InvalidParameter { 2196 t.Fatalf("%+v", resp) 2197 } 2198 }) 2199 t.Run("检测字段为空指针", func(t *testing.T) { 2200 oldName := ins.Service 2201 ins.Service = nil 2202 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2203 ins.Service = oldName 2204 if resp.Code.Value != api.InvalidServiceName { 2205 t.Fatalf("%+v", resp) 2206 } 2207 }) 2208 t.Run("检测字段为空", func(t *testing.T) { 2209 oldName := ins.Service 2210 ins.Service = utils.NewStringValue("") 2211 resp := discoverSuit.DiscoverServer().CreateInstances(discoverSuit.DefaultCtx, []*apiservice.Instance{ins}) 2212 ins.Service = oldName 2213 if resp.Code.Value != api.InvalidServiceName { 2214 t.Fatalf("%+v", resp) 2215 } 2216 }) 2217 } 2218 2219 // test对instance入参进行校验 2220 func TestCheckInstanceParam(t *testing.T) { 2221 2222 discoverSuit := &DiscoverTestSuit{} 2223 if err := discoverSuit.Initialize(); err != nil { 2224 t.Fatal(err) 2225 } 2226 defer discoverSuit.Destroy() 2227 2228 // get instances接口限制(service+namespace)或者host必传,其它传参均拒绝服务 2229 _, serviceResp := discoverSuit.createCommonService(t, 1254) 2230 defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) 2231 2232 instanceReq, instanceResp := discoverSuit.createCommonInstance(t, serviceResp, 153) 2233 defer discoverSuit.cleanInstance(instanceResp.GetId().GetValue()) 2234 2235 // 强制先update一次,规避上一次的数据查询结果 2236 _ = discoverSuit.DiscoverServer().Cache().TestUpdate() 2237 2238 t.Run("都不传", func(t *testing.T) { 2239 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, make(map[string]string)) 2240 if resp.Code.Value != api.EmptyQueryParameter { 2241 t.Fatalf("%+v", resp) 2242 } 2243 }) 2244 t.Run("只传service", func(t *testing.T) { 2245 query := map[string]string{} 2246 query["service"] = "test" 2247 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2248 if resp.Code.Value != api.ExecuteSuccess { 2249 t.Fatalf("%+v", resp) 2250 } 2251 }) 2252 t.Run("只传namespace", func(t *testing.T) { 2253 query := map[string]string{} 2254 query["namespace"] = "test" 2255 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2256 if resp.Code.Value != api.ExecuteSuccess { 2257 t.Fatalf("%+v", resp) 2258 } 2259 }) 2260 t.Run("只传port", func(t *testing.T) { 2261 query := map[string]string{} 2262 query["port"] = "123" 2263 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2264 if resp.Code.Value == api.InvalidQueryInsParameter { 2265 t.Fatalf("%+v", resp) 2266 } 2267 }) 2268 t.Run("只传version", func(t *testing.T) { 2269 query := map[string]string{} 2270 query["version"] = "123" 2271 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2272 if resp.Code.Value == api.InvalidQueryInsParameter { 2273 t.Fatalf("%+v", resp) 2274 } 2275 }) 2276 t.Run("只传protocol", func(t *testing.T) { 2277 query := map[string]string{} 2278 query["protocol"] = "http" 2279 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2280 if resp.Code.Value == api.InvalidQueryInsParameter { 2281 t.Fatalf("%+v", resp) 2282 } 2283 }) 2284 t.Run("传service+port", func(t *testing.T) { 2285 query := map[string]string{} 2286 query["service"] = "test" 2287 query["port"] = "123" 2288 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2289 if resp.Code.Value != api.ExecuteSuccess { 2290 t.Fatalf("%+v", resp) 2291 } 2292 }) 2293 t.Run("传namespace+port", func(t *testing.T) { 2294 query := map[string]string{} 2295 query["namespace"] = "test" 2296 query["port"] = "123" 2297 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2298 if resp.Code.Value != api.ExecuteSuccess { 2299 t.Fatalf("%+v", resp) 2300 } 2301 }) 2302 t.Run("传service+namespace", func(t *testing.T) { 2303 query := map[string]string{} 2304 query["service"] = instanceReq.GetService().Value 2305 query["namespace"] = instanceReq.GetNamespace().Value 2306 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2307 if resp.Code.Value != api.ExecuteSuccess { 2308 t.Fatalf("%+v", resp) 2309 } 2310 }) 2311 t.Run("传service+namespace+host", func(t *testing.T) { 2312 query := map[string]string{} 2313 query["service"] = instanceReq.GetService().Value 2314 query["namespace"] = instanceReq.GetNamespace().Value 2315 query["host"] = instanceReq.GetHost().Value 2316 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2317 if resp.Code.Value != api.ExecuteSuccess { 2318 t.Fatalf("%+v", resp) 2319 } 2320 }) 2321 t.Run("传service+namespace+port", func(t *testing.T) { 2322 query := map[string]string{} 2323 query["service"] = instanceReq.GetService().Value 2324 query["namespace"] = instanceReq.GetNamespace().Value 2325 query["port"] = strconv.Itoa(int(instanceReq.GetPort().Value)) 2326 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2327 if resp.Code.Value != api.ExecuteSuccess { 2328 t.Fatalf("%+v", resp) 2329 } 2330 }) 2331 t.Run("传host", func(t *testing.T) { 2332 query := map[string]string{} 2333 query["host"] = instanceReq.GetHost().Value 2334 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2335 if resp.Code.Value != api.ExecuteSuccess { 2336 t.Fatalf("%+v", resp) 2337 } 2338 }) 2339 t.Run("传host+namespace", func(t *testing.T) { 2340 query := map[string]string{} 2341 query["host"] = instanceReq.GetHost().Value 2342 query["namespace"] = instanceReq.GetNamespace().Value 2343 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2344 if resp.Code.Value != api.ExecuteSuccess { 2345 t.Fatalf("%+v", resp) 2346 } 2347 }) 2348 t.Run("传host+port", func(t *testing.T) { 2349 query := map[string]string{} 2350 query["host"] = instanceReq.GetHost().Value 2351 query["port"] = strconv.Itoa(int(instanceReq.GetPort().Value)) 2352 resp := discoverSuit.DiscoverServer().GetInstances(discoverSuit.DefaultCtx, query) 2353 if resp.Code.Value != api.ExecuteSuccess { 2354 t.Fatalf("%+v", resp) 2355 } 2356 }) 2357 } 2358 2359 func Test_isEmptyLocation(t *testing.T) { 2360 type args struct { 2361 loc *apimodel.Location 2362 } 2363 tests := []struct { 2364 name string 2365 args args 2366 want bool 2367 }{ 2368 { 2369 name: "test-1", 2370 args: args{ 2371 loc: &apimodel.Location{}, 2372 }, 2373 want: true, 2374 }, 2375 { 2376 name: "test-2", 2377 args: args{ 2378 loc: &apimodel.Location{ 2379 Region: &wrapperspb.StringValue{ 2380 Value: "Region", 2381 }, 2382 Zone: &wrapperspb.StringValue{ 2383 Value: "Zone", 2384 }, 2385 Campus: &wrapperspb.StringValue{ 2386 Value: "", 2387 }, 2388 }, 2389 }, 2390 want: false, 2391 }, 2392 { 2393 name: "test-2", 2394 args: args{ 2395 loc: &apimodel.Location{ 2396 Region: &wrapperspb.StringValue{ 2397 Value: "", 2398 }, 2399 Zone: &wrapperspb.StringValue{ 2400 Value: "Zone", 2401 }, 2402 Campus: &wrapperspb.StringValue{ 2403 Value: "Campus", 2404 }, 2405 }, 2406 }, 2407 want: false, 2408 }, 2409 { 2410 name: "test-2", 2411 args: args{ 2412 loc: nil, 2413 }, 2414 want: true, 2415 }, 2416 { 2417 name: "test-2", 2418 args: args{ 2419 loc: &apimodel.Location{ 2420 Region: nil, 2421 Zone: &wrapperspb.StringValue{ 2422 Value: "Zone", 2423 }, 2424 Campus: nil, 2425 }, 2426 }, 2427 want: false, 2428 }, 2429 } 2430 for _, tt := range tests { 2431 t.Run(tt.name, func(t *testing.T) { 2432 if got := service.TestIsEmptyLocation(tt.args.loc); got != tt.want { 2433 t.Errorf("isEmptyLocation() = %v, want %v", got, tt.want) 2434 } 2435 }) 2436 } 2437 } 2438 2439 func Test_HealthCheckInstanceMetadata(t *testing.T) { 2440 discoverSuit := &DiscoverTestSuit{} 2441 if err := discoverSuit.Initialize(); err != nil { 2442 t.Fatal(err) 2443 } 2444 defer discoverSuit.Destroy() 2445 2446 _, ins1 := discoverSuit.createCommonInstance(t, &apiservice.Service{ 2447 Namespace: wrapperspb.String("default"), 2448 Name: wrapperspb.String("mock_service"), 2449 }, 1) 2450 defer func() { 2451 discoverSuit.cleanInstance(ins1.GetId().GetValue()) 2452 }() 2453 2454 t.Run("toUnhealth", func(t *testing.T) { 2455 lastBeatTime := time.Now().Unix() 2456 future := discoverSuit.BatchController().AsyncHeartbeat(ins1, false, lastBeatTime) 2457 err := future.Wait() 2458 assert.NoError(t, err) 2459 2460 discoverSuit.DiscoverServer().Cache().TestUpdate() 2461 ins1Cache := discoverSuit.DiscoverServer().Cache().Instance().GetInstance(ins1.GetId().GetValue()) 2462 assert.NotNil(t, ins1Cache, "ins1Cache is nil") 2463 val, ok := ins1Cache.Metadata()[model.MetadataInstanceLastHeartbeatTime] 2464 assert.Truef(t, ok, "%s not exist", model.MetadataInstanceLastHeartbeatTime) 2465 assert.Equal(t, fmt.Sprintf("%d", lastBeatTime), val) 2466 }) 2467 2468 t.Run("toHealth", func(t *testing.T) { 2469 lastBeatTime := time.Now().Unix() 2470 future := discoverSuit.BatchController().AsyncHeartbeat(ins1, true, lastBeatTime) 2471 err := future.Wait() 2472 assert.NoError(t, err) 2473 2474 discoverSuit.DiscoverServer().Cache().TestUpdate() 2475 ins1Cache := discoverSuit.DiscoverServer().Cache().Instance().GetInstance(ins1.GetId().GetValue()) 2476 assert.NotNil(t, ins1Cache, "ins1Cache is nil") 2477 _, ok := ins1Cache.Metadata()[model.MetadataInstanceLastHeartbeatTime] 2478 assert.Falsef(t, ok, "%s exist", model.MetadataInstanceLastHeartbeatTime) 2479 }) 2480 } 2481 2482 func Test_OperateInstanceMetadata(t *testing.T) { 2483 discoverSuit := &DiscoverTestSuit{} 2484 if err := discoverSuit.Initialize(); err != nil { 2485 t.Fatal(err) 2486 } 2487 defer discoverSuit.Destroy() 2488 2489 _, ins1 := discoverSuit.createCommonInstance(t, &apiservice.Service{ 2490 Namespace: wrapperspb.String("default"), 2491 Name: wrapperspb.String("mock_service"), 2492 }, 1) 2493 defer func() { 2494 discoverSuit.cleanInstance(ins1.GetId().GetValue()) 2495 }() 2496 _, ins2 := discoverSuit.createCommonInstance(t, &apiservice.Service{ 2497 Namespace: wrapperspb.String("default"), 2498 Name: wrapperspb.String("mock_service"), 2499 }, 2) 2500 defer func() { 2501 discoverSuit.cleanInstance(ins2.GetId().GetValue()) 2502 }() 2503 2504 t.Run("append-instance-metadata", func(t *testing.T) { 2505 err := discoverSuit.Storage.BatchAppendInstanceMetadata([]*store.InstanceMetadataRequest{ 2506 { 2507 InstanceID: ins1.GetId().GetValue(), 2508 Metadata: map[string]string{ 2509 "ins1_mock_key": "ins1_mock_value", 2510 }, 2511 }, 2512 { 2513 InstanceID: ins2.GetId().GetValue(), 2514 Metadata: map[string]string{ 2515 "ins2_mock_key": "ins2_mock_value", 2516 }, 2517 }, 2518 }) 2519 assert.NoError(t, err) 2520 2521 discoverSuit.DiscoverServer().Cache().TestUpdate() 2522 ins1Cache := discoverSuit.DiscoverServer().Cache().Instance().GetInstance(ins1.GetId().GetValue()) 2523 assert.NotNil(t, ins1Cache, "ins1Cache is nil") 2524 val, ok := ins1Cache.Metadata()["ins1_mock_key"] 2525 assert.True(t, ok, "ins1_mock_key not exist") 2526 assert.Equal(t, "ins1_mock_value", val) 2527 ins2Cache := discoverSuit.DiscoverServer().Cache().Instance().GetInstance(ins2.GetId().GetValue()) 2528 assert.NotNil(t, ins2Cache, "ins2Cache is nil") 2529 val, ok = ins2Cache.Metadata()["ins2_mock_key"] 2530 assert.True(t, ok, "ins2_mock_key not exist") 2531 assert.Equal(t, "ins2_mock_value", val) 2532 }) 2533 2534 t.Run("notinstance-append-instance-metadata", func(t *testing.T) { 2535 err := discoverSuit.Storage.BatchAppendInstanceMetadata([]*store.InstanceMetadataRequest{ 2536 { 2537 InstanceID: utils.NewUUID(), 2538 Metadata: map[string]string{ 2539 "ins1_mock_key": "ins1_mock_value", 2540 }, 2541 }, 2542 }) 2543 assert.NoError(t, err) 2544 }) 2545 2546 t.Run("remove-instance-metadata", func(t *testing.T) { 2547 err := discoverSuit.Storage.BatchRemoveInstanceMetadata([]*store.InstanceMetadataRequest{ 2548 { 2549 InstanceID: ins1.GetId().GetValue(), 2550 Keys: []string{"ins1_mock_key"}, 2551 }, 2552 { 2553 InstanceID: ins2.GetId().GetValue(), 2554 Keys: []string{"ins2_mock_key"}, 2555 }, 2556 }) 2557 assert.NoError(t, err) 2558 2559 discoverSuit.DiscoverServer().Cache().TestUpdate() 2560 ins1Cache := discoverSuit.DiscoverServer().Cache().Instance().GetInstance(ins1.GetId().GetValue()) 2561 assert.NotNil(t, ins1Cache, "ins1Cache is nil") 2562 _, ok := ins1Cache.Metadata()["ins1_mock_key"] 2563 assert.False(t, ok, "ins1_mock_key exist") 2564 ins2Cache := discoverSuit.DiscoverServer().Cache().Instance().GetInstance(ins2.GetId().GetValue()) 2565 assert.NotNil(t, ins2Cache, "ins2Cache is nil") 2566 _, ok = ins2Cache.Metadata()["ins2_mock_key"] 2567 assert.False(t, ok, "ins2_mock_key exist") 2568 }) 2569 2570 t.Run("notinstance-remove-instance-metadata", func(t *testing.T) { 2571 err := discoverSuit.Storage.BatchRemoveInstanceMetadata([]*store.InstanceMetadataRequest{ 2572 { 2573 InstanceID: utils.NewUUID(), 2574 Keys: []string{"ins1_mock_key"}, 2575 }, 2576 }) 2577 assert.NoError(t, err) 2578 }) 2579 2580 }