Skip to content

Commit

Permalink
(#109) TcpClientExTests: use same endpoint for host and client
Browse files Browse the repository at this point in the history
  • Loading branch information
ForNeVeR committed Sep 24, 2021
1 parent b0d6d7a commit c067278
Showing 1 changed file with 21 additions and 35 deletions.
56 changes: 21 additions & 35 deletions SharpXMPP.NUnit/Compat/TcpClientExTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ namespace SharpXMPP.Compat
{
public class TcpClientExTests
{
private static int GetFreePort()
private static IPEndPoint GetFreePortEndpoint()
{
var host = new TcpListener(new IPEndPoint(IPAddress.Loopback, 0));
var endpoint = new IPEndPoint(IPAddress.Loopback, 0);
var host = new TcpListener(endpoint);
host.Start();
try
{
return ((IPEndPoint)host.LocalEndpoint).Port;
return (IPEndPoint)host.LocalEndpoint;
}
finally
{
Expand All @@ -39,42 +40,27 @@ public void TestCancellation()
int cancelled = 0;

// Connecting to a free port takes enough time for the tasks to be cancelled in time.
var port = GetFreePort();
TcpListener host = null;
if (Environment.OSVersion.Platform == PlatformID.Unix)
var endpoint = GetFreePortEndpoint();
for (int i = 0; i < iterations; ++i)
{
// Since the port trick doesn't work on Linux, do this.
host = new TcpListener(new IPEndPoint(IPAddress.Loopback, port));
host.Start();
}

try
{
for (int i = 0; i < iterations; ++i)
Task.Run(async () =>
{
Task.Run(async () =>
{
using var cts = new CancellationTokenSource();
var token = cts.Token;
using var cts = new CancellationTokenSource();
var token = cts.Token;

using var client = new TcpClient();
var task = client.ConnectWithCancellationAsync(IPAddress.Loopback, port, token);
cts.Cancel();
using var client = new TcpClient();
var task = client.ConnectWithCancellationAsync(endpoint.Address, endpoint.Port, token);
cts.Cancel();

try
{
await task;
}
catch (OperationCanceledException)
{
++cancelled;
}
}).Wait();
}
}
finally
{
host?.Stop();
try
{
await task;
}
catch (OperationCanceledException)
{
++cancelled;
}
}).Wait();
}

Assert.Greater(cancelled, 0);
Expand Down

0 comments on commit c067278

Please sign in to comment.