golang.org/x/net@v0.25.1-0.20240516223405-c87a5b62e243/websocket/dial_test.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package websocket 6 7 import ( 8 "context" 9 "crypto/tls" 10 "errors" 11 "fmt" 12 "log" 13 "net" 14 "net/http" 15 "net/http/httptest" 16 "testing" 17 "time" 18 ) 19 20 // This test depend on Go 1.3+ because in earlier versions the Dialer won't be 21 // used in TLS connections and a timeout won't be triggered. 22 func TestDialConfigTLSWithDialer(t *testing.T) { 23 tlsServer := httptest.NewTLSServer(nil) 24 tlsServerAddr := tlsServer.Listener.Addr().String() 25 log.Print("Test TLS WebSocket server listening on ", tlsServerAddr) 26 defer tlsServer.Close() 27 config, _ := NewConfig(fmt.Sprintf("wss://%s/echo", tlsServerAddr), "http://localhost") 28 config.Dialer = &net.Dialer{ 29 Deadline: time.Now().Add(-time.Minute), 30 } 31 config.TlsConfig = &tls.Config{ 32 InsecureSkipVerify: true, 33 } 34 _, err := DialConfig(config) 35 dialerr, ok := err.(*DialError) 36 if !ok { 37 t.Fatalf("DialError expected, got %#v", err) 38 } 39 neterr, ok := dialerr.Err.(*net.OpError) 40 if !ok { 41 t.Fatalf("net.OpError error expected, got %#v", dialerr.Err) 42 } 43 if !neterr.Timeout() { 44 t.Fatalf("expected timeout error, got %#v", neterr) 45 } 46 } 47 48 func TestDialConfigTLSWithTimeouts(t *testing.T) { 49 t.Parallel() 50 51 finishedRequest := make(chan bool) 52 53 // Context for cancellation 54 ctx, cancel := context.WithCancel(context.Background()) 55 56 // This is a TLS server that blocks each request indefinitely (and cancels the context) 57 tlsServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 58 cancel() 59 <-finishedRequest 60 })) 61 62 tlsServerAddr := tlsServer.Listener.Addr().String() 63 log.Print("Test TLS WebSocket server listening on ", tlsServerAddr) 64 defer tlsServer.Close() 65 defer close(finishedRequest) 66 67 config, _ := NewConfig(fmt.Sprintf("wss://%s/echo", tlsServerAddr), "http://localhost") 68 config.TlsConfig = &tls.Config{ 69 InsecureSkipVerify: true, 70 } 71 72 _, err := config.DialContext(ctx) 73 dialerr, ok := err.(*DialError) 74 if !ok { 75 t.Fatalf("DialError expected, got %#v", err) 76 } 77 if !errors.Is(dialerr.Err, context.Canceled) { 78 t.Fatalf("context.Canceled error expected, got %#v", dialerr.Err) 79 } 80 }