github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/cache/cache_test.go (about)

     1  package cache
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/tickoalcantara12/micro/v3/service/context/metadata"
     9  )
    10  
    11  func TestCache(t *testing.T) {
    12  	ctx := context.TODO()
    13  	req := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar"}
    14  
    15  	t.Run("CacheMiss", func(t *testing.T) {
    16  		if _, ok := New().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 := New()
    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  
    38  	req1 := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar"}
    39  	req2 := &testRequest{service: "go.micro.service.foo", method: "Foo.Baz"}
    40  	req3 := &testRequest{service: "go.micro.service.foo", method: "Foo.Bar", body: "customquery"}
    41  
    42  	t.Run("IdenticalRequests", func(t *testing.T) {
    43  		key1 := key(ctx, req1)
    44  		key2 := key(ctx, req1)
    45  		if key1 != key2 {
    46  			t.Errorf("Expected the keys to match for identical requests and context")
    47  		}
    48  	})
    49  
    50  	t.Run("DifferentRequestEndpoints", func(t *testing.T) {
    51  		key1 := key(ctx, req1)
    52  		key2 := key(ctx, req2)
    53  
    54  		if key1 == key2 {
    55  			t.Errorf("Expected the keys to differ for different request endpoints")
    56  		}
    57  	})
    58  
    59  	t.Run("DifferentRequestBody", func(t *testing.T) {
    60  		key1 := key(ctx, req2)
    61  		key2 := key(ctx, req3)
    62  
    63  		if key1 == key2 {
    64  			t.Errorf("Expected the keys to differ for different request bodies")
    65  		}
    66  	})
    67  
    68  	t.Run("DifferentMetadata", func(t *testing.T) {
    69  		mdCtx := metadata.Set(context.TODO(), "Micro-Namespace", "bar")
    70  		key1 := key(mdCtx, req1)
    71  		key2 := key(ctx, req1)
    72  
    73  		if key1 == key2 {
    74  			t.Errorf("Expected the keys to differ for different metadata")
    75  		}
    76  	})
    77  }