github.com/MetalBlockchain/metalgo@v1.11.9/network/dialer/dialer_test.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package dialer 5 6 import ( 7 "context" 8 "net" 9 "net/netip" 10 "testing" 11 "time" 12 13 "github.com/stretchr/testify/require" 14 15 "github.com/MetalBlockchain/metalgo/utils/logging" 16 ) 17 18 // Test that canceling a context passed into Dial results 19 // in giving up trying to connect 20 func TestDialerCancelDial(t *testing.T) { 21 require := require.New(t) 22 23 listenAddrPort := netip.AddrPortFrom( 24 netip.AddrFrom4([4]byte{127, 0, 0, 1}), 25 0, 26 ) 27 l, err := net.Listen("tcp", listenAddrPort.String()) 28 require.NoError(err) 29 30 done := make(chan struct{}) 31 go func() { 32 for { 33 // Continuously accept connections from myself 34 _, err := l.Accept() 35 if err != nil { 36 // Distinguish between an error that occurred because 37 // the test is over from actual errors 38 select { 39 case <-done: 40 return 41 default: 42 require.FailNow(err.Error()) 43 } 44 } 45 } 46 }() 47 48 listenedAddrPort, err := netip.ParseAddrPort(l.Addr().String()) 49 require.NoError(err) 50 51 // Create a dialer 52 dialer := NewDialer( 53 "tcp", 54 Config{ 55 ThrottleRps: 10, 56 ConnectionTimeout: 30 * time.Second, 57 }, 58 logging.NoLog{}, 59 ) 60 61 // Make an outgoing connection with a cancelled context 62 ctx, cancel := context.WithCancel(context.Background()) 63 cancel() 64 _, err = dialer.Dial(ctx, listenedAddrPort) 65 require.ErrorIs(err, context.Canceled) 66 67 // Make an outgoing connection with a non-cancelled context 68 conn, err := dialer.Dial(context.Background(), listenedAddrPort) 69 require.NoError(err) 70 _ = conn.Close() 71 72 close(done) // stop listener goroutine 73 _ = l.Close() 74 }