From: Marek Safar Date: Tue, 19 Sep 2017 06:25:45 +0000 (+0200) Subject: Merge pull request #5589 from marek-safar/tests X-Git-Url: http://wien.tomnetworks.com/gitweb/?a=commitdiff_plain;h=7cec5b71231cfc136d6d70428370b3f7e0465051;hp=44fee4ff97aff7a337fb9afc603a0a5f6933f646;p=mono.git Merge pull request #5589 from marek-safar/tests Update tests network helper to be reliable in multi-threaded tests --- diff --git a/mcs/class/System.Runtime.Remoting/Makefile b/mcs/class/System.Runtime.Remoting/Makefile index 25d474679f9..4dc2f64f9d2 100644 --- a/mcs/class/System.Runtime.Remoting/Makefile +++ b/mcs/class/System.Runtime.Remoting/Makefile @@ -13,7 +13,7 @@ LIB_REFS += System.Web endif TEST_MCS_FLAGS = -nowarn:618 -TEST_LIB_REFS = System System.Xml +TEST_LIB_REFS = System System.Xml System.Core TEST_MONO_PATH = . diff --git a/mcs/class/test-helpers/NetworkHelpers.cs b/mcs/class/test-helpers/NetworkHelpers.cs index 9d5eb114081..262b8d33232 100644 --- a/mcs/class/test-helpers/NetworkHelpers.cs +++ b/mcs/class/test-helpers/NetworkHelpers.cs @@ -1,12 +1,14 @@ using System; using System.Net; using System.Net.Sockets; +using System.Collections.Generic; namespace MonoTests.Helpers { public static class NetworkHelpers { static Random rndPort = new Random (); + static HashSet portsTable = new HashSet (); public static int FindFreePort () { @@ -15,17 +17,32 @@ namespace MonoTests.Helpers { public static IPEndPoint LocalEphemeralEndPoint () { - while (true) { - var ep = new IPEndPoint (IPAddress.Loopback, rndPort.Next (10000, 60000)); - - try { - using (var socket = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { - socket.Bind (ep); - socket.Close (); - } - return ep; - } catch (SocketException) { } + int counter = 0; + + while (counter < 1000) { + var testingPort = rndPort.Next (10000, 60000); + + var ep = new IPEndPoint (IPAddress.Loopback, testingPort); + + lock (portsTable) { + if (portsTable.Contains (testingPort)) + continue; + + ++counter; + + try { + using (var socket = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { + socket.Bind (ep); + socket.Close (); + } + + portsTable.Add (testingPort); + return ep; + } catch (SocketException) { } + } } + + throw new ApplicationException ($"Could not find available local port after {counter} retries"); } } }