diff --git a/src/transport/raw/tests/TestTCP.cpp b/src/transport/raw/tests/TestTCP.cpp index 787a1ed250c9fb..990e71867fb93e 100644 --- a/src/transport/raw/tests/TestTCP.cpp +++ b/src/transport/raw/tests/TestTCP.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -107,6 +108,27 @@ class MockTransportMgrDelegate : public chip::TransportMgrDelegate void InitializeMessageTest(TCPImpl & tcp, const IPAddress & addr) { CHIP_ERROR err = tcp.Init(Transport::TcpListenParameters(mContext.GetTCPEndPointManager()).SetAddressType(addr.Type())); + + // retry a few times in case the port is somehow in use. + // this is a WORKAROUND for flaky testing if we run tests very fast after each other. + // in that case, a port could be in a WAIT state. + // + // What may be happening: + // - We call InitializeMessageTest several times in this unit test + // - closing sockets takes a while (FIN-wait or similar) + // - trying InitializeMessageTest to take the same port right after may fail + // + // The tests may be run with a 0 port (to self select an active port) however I have not + // validated that this works and we need a followup for it + // + // TODO: stop using fixed ports. + for (int i = 0; (i < 50) && (err != CHIP_NO_ERROR); i++) + { + ChipLogProgress(NotSpecified, "RETRYING tcp initialization"); + chip::test_utils::SleepMillis(100); + err = tcp.Init(Transport::TcpListenParameters(mContext.GetTCPEndPointManager()).SetAddressType(addr.Type())); + } + NL_TEST_ASSERT(mSuite, err == CHIP_NO_ERROR); mTransportMgrBase.SetSessionManager(this);