Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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,14 +4,15 @@
<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>

<ItemGroup>
<ProjectReference Include="..\..\..\core\Akka.TestKit\Akka.TestKit.csproj" />
<PackageReference Include="xunit" Version="$(XunitVersion)" />
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionsVersion)" />
Copy link
Member

Choose a reason for hiding this comment

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

Do we need the dependency on FluentAssertions for the TaskExtensions class?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I guess not, I wanted to introduce the ShouldCompleteWithin method in tests; I guess we can use our own WithTimeout method.

Copy link
Member

Choose a reason for hiding this comment

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

I'm fine bringing it in since we seem to use it everywhere, but maybe we should make it part of the base testkit if we're going to take a dependency on it. We can punt on it for now and just do our own thing, or we can try to close out #5432

Copy link
Member

Choose a reason for hiding this comment

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

How would you like to proceed on that?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

well, we can't because FluentAssertion depends on XUnit, that's why I'm putting it here instead in the base TestKit

Copy link
Contributor Author

@Arkatufus Arkatufus Apr 29, 2022

Choose a reason for hiding this comment

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

Oops, didn't know that FluentAssertion is unit test framework agnostic... I'm refactoring this to TestKit instead.

</ItemGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// //-----------------------------------------------------------------------
// // <copyright file="TaskExtensions.cs" company="Akka.NET Project">
// // Copyright (C) 2009-2022 Lightbend Inc. <http://www.lightbend.com>
// // Copyright (C) 2013-2022 .NET Foundation <https://github.com/akkadotnet/akka.net>
// // </copyright>
// //-----------------------------------------------------------------------

using System;
using System.Threading.Tasks;
using FluentAssertions;
using static FluentAssertions.FluentActions;

namespace Akka.TestKit.Xunit2.Extensions
{
public static class TaskExtensions
{
/// <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);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//-----------------------------------------------------------------------

using System;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Akka.Actor;
Expand All @@ -16,20 +15,21 @@
using Akka.TestKit.Internal;
using Akka.TestKit.Internal.StringMatcher;
using Akka.TestKit.TestEvent;
using Akka.TestKit.Xunit2.Extensions;
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