Skip to content

Commit

Permalink
(#279) Add Polly test project
Browse files Browse the repository at this point in the history
  • Loading branch information
pardahlman committed Oct 8, 2017
1 parent 2c574fb commit f8c091f
Show file tree
Hide file tree
Showing 6 changed files with 321 additions and 0 deletions.
7 changes: 7 additions & 0 deletions RawRabbit.sln
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RawRabbit.DependencyInjecti
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RawRabbit.Enrichers.Protobuf", "src\RawRabbit.Enrichers.Protobuf\RawRabbit.Enrichers.Protobuf.csproj", "{8D45F8AC-B65F-4A2B-9153-8A7F3D423575}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RawRabbit.Enrichers.Polly.Tests", "test\RawRabbit.Enrichers.Polly.Tests\RawRabbit.Enrichers.Polly.Tests.csproj", "{4B4C5936-D61E-4FD8-AEB7-154CEAF84E15}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -188,6 +190,10 @@ Global
{8D45F8AC-B65F-4A2B-9153-8A7F3D423575}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8D45F8AC-B65F-4A2B-9153-8A7F3D423575}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8D45F8AC-B65F-4A2B-9153-8A7F3D423575}.Release|Any CPU.Build.0 = Release|Any CPU
{4B4C5936-D61E-4FD8-AEB7-154CEAF84E15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B4C5936-D61E-4FD8-AEB7-154CEAF84E15}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B4C5936-D61E-4FD8-AEB7-154CEAF84E15}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B4C5936-D61E-4FD8-AEB7-154CEAF84E15}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -221,6 +227,7 @@ Global
{2788DED9-2558-496C-81B1-B471CD42AB64} = {2F91E22A-AEBA-4BEF-9A03-C8232830F697}
{CF308330-735E-411D-BBA9-0018DD079AF1} = {7FCF8D3B-BA55-4C47-AC60-5CEF75418BEB}
{8D45F8AC-B65F-4A2B-9153-8A7F3D423575} = {7FCF8D3B-BA55-4C47-AC60-5CEF75418BEB}
{4B4C5936-D61E-4FD8-AEB7-154CEAF84E15} = {2F91E22A-AEBA-4BEF-9A03-C8232830F697}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6EC93B92-1319-44D3-A596-9FBD9BD23050}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Moq;
using Polly;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using RawRabbit.Common;
using RawRabbit.Configuration.Queue;
using RawRabbit.Pipe;
using RawRabbit.Pipe.Middleware;
using Xunit;
using QueueDeclareMiddleware = RawRabbit.Enrichers.Polly.Middleware.QueueDeclareMiddleware;

namespace RawRabbit.Enrichers.Polly.Tests.Middleware
{
public class QueueDeclareMiddlewareTests
{
[Fact]
public async Task Should_Invoke_Queue_Declare_Policy_With_Correct_Context()
{
var topology = new Mock<ITopologyProvider>();
var queueDeclaration = new QueueDeclaration();
var policyCalled = false;
Context capturedContext = null;

topology
.SetupSequence(t => t.DeclareQueueAsync(queueDeclaration))
.Throws(new OperationInterruptedException(null))
.Returns(Task.CompletedTask);

var context = new PipeContext
{
Properties = new Dictionary<string, object>
{
{PipeKey.QueueDeclaration, queueDeclaration}
}
};

context.UsePolicy(Policy
.Handle<OperationInterruptedException>()
.RetryAsync((exception, retryCount, pollyContext) =>
{
policyCalled = true;
capturedContext = pollyContext;
}), PolicyKeys.QueueDeclare);
var middleware = new QueueDeclareMiddleware(topology.Object) {Next = new NoOpMiddleware()};

/* Test */
await middleware.InvokeAsync(context);

/* Assert */
Assert.True(policyCalled, "Should call policy");
Assert.Equal(context, capturedContext[RetryKey.PipeContext]);
Assert.Equal(queueDeclaration, capturedContext[RetryKey.QueueDeclaration]);
Assert.Equal(topology.Object, capturedContext[RetryKey.TopologyProvider]);
}
}
}
36 changes: 36 additions & 0 deletions test/RawRabbit.Enrichers.Polly.Tests/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RawRabbit.Enrichers.Polly.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RawRabbit.Enrichers.Polly.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4b4c5936-d61e-4fd8-aeb7-154ceaf84e15")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\xunit.core.2.3.0\build\xunit.core.props" Condition="Exists('..\..\packages\xunit.core.2.3.0\build\xunit.core.props')" />
<Import Project="..\..\packages\xunit.runner.visualstudio.2.3.0\build\net20\xunit.runner.visualstudio.props" Condition="Exists('..\..\packages\xunit.runner.visualstudio.2.3.0\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4B4C5936-D61E-4FD8-AEB7-154CEAF84E15}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RawRabbit.Enrichers.Polly.Tests</RootNamespace>
<AssemblyName>RawRabbit.Enrichers.Polly.Tests</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Castle.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Castle.Core.4.2.0\lib\net45\Castle.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Diagnostics.Tracing.EventSource, Version=1.1.28.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Diagnostics.Tracing.EventSource.Redist.1.1.28\lib\net46\Microsoft.Diagnostics.Tracing.EventSource.dll</HintPath>
</Reference>
<Reference Include="Moq, Version=4.7.137.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\..\packages\Moq.4.7.137\lib\net45\Moq.dll</HintPath>
</Reference>
<Reference Include="Polly, Version=5.3.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\Polly.5.3.1\lib\net45\Polly.dll</HintPath>
</Reference>
<Reference Include="RabbitMQ.Client, Version=5.0.0.0, Culture=neutral, PublicKeyToken=89e7d7c5feba84ce, processorArchitecture=MSIL">
<HintPath>..\..\packages\RabbitMQ.Client.5.0.1\lib\net451\RabbitMQ.Client.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.assert, Version=2.3.0.3820, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll</HintPath>
</Reference>
<Reference Include="xunit.core, Version=2.3.0.3820, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll</HintPath>
</Reference>
<Reference Include="xunit.execution.desktop, Version=2.3.0.3820, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Middleware\QueueDeclareMiddlewareTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\ChannelFactoryTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\..\packages\xunit.analyzers.0.7.0\analyzers\dotnet\cs\xunit.analyzers.dll" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RawRabbit.Enrichers.Polly\RawRabbit.Enrichers.Polly.csproj">
<Project>{c95030ff-2d90-4c68-b382-061ce8542c3b}</Project>
<Name>RawRabbit.Enrichers.Polly</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\RawRabbit\RawRabbit.csproj">
<Project>{14195f79-b374-4feb-ba3c-e24138542421}</Project>
<Name>RawRabbit</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\xunit.runner.visualstudio.2.3.0\build\net20\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\xunit.runner.visualstudio.2.3.0\build\net20\xunit.runner.visualstudio.props'))" />
<Error Condition="!Exists('..\..\packages\xunit.core.2.3.0\build\xunit.core.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\xunit.core.2.3.0\build\xunit.core.props'))" />
<Error Condition="!Exists('..\..\packages\xunit.core.2.3.0\build\xunit.core.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\xunit.core.2.3.0\build\xunit.core.targets'))" />
</Target>
<Import Project="..\..\packages\xunit.core.2.3.0\build\xunit.core.targets" Condition="Exists('..\..\packages\xunit.core.2.3.0\build\xunit.core.targets')" />
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Moq;
using Polly;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using RawRabbit.Configuration;
using RawRabbit.Enrichers.Polly.Services;
using Xunit;

namespace RawRabbit.Enrichers.Polly.Tests.Services
{
public class ChannelFactoryTests
{
[Fact]
public async Task Should_Use_Connect_Policy_When_Connecting_To_Broker()
{
/* Setup */
var connection = new Mock<IConnection>();
var connectionFactory = new Mock<IConnectionFactory>();
connectionFactory
.Setup(f => f.CreateConnection())
.Returns(connection.Object);
connectionFactory
.SetupSequence(c => c.CreateConnection(
It.IsAny<List<string>>()
))
.Throws(new BrokerUnreachableException(new Exception()))
.Throws(new BrokerUnreachableException(new Exception()))
.Throws(new BrokerUnreachableException(new Exception()))
.Returns(connection.Object);

var policy = Policy
.Handle<BrokerUnreachableException>()
.WaitAndRetryAsync(new[]
{
TimeSpan.FromMilliseconds(1),
TimeSpan.FromMilliseconds(2),
TimeSpan.FromMilliseconds(4),
TimeSpan.FromMilliseconds(8),
TimeSpan.FromMilliseconds(16)
});

var factory = new ChannelFactory(connectionFactory.Object, RawRabbitConfiguration.Local, new ConnectionPolicies{ Connect = policy});

/* Test */
/* Assert */
await factory.ConnectAsync();
}

[Fact]
public async Task Should_Use_Create_Channel_Policy_When_Creaing_Channels()
{
/* Setup */
var channel = new Mock<IModel>();
var connection = new Mock<IConnection>();
var connectionFactory = new Mock<IConnectionFactory>();
connectionFactory
.Setup(f => f.CreateConnection())
.Returns(connection.Object);
connectionFactory
.Setup(c => c.CreateConnection(
It.IsAny<List<string>>()
))
.Returns(connection.Object);
connection
.Setup(c => c.IsOpen)
.Returns(true);
connection
.SetupSequence(c => c.CreateModel())
.Throws(new TimeoutException())
.Throws(new TimeoutException())
.Returns(channel.Object);

var policy = Policy
.Handle<TimeoutException>()
.WaitAndRetryAsync(new[]
{
TimeSpan.FromMilliseconds(1),
TimeSpan.FromMilliseconds(2),
TimeSpan.FromMilliseconds(4),
TimeSpan.FromMilliseconds(8),
TimeSpan.FromMilliseconds(16)
});

var factory = new ChannelFactory(connectionFactory.Object, RawRabbitConfiguration.Local, new ConnectionPolicies { CreateChannel = policy });

/* Test */
var retrievedChannel = await factory.CreateChannelAsync();

/* Assert */
Assert.Equal(channel.Object, retrievedChannel);
}
}
}
16 changes: 16 additions & 0 deletions test/RawRabbit.Enrichers.Polly.Tests/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="4.2.0" targetFramework="net462" />
<package id="Microsoft.Diagnostics.Tracing.EventSource.Redist" version="1.1.28" targetFramework="net46" />
<package id="Moq" version="4.7.137" targetFramework="net462" />
<package id="Polly" version="5.3.1" targetFramework="net46" />
<package id="RabbitMQ.Client" version="5.0.1" targetFramework="net46" />
<package id="xunit" version="2.3.0" targetFramework="net462" />
<package id="xunit.abstractions" version="2.0.1" targetFramework="net462" />
<package id="xunit.analyzers" version="0.7.0" targetFramework="net462" />
<package id="xunit.assert" version="2.3.0" targetFramework="net462" />
<package id="xunit.core" version="2.3.0" targetFramework="net462" />
<package id="xunit.extensibility.core" version="2.3.0" targetFramework="net462" />
<package id="xunit.extensibility.execution" version="2.3.0" targetFramework="net462" />
<package id="xunit.runner.visualstudio" version="2.3.0" targetFramework="net462" developmentDependency="true" />
</packages>

0 comments on commit f8c091f

Please sign in to comment.