From 4514a2c16bfb137d700aa6ed89e7657b0d60c169 Mon Sep 17 00:00:00 2001 From: Marco Munizaga Date: Tue, 12 Nov 2024 15:22:02 -0800 Subject: [PATCH] add test --- p2p/transport/tcpreuse/demultiplex.go | 5 +++-- p2p/transport/tcpreuse/listener_test.go | 27 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/p2p/transport/tcpreuse/demultiplex.go b/p2p/transport/tcpreuse/demultiplex.go index 703e79ef9e..723f12519c 100644 --- a/p2p/transport/tcpreuse/demultiplex.go +++ b/p2p/transport/tcpreuse/demultiplex.go @@ -9,8 +9,9 @@ import ( manet "github.com/multiformats/go-multiaddr/net" ) -// This is readiung the first 3 bytes of the packet. It should be instant. -const identifyConnTimeout = 1 * time.Second +// This is reading the first 3 bytes of the packet. It should be instant. +// A var so we can change it in tests. +var identifyConnTimeout = 1 * time.Second type DemultiplexedConnType int diff --git a/p2p/transport/tcpreuse/listener_test.go b/p2p/transport/tcpreuse/listener_test.go index bdb030a676..b5dc49f2c1 100644 --- a/p2p/transport/tcpreuse/listener_test.go +++ b/p2p/transport/tcpreuse/listener_test.go @@ -447,3 +447,30 @@ func TestListenerClose(t *testing.T) { testClose(listenAddr) } } + +func setDeferReset[T any](t testing.TB, ptr *T, val T) { + t.Helper() + orig := *ptr + *ptr = val + t.Cleanup(func() { *ptr = orig }) +} + +// TestHitTimeout asserts that we don't panic in case we fail to peek at the connection. +func TestHitTimeout(t *testing.T) { + setDeferReset(t, &identifyConnTimeout, 100*time.Millisecond) + // listen on port 0 + cm := NewConnMgr(false, nil, nil) + + listenAddr := ma.StringCast("/ip4/127.0.0.1/tcp/0") + ml, err := cm.DemultiplexedListen(listenAddr, DemultiplexedConnType_MultistreamSelect) + require.NoError(t, err) + defer ml.Close() + + tcpConn, err := net.Dial(ml.Addr().Network(), ml.Addr().String()) + require.NoError(t, err) + + // Stall tcp conn for over the timeout. + time.Sleep(identifyConnTimeout + 100*time.Millisecond) + + tcpConn.Close() +}