github.com/ezoic/ws@v1.0.4-0.20220713205711-5c1d69e074c5/wsutil/upgrader_test.go (about) 1 package wsutil 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "net/url" 8 "testing" 9 10 "github.com/ezoic/ws" 11 ) 12 13 func TestDebugUpgrader(t *testing.T) { 14 for _, test := range []struct { 15 name string 16 upgrader ws.Upgrader 17 req []byte 18 }{ 19 { 20 // Base case. 21 }, 22 { 23 req: []byte("" + 24 "GET /test HTTP/1.1\r\n" + 25 "Host: example.org\r\n" + 26 "\r\n", 27 ), 28 }, 29 { 30 req: []byte("PUT /fail HTTP/1.1\r\n\r\n"), 31 }, 32 { 33 req: []byte("GET /fail HTTP/1.0\r\n\r\n"), 34 }, 35 } { 36 t.Run(test.name, func(t *testing.T) { 37 var ( 38 reqBuf bytes.Buffer 39 resBuf bytes.Buffer 40 41 expReq, expRes []byte 42 actReq, actRes []byte 43 ) 44 if test.req == nil { 45 var dialer ws.Dialer 46 dialer.Upgrade(struct { 47 io.Reader 48 io.Writer 49 }{ 50 new(falseReader), 51 &reqBuf, 52 }, makeURL("wss://example.org")) 53 } else { 54 reqBuf.Write(test.req) 55 } 56 57 // Need to save bytes before they will be read by Upgrade(). 58 expReq = reqBuf.Bytes() 59 60 du := DebugUpgrader{ 61 Upgrader: test.upgrader, 62 OnRequest: func(p []byte) { actReq = p }, 63 OnResponse: func(p []byte) { actRes = p }, 64 } 65 du.Upgrade(struct { 66 io.Reader 67 io.Writer 68 }{ 69 &reqBuf, 70 &resBuf, 71 }) 72 73 expRes = resBuf.Bytes() 74 75 if !bytes.Equal(actReq, expReq) { 76 t.Errorf( 77 "unexpected request bytes:\nact:\n%s\nwant:\n%s\n", 78 actReq, expReq, 79 ) 80 } 81 if !bytes.Equal(actRes, expRes) { 82 t.Errorf( 83 "unexpected response bytes:\nact:\n%s\nwant:\n%s\n", 84 actRes, expRes, 85 ) 86 } 87 }) 88 } 89 } 90 91 type falseReader struct{} 92 93 func (f falseReader) Read(p []byte) (int, error) { 94 return 0, fmt.Errorf("falsy read") 95 } 96 97 func makeURL(s string) *url.URL { 98 u, err := url.Parse(s) 99 if err != nil { 100 panic(err) 101 } 102 return u 103 }