github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/znet/timeout/timeout_test.go (about) 1 package timeout 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "strings" 7 "sync" 8 "testing" 9 "time" 10 11 "github.com/sohaha/zlsgo" 12 "github.com/sohaha/zlsgo/znet" 13 ) 14 15 func TestWebTimeout(tt *testing.T) { 16 t := zlsgo.NewTest(tt) 17 r := newServer() 18 body := "" 19 w1 := newRequest(r, "GET", "/timeout_1", func(c *znet.Context) { 20 tt.Log("timeout_1") 21 c.String(201, "timeout_1") 22 }, New(2*time.Second, func(c *znet.Context) { 23 tt.Log("timeout_1 Second") 24 }), func(c *znet.Context) { 25 c.Next() 26 }) 27 body = w1.Body.String() 28 tt.Log("code:", w1.Code) 29 tt.Log("body:", body) 30 t.Equal(201, w1.Code) 31 t.Equal("timeout_1", body) 32 33 w2 := newRequest(r, "GET", "/timeout_2", func(c *znet.Context) { 34 time.Sleep(2 * time.Second) 35 t.Log("run 2") 36 c.String(200, "timeout_2") 37 }, New(1*time.Second)) 38 t.Equal(504, w2.Code) 39 t.Equal("", w2.Body.String()) 40 41 w3 := newRequest(r, "GET", "/timeout_3", func(c *znet.Context) { 42 time.Sleep(2 * time.Second) 43 c.String(200, "timeout_3") 44 }, New(1*time.Second, func(c *znet.Context) { 45 tt.Log("3 timeout") 46 c.String(210, "is timeout") 47 })) 48 t.Equal(210, w3.Code) 49 t.Equal("is timeout", w3.Body.String()) 50 tt.Log(w3.Body.String()) 51 52 w4 := newRequest(r, "GET", "/timeout_4", func(c *znet.Context) { 53 time.Sleep(3 * time.Second) 54 c.String(200, "timeout_2") 55 }, New(1*time.Second, func(c *znet.Context) { 56 c.Next() 57 c.String(211, "ok timeout_4") 58 c.Abort() 59 })) 60 t.Equal(211, w4.Code) 61 t.Equal("ok timeout_4", w4.Body.String()) 62 63 w5 := newRequest(r, "GET", "/timeout_5", func(c *znet.Context) { 64 c.String(200, "timeout_5") 65 }, New(1*time.Second, func(c *znet.Context) { 66 c.String(211, "ok") 67 })) 68 t.Equal(200, w5.Code) 69 t.Equal("timeout_5", w5.Body.String()) 70 } 71 72 var ( 73 one sync.Once 74 Engine *znet.Engine 75 ) 76 77 func newServer() *znet.Engine { 78 one.Do(func() { 79 Engine = znet.New() 80 Engine.SetMode(znet.DebugMode) 81 }) 82 return Engine 83 } 84 85 func newRequest(r *znet.Engine, method string, path string, handler ...znet.Handler) *httptest.ResponseRecorder { 86 method = strings.ToUpper(method) 87 if len(handler) > 0 { 88 firstHandler := handler[0] 89 handlers := handler[1:] 90 switch method { 91 case "GET": 92 r.GET(path, firstHandler, handlers...) 93 case "POST": 94 r.POST(path, firstHandler, handlers...) 95 } 96 } 97 w := httptest.NewRecorder() 98 req, _ := http.NewRequest(method, path, nil) 99 r.ServeHTTP(w, req) 100 return w 101 }