github.com/cloudwego/hertz@v0.9.3/pkg/app/middlewares/client/sd/discovery_test.go (about)

     1  /*
     2   * Copyright 2022 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package sd
    18  
    19  import (
    20  	"context"
    21  	"testing"
    22  
    23  	"github.com/cloudwego/hertz/pkg/app/client/discovery"
    24  	"github.com/cloudwego/hertz/pkg/common/config"
    25  	"github.com/cloudwego/hertz/pkg/common/test/assert"
    26  	"github.com/cloudwego/hertz/pkg/protocol"
    27  )
    28  
    29  func TestDiscovery(t *testing.T) {
    30  	inss := []discovery.Instance{
    31  		discovery.NewInstance("tcp", "127.0.0.1:8888", 10, nil),
    32  		discovery.NewInstance("tcp", "127.0.0.1:8889", 10, nil),
    33  	}
    34  	r := &discovery.SynthesizedResolver{
    35  		TargetFunc: func(ctx context.Context, target *discovery.TargetInfo) string {
    36  			return target.Host
    37  		},
    38  		ResolveFunc: func(ctx context.Context, key string) (discovery.Result, error) {
    39  			return discovery.Result{CacheKey: "svc1", Instances: inss}, nil
    40  		},
    41  		NameFunc: func() string { return t.Name() },
    42  	}
    43  
    44  	mw := Discovery(r)
    45  	checkMdw := func(ctx context.Context, req *protocol.Request, resp *protocol.Response) (err error) {
    46  		t.Log(string(req.Host()))
    47  		assert.Assert(t, string(req.Host()) == "127.0.0.1:8888" || string(req.Host()) == "127.0.0.1:8889")
    48  		return nil
    49  	}
    50  	for i := 0; i < 10; i++ {
    51  		req := &protocol.Request{}
    52  		resp := &protocol.Response{}
    53  		req.Options().Apply([]config.RequestOption{config.WithSD(true)})
    54  		req.SetRequestURI("http://service_name")
    55  		_ = mw(checkMdw)(context.Background(), req, resp)
    56  	}
    57  }