Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Async TestKit] Convert Akka.Remote.Tests to async - Transport.ThrottlerTransportAdapterSpec #5901

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<PropertyGroup>
<AssemblyTitle>Akka.TestKit.Xunit2</AssemblyTitle>
<Description>TestKit for writing tests for Akka.NET using xUnit.</Description>
<TargetFrameworks>$(NetStandardLibVersion)</TargetFrameworks>
<TargetFramework>$(NetStandardLibVersion)</TargetFramework>
<PackageTags>$(AkkaPackageTags);testkit;xunit</PackageTags>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,30 @@
//-----------------------------------------------------------------------

using System;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Configuration;
using Akka.Remote.Transport;
using Akka.TestKit;
using Akka.TestKit.Extensions;
using Akka.TestKit.Internal;
using Akka.TestKit.Internal.StringMatcher;
using Akka.TestKit.TestEvent;
using Akka.Util;
using Akka.Util.Internal;
using FluentAssertions;
using FluentAssertions.Extensions;
using Xunit;
using Xunit.Abstractions;
using static FluentAssertions.FluentActions;

namespace Akka.Remote.Tests.Transport
{
public class ThrottlerTransportAdapterSpec : AkkaSpec
{
#region Setup / Config

public static Config ThrottlerTransportAdapterSpecConfig
private static Config ThrottlerTransportAdapterSpecConfig
{
get
{
Expand All @@ -53,12 +53,12 @@ public static Config ThrottlerTransportAdapterSpecConfig
private const int PingPacketSize = 350;
private const int MessageCount = 15;
private const int BytesPerSecond = 700;
private static readonly long TotalTime = (MessageCount * PingPacketSize) / BytesPerSecond;
private const long TotalTime = (MessageCount * PingPacketSize) / BytesPerSecond;

public class ThrottlingTester : ReceiveActor
{
private IActorRef _remoteRef;
private IActorRef _controller;
private readonly IActorRef _remoteRef;
private readonly IActorRef _controller;

private int _received = 0;
private int _messageCount = MessageCount;
Expand Down Expand Up @@ -110,7 +110,7 @@ public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is Lost && Equals((Lost) obj);
return obj is Lost lost && Equals(lost);
}

public override int GetHashCode()
Expand Down Expand Up @@ -140,14 +140,15 @@ protected override void OnReceive(object message)
private readonly ActorSystem _systemB;
private readonly IActorRef _remote;

private TimeSpan DefaultTimeout => Dilated(TestKitSettings.DefaultTimeout);

private RootActorPath RootB
{
get { return new RootActorPath(_systemB.AsInstanceOf<ExtendedActorSystem>().Provider.DefaultAddress); }
}
=> new RootActorPath(_systemB.AsInstanceOf<ExtendedActorSystem>().Provider.DefaultAddress);

private async Task<IActorRef> Here()
{
var identity = await Sys.ActorSelection(RootB / "user" / "echo").Ask<ActorIdentity>(new Identify(null));
var identity = await Sys.ActorSelection(RootB / "user" / "echo").Ask<ActorIdentity>(new Identify(null))
.ShouldCompleteWithin(DefaultTimeout);
return identity.Subject;
}

Expand All @@ -157,7 +158,8 @@ private async Task<bool> Throttle(ThrottleTransportAdapter.Direction direction,
var transport =
Sys.AsInstanceOf<ExtendedActorSystem>().Provider.AsInstanceOf<RemoteActorRefProvider>().Transport;

return await transport.ManagementCommand(new SetThrottle(rootBAddress, direction, mode));
return await transport.ManagementCommand(new SetThrottle(rootBAddress, direction, mode))
.ShouldCompleteWithin(DefaultTimeout);
}

private async Task<bool> Disassociate()
Expand All @@ -166,7 +168,8 @@ private async Task<bool> Disassociate()
var transport =
Sys.AsInstanceOf<ExtendedActorSystem>().Provider.AsInstanceOf<RemoteActorRefProvider>().Transport;

return await transport.ManagementCommand(new ForceDisassociate(rootBAddress));
return await transport.ManagementCommand(new ForceDisassociate(rootBAddress))
.ShouldCompleteWithin(DefaultTimeout);
}

#endregion
Expand All @@ -183,23 +186,21 @@ public ThrottlerTransportAdapterSpec(ITestOutputHelper output)
[Fact]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests themselves look fine

public async Task ThrottlerTransportAdapter_must_maintain_average_message_rate()
{
await ShouldCompleteWithin(
() => Throttle(
await Throttle(
ThrottleTransportAdapter.Direction.Send,
new Remote.Transport.TokenBucket(PingPacketSize * 4, BytesPerSecond, 0, 0)),
true, TimeSpan.FromSeconds(3));
new Remote.Transport.TokenBucket(PingPacketSize * 4, BytesPerSecond, 0, 0))
.ShouldCompleteWithin(true, TimeSpan.FromSeconds(3));

var here = await Here();
var tester = Sys.ActorOf(Props.Create(() => new ThrottlingTester(here, TestActor)));
tester.Tell("start");

var time = TimeSpan.FromTicks(ExpectMsg<long>(TimeSpan.FromSeconds(TotalTime + 12))).TotalSeconds;
var time = TimeSpan.FromTicks(await ExpectMsgAsync<long>(TimeSpan.FromSeconds(TotalTime + 12))).TotalSeconds;
Log.Warning("Total time of transmission: {0}", time);
time.Should().BeGreaterThan(TotalTime - 12);

await ShouldCompleteWithin(
() => Throttle(ThrottleTransportAdapter.Direction.Send, Unthrottled.Instance),
true, TimeSpan.FromSeconds(3));

await Throttle(ThrottleTransportAdapter.Direction.Send, Unthrottled.Instance)
.ShouldCompleteWithin(true, TimeSpan.FromSeconds(3));
}

[Fact]
Expand All @@ -208,25 +209,21 @@ public async Task ThrottlerTransportAdapter_must_survive_blackholing()

var here = await Here();
here.Tell(new ThrottlingTester.Lost("BlackHole 1"));
ExpectMsg(new ThrottlingTester.Lost("BlackHole 1"));
await ExpectMsgAsync(new ThrottlingTester.Lost("BlackHole 1"));

MuteDeadLetters(typeof(ThrottlingTester.Lost));
MuteDeadLetters(_systemB, typeof(ThrottlingTester.Lost));

await ShouldCompleteWithin(
func: () => Throttle(ThrottleTransportAdapter.Direction.Both, Blackhole.Instance),
expected: true,
timeout: TimeSpan.FromSeconds(3));
await Throttle(ThrottleTransportAdapter.Direction.Both, Blackhole.Instance)
.ShouldCompleteWithin(true, 3.Seconds());

here.Tell(new ThrottlingTester.Lost("BlackHole 2"));
await ExpectNoMsgAsync(TimeSpan.FromSeconds(1));
await ShouldCompleteWithin(Disassociate, true, TimeSpan.FromSeconds(3));
await Disassociate().ShouldCompleteWithin(true, TimeSpan.FromSeconds(3));
await ExpectNoMsgAsync(TimeSpan.FromSeconds(1));

await ShouldCompleteWithin(
func: () => Throttle(ThrottleTransportAdapter.Direction.Both, Unthrottled.Instance),
expected: true,
timeout: TimeSpan.FromSeconds(3));
await Throttle(ThrottleTransportAdapter.Direction.Both, Unthrottled.Instance)
.ShouldCompleteWithin(true, TimeSpan.FromSeconds(3));

// after we remove the Blackhole we can't be certain of the state
// of the connection, repeat until success
Expand All @@ -246,17 +243,6 @@ await AwaitConditionAsync(async () =>
await FishForMessageAsync(o => o.Equals("Cleanup"), TimeSpan.FromSeconds(5));
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static async Task ShouldCompleteWithin<T>(Func<Task<T>> func, T expected, TimeSpan timeout)
{
T result = default;
await Awaiting(async () =>
{
result = await func();
}).Should().CompleteWithinAsync(timeout);
result.Should().Be(expected);
}

#endregion

#region Cleanup
Expand All @@ -271,10 +257,10 @@ protected override async Task BeforeTerminationAsync()
await base.BeforeTerminationAsync();
}

protected override async Task AfterTerminationAsync()
protected override async Task AfterAllAsync()
{
await base.AfterAllAsync();
await ShutdownAsync(_systemB);
await base.AfterTerminationAsync();
}

#endregion
Expand Down
1 change: 1 addition & 0 deletions src/core/Akka.TestKit/Akka.TestKit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<PackageReference Include="Nito.AsyncEx.Coordination" Version="5.1.2" />
<PackageReference Include="Nito.AsyncEx.Context" Version="5.1.2" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionsVersion)" />
</ItemGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
Expand Down
65 changes: 65 additions & 0 deletions src/core/Akka.TestKit/Extensions/TaskExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using static FluentAssertions.FluentActions;

namespace Akka.TestKit.Extensions
{
Expand Down Expand Up @@ -64,5 +66,68 @@ public static async Task<T> WithTimeout<T>(this Task<T> parentTask, TimeSpan tim
}
}

/// <summary>
/// Guard a <see cref="Task{T}"/> with a timeout and checks to see if
/// the <see cref="Task{T}.Result"/> matches the provided expected value.
/// </summary>
/// <param name="task">The Task to be guarded</param>
/// <param name="expected">The expected Task.Result</param>
/// <param name="timeout">The allowed time span for the operation.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="M:System.String.Format(System.String,System.Object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="!:because" />.
/// </param>
/// <typeparam name="T"></typeparam>
public static async Task ShouldCompleteWithin<T>(
this Task<T> task, T expected, TimeSpan timeout, string because = "", params object[] becauseArgs)
{
await Awaiting(async () =>
{
var result = await task;
result.Should().Be(expected);
}).Should().CompleteWithinAsync(timeout, because, becauseArgs);
}

/// <summary>
/// Guard a <see cref="Task{T}"/> with a timeout and returns the <see cref="Task{T}.Result"/>.
/// </summary>
/// <param name="task">The Task to be guarded</param>
/// <param name="timeout">The allowed time span for the operation.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="M:System.String.Format(System.String,System.Object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="!:because" />.
/// </param>
/// <typeparam name="T"></typeparam>
public static async Task<T> ShouldCompleteWithin<T>(
this Task<T> task, TimeSpan timeout, string because = "", params object[] becauseArgs)
{
return (await Awaiting(async () => await task).Should().CompleteWithinAsync(timeout), because, becauseArgs)
.Item1.Subject;
}

/// <summary>
/// Guard a <see cref="Task"/> with a timeout.
/// </summary>
/// <param name="task">The Task to be guarded</param>
/// <param name="timeout">The allowed time span for the operation.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="M:System.String.Format(System.String,System.Object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="!:because" />.
/// </param>
/// <typeparam name="T"></typeparam>
public static async Task ShouldCompleteWithin(
this Task task, TimeSpan timeout, string because = "", params object[] becauseArgs)
{
await Awaiting(async () => await task).Should().CompleteWithinAsync(timeout, because, becauseArgs);
}
}
}