Skip to content

Commit

Permalink
(#109) TcpClientEx: add memory leak tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ForNeVeR committed Sep 23, 2021
1 parent a6d10bb commit 2d05994
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
72 changes: 72 additions & 0 deletions SharpXMPP.NUnit/Compat/TcpClientExTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;

namespace SharpXMPP.Compat
{
public class TcpClientExTests
{
private static int GetFreePort()
{
var host = new TcpListener(new IPEndPoint(IPAddress.Loopback, 0));
host.Start();
try
{
return ((IPEndPoint)host.LocalEndpoint).Port;
}
finally
{
host.Stop();
}
}

/// <summary>
/// This test checks for TcpClient leaks which are guaranteed to happen if the requests aren't properly
/// cancelled.
/// </summary>
/// <remarks>
/// Run with dotMemoryUnit to check for leaks, run without it for basic sanity check. For details see
/// https://www.jetbrains.com/help/dotmemory-unit/Get_Started.html#3-run-the-test
/// </remarks>
[Test, DotMemoryUnit(FailIfRunWithoutSupport = false)]
public void TestCancellation()
{
const int iterations = 100;
int cancelled = 0;

// Connecting to a free port takes enough time for the tasks to be cancelled in time.
var port = GetFreePort();
for (int i = 0; i < iterations; ++i)
{
Task.Run(async () =>
{
using var cts = new CancellationTokenSource();
var token = cts.Token;

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

try
{
await task;
}
catch (OperationCanceledException)
{
++cancelled;
}
}).Wait();
}

Assert.Greater(cancelled, 0);

dotMemory.Check(memory =>
// note there's 1 task object on pre-.NET 5 runtimes
Assert.LessOrEqual(memory.GetObjects(o => o.Type.Is<Task>()).ObjectsCount, 1));
}
}
}
1 change: 1 addition & 0 deletions SharpXMPP.NUnit/SharpXMPP.NUnit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="JetBrains.DotMemoryUnit" Version="3.1.20200127.214830" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
Expand Down
2 changes: 2 additions & 0 deletions SharpXMPP.Shared/Compat/TcpClientEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ private static async Task AbandonOnCancel(this Task task, CancellationToken canc
throw new OperationCanceledException(cancellationToken);
}
}

await task;
}
#endif

Expand Down

0 comments on commit 2d05994

Please sign in to comment.