github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/znet/cache/cache_test.go (about)

     1  package cache_test
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/sohaha/zlsgo"
    10  	"github.com/sohaha/zlsgo/znet"
    11  	"github.com/sohaha/zlsgo/znet/cache"
    12  	"github.com/sohaha/zlsgo/zstring"
    13  	"github.com/sohaha/zlsgo/zsync"
    14  )
    15  
    16  var (
    17  	r *znet.Engine
    18  )
    19  
    20  func init() {
    21  	r = znet.New()
    22  	r.SetMode(znet.ProdMode)
    23  
    24  	r.GET("/cache", func(c *znet.Context) {
    25  		c.String(200, zstring.Rand(10))
    26  	}, cache.New(func(conf *cache.Config) {
    27  		conf.Expiration = 10 * time.Second
    28  		conf.Custom = func(c *znet.Context) (key string, expiration time.Duration) {
    29  			return cache.QueryKey(c), 0
    30  		}
    31  	}))
    32  }
    33  
    34  func qvalue() string {
    35  	q := map[string]string{
    36  		"b": "2",
    37  		"a": "1",
    38  		"c": "3",
    39  	}
    40  
    41  	val := ""
    42  	for k, v := range q {
    43  		val += k + "=" + v + "&"
    44  	}
    45  	return val
    46  }
    47  
    48  func TestCache(t *testing.T) {
    49  	tt := zlsgo.NewTest(t)
    50  
    51  	w := httptest.NewRecorder()
    52  
    53  	req, _ := http.NewRequest("GET", "/cache?"+qvalue(), nil)
    54  	r.ServeHTTP(w, req)
    55  	str := w.Body
    56  
    57  	var wg zsync.WaitGroup
    58  	for i := 0; i < 5; i++ {
    59  		wg.Go(func() {
    60  			w := httptest.NewRecorder()
    61  			url := "/cache?" + qvalue()
    62  			req, _ := http.NewRequest("GET", url, nil)
    63  			r.ServeHTTP(w, req)
    64  			tt.Equal(200, w.Code)
    65  			tt.Equal(10, w.Body.Len())
    66  			tt.Equal(str, w.Body)
    67  		})
    68  	}
    69  	_ = wg.Wait()
    70  }