github.com/micro/go-micro/v2@v2.9.1/client/cache_test.go (about)

     1  package client
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/micro/go-micro/v2/metadata"
     9  )
    10  
    11  func TestCache(t *testing.T) {
    12  	ctx := context.TODO()
    13  	req := NewRequest("go.micro.service.foo", "Foo.Bar", nil)
    14  
    15  	t.Run("CacheMiss", func(t *testing.T) {
    16  		if _, ok := NewCache().Get(ctx, &req); ok {
    17  			t.Errorf("Expected to get no result from Get")
    18  		}
    19  	})
    20  
    21  	t.Run("CacheHit", func(t *testing.T) {
    22  		c := NewCache()
    23  
    24  		rsp := "theresponse"
    25  		c.Set(ctx, &req, rsp, time.Minute)
    26  
    27  		if res, ok := c.Get(ctx, &req); !ok {
    28  			t.Errorf("Expected a result, got nothing")
    29  		} else if res != rsp {
    30  			t.Errorf("Expected '%v' result, got '%v'", rsp, res)
    31  		}
    32  	})
    33  }
    34  
    35  func TestCacheKey(t *testing.T) {
    36  	ctx := context.TODO()
    37  	req1 := NewRequest("go.micro.service.foo", "Foo.Bar", nil)
    38  	req2 := NewRequest("go.micro.service.foo", "Foo.Baz", nil)
    39  	req3 := NewRequest("go.micro.service.foo", "Foo.Baz", "customquery")
    40  
    41  	t.Run("IdenticalRequests", func(t *testing.T) {
    42  		key1 := key(ctx, &req1)
    43  		key2 := key(ctx, &req1)
    44  		if key1 != key2 {
    45  			t.Errorf("Expected the keys to match for identical requests and context")
    46  		}
    47  	})
    48  
    49  	t.Run("DifferentRequestEndpoints", func(t *testing.T) {
    50  		key1 := key(ctx, &req1)
    51  		key2 := key(ctx, &req2)
    52  
    53  		if key1 == key2 {
    54  			t.Errorf("Expected the keys to differ for different request endpoints")
    55  		}
    56  	})
    57  
    58  	t.Run("DifferentRequestBody", func(t *testing.T) {
    59  		key1 := key(ctx, &req2)
    60  		key2 := key(ctx, &req3)
    61  
    62  		if key1 == key2 {
    63  			t.Errorf("Expected the keys to differ for different request bodies")
    64  		}
    65  	})
    66  
    67  	t.Run("DifferentMetadata", func(t *testing.T) {
    68  		mdCtx := metadata.Set(context.TODO(), "Micro-Namespace", "bar")
    69  		key1 := key(mdCtx, &req1)
    70  		key2 := key(ctx, &req1)
    71  
    72  		if key1 == key2 {
    73  			t.Errorf("Expected the keys to differ for different metadata")
    74  		}
    75  	})
    76  }