github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/znet/gzip/gzip_test.go (about) 1 package gzip_test 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "sync" 7 "testing" 8 9 "github.com/sohaha/zlsgo" 10 "github.com/sohaha/zlsgo/znet" 11 "github.com/sohaha/zlsgo/znet/gzip" 12 "github.com/sohaha/zlsgo/zstring" 13 ) 14 15 const host = "127.0.0.1" 16 17 var ( 18 r *znet.Engine 19 size = 10000 20 ) 21 22 func init() { 23 r = znet.New() 24 r.SetMode(znet.ProdMode) 25 26 r.GET("/gzip", func(c *znet.Context) { 27 c.String(200, zstring.Rand(size, "abc")) 28 }, gzip.Default()) 29 30 } 31 32 func TestGzip(t *testing.T) { 33 tt := zlsgo.NewTest(t) 34 35 go func() { 36 w := httptest.NewRecorder() 37 req, _ := http.NewRequest("GET", "/gzip", nil) 38 r.ServeHTTP(w, req) 39 tt.Equal(200, w.Code) 40 tt.Equal(size, w.Body.Len()) 41 }() 42 43 var g sync.WaitGroup 44 for i := 0; i < 1000; i++ { 45 g.Add(1) 46 go func() { 47 w := httptest.NewRecorder() 48 req, _ := http.NewRequest("GET", "/gzip", nil) 49 req.Header.Add("Accept-Encoding", "gzip") 50 req.Host = host 51 r.ServeHTTP(w, req) 52 tt.Equal(200, w.Code) 53 tt.EqualTrue(w.Body.Len() > 100) 54 tt.EqualTrue(w.Body.Len() < size) 55 g.Done() 56 }() 57 } 58 g.Wait() 59 } 60 61 func BenchmarkGzipDoNotUse(b *testing.B) { 62 for i := 0; i < b.N; i++ { 63 w := httptest.NewRecorder() 64 req, _ := http.NewRequest("GET", "/gzip", nil) 65 req.Header.Add("Accept-Encoding1", "not-gzip") 66 r.ServeHTTP(w, req) 67 if 200 != w.Code || size != w.Body.Len() { 68 b.Fail() 69 } 70 } 71 } 72 73 func BenchmarkGzipUse(b *testing.B) { 74 for i := 0; i < b.N; i++ { 75 w := httptest.NewRecorder() 76 req, _ := http.NewRequest("GET", "/gzip", nil) 77 req.Header.Add("Accept-Encoding", "gzip") 78 req.Host = host 79 r.ServeHTTP(w, req) 80 if 200 != w.Code || size <= w.Body.Len() || 100 >= w.Body.Len() { 81 b.Fail() 82 } 83 } 84 }