github.com/sunvim/utils@v0.1.0/netpoll/handler_test.go (about) 1 // Copyright (c) 2020 Meng Huang (mhboy@outlook.com) 2 // This package is licensed under a MIT license that can be found in the LICENSE file. 3 4 package netpoll 5 6 import ( 7 "errors" 8 "net" 9 "testing" 10 "time" 11 12 "github.com/oxtoacart/bpool" 13 ) 14 15 func TestNewHandler(t *testing.T) { 16 var handler = NewHandler(func(conn net.Conn) (Context, error) { 17 if n, err := conn.Write([]byte("")); err != nil { 18 t.Error(err) 19 } else if n != 0 { 20 t.Error(n) 21 } 22 if n, err := conn.Write([]byte("12345678")); err == nil { 23 t.Error("Unexpected") 24 } else if n != 0 { 25 t.Error(n) 26 } 27 if n, err := conn.Read([]byte("")); err != nil { 28 t.Error(err) 29 } else if n != 0 { 30 t.Error(n) 31 } 32 conn.LocalAddr() 33 conn.RemoteAddr() 34 conn.SetDeadline(time.Now().Add(time.Second)) 35 conn.SetReadDeadline(time.Now().Add(time.Second)) 36 conn.SetWriteDeadline(time.Now().Add(time.Second)) 37 conn.Close() 38 conn.Close() 39 return conn, nil 40 }, func(context Context) error { 41 return nil 42 }) 43 ctx, err := handler.Upgrade(&conn{}) 44 if err != nil { 45 t.Error(err) 46 } 47 err = handler.Serve(ctx) 48 if err != nil { 49 t.Error(err) 50 } 51 } 52 53 func TestConnHandler(t *testing.T) { 54 var handler = &ConnHandler{} 55 ctx, err := handler.Upgrade(&conn{}) 56 if err != ErrUpgradeFunc { 57 t.Error(err) 58 } 59 err = handler.Serve(ctx) 60 if err != ErrServeFunc { 61 t.Error(err) 62 } 63 handler.SetUpgrade(func(conn net.Conn) (Context, error) { 64 return conn, nil 65 }) 66 handler.SetServe(func(context Context) error { 67 return nil 68 }) 69 } 70 71 func TestDataHandler(t *testing.T) { 72 var handler = &DataHandler{ 73 Pool: bpool.NewBytePool(1024, 12*1024), 74 } 75 _, err := handler.Upgrade(&conn{}) 76 if err != ErrHandlerFunc { 77 t.Error(err) 78 } 79 handler.HandlerFunc = func(req []byte) (res []byte) { 80 return 81 } 82 var fakeErr = errors.New("fake error") 83 handler.SetUpgrade(func(conn net.Conn) (net.Conn, error) { 84 return nil, fakeErr 85 }) 86 _, err = handler.Upgrade(&conn{}) 87 if err != fakeErr { 88 t.Error(err) 89 } 90 handler.SetUpgrade(func(conn net.Conn) (net.Conn, error) { 91 return conn, nil 92 }) 93 _, err = handler.Upgrade(&conn{}) 94 if err != nil { 95 t.Error(err) 96 } 97 }