diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 00000000000..ed800ac9f70 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "cake.tool": { + "version": "2.0.0", + "commands": [ + "dotnet-cake" + ] + } + } +} diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000000..8c69262d34c --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,4 @@ +# Use file-scoped namespaces +a450cb69b5e4549f5515cdb057a68771f56cefd7 +e32730600746b479db0241826b9bdef8eec9bb28 +63b151ebc191ef35df9e3f29584ca94ec5d7c792 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000000..6caebf98f56 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,51 @@ +name: build + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + workflow_dispatch: + +jobs: + build: + name: ${{ matrix.os }} + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: [ windows-latest ] + include: + #- os: macos-latest + # os_name: macos + #- os: ubuntu-latest + # os_name: linux + - os: windows-latest + os_name: windows + + steps: + + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v3 + + - name: Build, Test and Package + shell: pwsh + run: ./build.ps1 + env: + DOTNET_CLI_TELEMETRY_OPTOUT: true + DOTNET_GENERATE_ASPNET_CERTIFICATE: false + DOTNET_NOLOGO: true + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION: 1 + NUGET_XMLDOC_MODE: skip + TERM: xterm + + - name: Publish NuGet packages + uses: actions/upload-artifact@v3 + with: + name: packages-${{ matrix.os_name }} + path: ./artifacts/nuget-package diff --git a/.gitignore b/.gitignore index 08bc694c20c..444b9d4f606 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,6 @@ TestResults *.user *.sln.docstates .vs/ -.vscode/ .idea/ .ionide/ @@ -123,4 +122,5 @@ tools *.lock.json *.nuget.targets -*.nuget.props \ No newline at end of file +*.nuget.props +coverage.*.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000000..23f0bc802dd --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + "recommendations": [ + "EditorConfig.EditorConfig", + "k--kato.docomment", + "ms-dotnettools.csharp" + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000000..1333961f325 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,19 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Run tests", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "dotnet", + "args": [ + "test" + ], + "cwd": "${workspaceFolder}/src/Polly.Specs", + "console": "internalConsole", + "stopAtEntry": false, + "internalConsoleOptions": "openOnSessionStart" + } + ] +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 00000000000..395486b5a09 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,15 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet build ./src/Polly.sln", + "type": "shell", + "group": "build", + "presentation": { + "reveal": "silent" + }, + "problemMatcher": "$msCompile" + } + ] +} diff --git a/GitVersionConfig.yaml b/GitVersionConfig.yaml index 0105503e461..1b138331757 100644 --- a/GitVersionConfig.yaml +++ b/GitVersionConfig.yaml @@ -1 +1 @@ -next-version: 7.3.0 +next-version: 7.2.4 diff --git a/appveyor.yml b/appveyor.yml index 8494dd7f5c7..6c4bbe3aa72 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -12,5 +12,7 @@ artifacts: - path: artifacts\nuget-package\*.snupkg environment: - # Skip dotnet package caching on build servers - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + DOTNET_CLI_TELEMETRY_OPTOUT: true + DOTNET_GENERATE_ASPNET_CERTIFICATE: false + DOTNET_NOLOGO: true + NUGET_XMLDOC_MODE: skip diff --git a/build.bat b/build.bat index 8dbd6710abd..dde0203b8be 100644 --- a/build.bat +++ b/build.bat @@ -3,4 +3,3 @@ PUSHD %~dp0 PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& './build.ps1'" IF %errorlevel% neq 0 PAUSE - diff --git a/build.cake b/build.cake index a18ca7ce761..98920b3b91a 100644 --- a/build.cake +++ b/build.cake @@ -9,16 +9,17 @@ var configuration = Argument("configuration", "Release"); // EXTERNAL NUGET TOOLS ////////////////////////////////////////////////////////////////////// -#Tool "xunit.runner.console" -#Tool "GitVersion.CommandLine" +#Tool "GitVersion.CommandLine&version=5.8.1" +#Tool "xunit.runner.console&version=2.4.1" ////////////////////////////////////////////////////////////////////// // EXTERNAL NUGET LIBRARIES ////////////////////////////////////////////////////////////////////// -#addin nuget:?package=Cake.FileHelpers&version=3.3.0 -#addin nuget:?package=Cake.Yaml&version=3.1.1 -#addin nuget:?package=YamlDotNet&version=5.2.1 +#addin nuget:?package=Cake.FileHelpers&version=5.0.0 +#addin nuget:?package=Cake.Yaml&version=4.0.0 +#addin nuget:?package=Newtonsoft.Json&version=13.0.1 +#addin nuget:?package=YamlDotNet&version=11.2.1 /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES @@ -31,15 +32,15 @@ var solutionPaths = solutions.Select(solution => solution.GetDirectory()); var srcDir = Directory("./src"); var artifactsDir = Directory("./artifacts"); -var testResultsDir = artifactsDir + Directory("test-results"); +var testResultsDir = System.IO.Path.Combine(artifactsDir, Directory("test-results")); // NuGet -var nupkgDestDir = artifactsDir + Directory("nuget-package"); +var nupkgDestDir = System.IO.Path.Combine(artifactsDir, Directory("nuget-package")); -// Gitversion +// GitVersion var gitVersionPath = ToolsExePath("GitVersion.exe"); -Dictionary gitVersionOutput; var gitVersionConfigFilePath = "./GitVersionConfig.yaml"; +Dictionary gitVersionOutput; // Versioning string nugetVersion; @@ -81,7 +82,8 @@ Teardown(_ => Task("__Clean") .Does(() => { - DirectoryPath[] cleanDirectories = new DirectoryPath[] { + DirectoryPath[] cleanDirectories = new DirectoryPath[] + { testResultsDir, nupkgDestDir, artifactsDir @@ -94,17 +96,17 @@ Task("__Clean") foreach(var path in solutionPaths) { Information("Cleaning {0}", path); - DotNetCoreClean(path.ToString()); + DotNetClean(path.ToString()); } }); -Task("__RestoreNugetPackages") +Task("__RestoreNuGetPackages") .Does(() => { foreach(var solution in solutions) { Information("Restoring NuGet Packages for {0}", solution); - DotNetCoreRestore(solution.ToString()); + DotNetRestore(solution.ToString()); } }); @@ -114,7 +116,8 @@ Task("__UpdateAssemblyVersionInformation") var gitVersionSettings = new ProcessSettings() .SetRedirectStandardOutput(true); - try { + try + { IEnumerable outputLines; StartProcess(gitVersionPath, gitVersionSettings, out outputLines); @@ -129,13 +132,13 @@ Task("__UpdateAssemblyVersionInformation") GitVersionConfigYaml deserialized = DeserializeYaml(gitVersionYamlString.Replace("next-version", "NextVersion")); string gitVersionConfig = deserialized.NextVersion; - gitVersionOutput = new Dictionary{ + gitVersionOutput = new Dictionary + { { "NuGetVersion", gitVersionConfig + "-NotFromGitRepo" }, { "FullSemVer", gitVersionConfig }, { "AssemblySemVer", gitVersionConfig }, { "Major", gitVersionConfig.Split('.')[0] }, }; - } Information(""); @@ -151,19 +154,21 @@ Task("__UpdateAssemblyVersionInformation") Information(""); Information("Mapping versioning information to:"); - Information("Appveyor build number -> {0}", appveyorBuildNumber); - Information("Nuget package version -> {0}", nugetVersion); + Information("AppVeyor build number -> {0}", appveyorBuildNumber); + Information("NuGet package version -> {0}", nugetVersion); Information("AssemblyVersion -> {0}", assemblyVersion); Information("AssemblyFileVersion -> {0}", assemblySemver); Information("AssemblyInformationalVersion -> {0}", assemblySemver); }); Task("__UpdateDotNetStandardAssemblyVersionNumber") + .WithCriteria(() => AppVeyor.IsRunningOnAppVeyor) .Does(() => { Information("Updating Assembly Version Information"); - var attributeToValueMap = new Dictionary() { + var attributeToValueMap = new Dictionary() + { { "AssemblyVersion", assemblyVersion }, { "FileVersion", assemblySemver }, { "InformationalVersion", assemblySemver }, @@ -174,7 +179,8 @@ Task("__UpdateDotNetStandardAssemblyVersionNumber") var csproj = File("./src/" + projectName + "/" + projectName + ".csproj"); - foreach(var attributeMap in attributeToValueMap) { + foreach(var attributeMap in attributeToValueMap) + { var attribute = attributeMap.Key; var value = attributeMap.Value; @@ -184,7 +190,6 @@ Task("__UpdateDotNetStandardAssemblyVersionNumber") throw new Exception($"{attribute} version could not be updated in {csproj}."); } } - }); Task("__UpdateAppVeyorBuildNumber") @@ -201,42 +206,46 @@ Task("__BuildSolutions") { Information("Building {0}", solution); - var dotNetCoreBuildSettings = new DotNetCoreBuildSettings { - Configuration = configuration, - Verbosity = DotNetCoreVerbosity.Minimal, - NoRestore = true, - MSBuildSettings = new DotNetCoreMSBuildSettings { TreatAllWarningsAs = MSBuildTreatAllWarningsAs.Error } + var dotNetCoreBuildSettings = new DotNetBuildSettings + { + Configuration = configuration, + Verbosity = DotNetCoreVerbosity.Minimal, + NoRestore = true, + MSBuildSettings = new DotNetMSBuildSettings { TreatAllWarningsAs = MSBuildTreatAllWarningsAs.Error }, }; - DotNetCoreBuild(solution.ToString(), dotNetCoreBuildSettings); + DotNetBuild(solution.ToString(), dotNetCoreBuildSettings); } }); Task("__RunTests") .Does(() => { - foreach(var specsProj in GetFiles("./src/**/*.Specs.csproj")) { - DotNetCoreTest(specsProj.FullPath, new DotNetCoreTestSettings { + foreach(var specsProj in GetFiles("./src/**/*.Specs.csproj")) + { + DotNetTest(specsProj.FullPath, new DotNetTestSettings + { Configuration = configuration, - NoBuild = true + NoBuild = true, }); } }); -Task("__CreateSignedNugetPackage") +Task("__CreateSignedNuGetPackage") .Does(() => { var packageName = projectName; Information("Building {0}.{1}.nupkg", packageName, nugetVersion); - var dotNetCorePackSettings = new DotNetCorePackSettings { + var dotNetCorePackSettings = new DotNetPackSettings + { Configuration = configuration, NoBuild = true, - OutputDirectory = nupkgDestDir + OutputDirectory = nupkgDestDir, }; - DotNetCorePack($@"{srcDir}\{projectName}.sln", dotNetCorePackSettings); + DotNetPack(System.IO.Path.Combine(srcDir, projectName + ".sln"), dotNetCorePackSettings); }); ////////////////////////////////////////////////////////////////////// @@ -245,13 +254,13 @@ Task("__CreateSignedNugetPackage") Task("Build") .IsDependentOn("__Clean") - .IsDependentOn("__RestoreNugetPackages") + .IsDependentOn("__RestoreNuGetPackages") .IsDependentOn("__UpdateAssemblyVersionInformation") .IsDependentOn("__UpdateDotNetStandardAssemblyVersionNumber") .IsDependentOn("__UpdateAppVeyorBuildNumber") .IsDependentOn("__BuildSolutions") .IsDependentOn("__RunTests") - .IsDependentOn("__CreateSignedNugetPackage"); + .IsDependentOn("__CreateSignedNuGetPackage"); /////////////////////////////////////////////////////////////////////////////// // PRIMARY TARGETS @@ -271,6 +280,6 @@ RunTarget(target); ////////////////////////////////////////////////////////////////////// string ToolsExePath(string exeFileName) { - var exePath = System.IO.Directory.GetFiles(@"./tools", exeFileName, SearchOption.AllDirectories).FirstOrDefault(); + var exePath = System.IO.Directory.GetFiles("./tools", exeFileName, SearchOption.AllDirectories).FirstOrDefault(); return exePath; } diff --git a/build.ps1 b/build.ps1 old mode 100644 new mode 100755 index 5d095556f4d..6838e1e840c --- a/build.ps1 +++ b/build.ps1 @@ -1,3 +1,4 @@ +#! /usr/bin/env pwsh <# .SYNOPSIS @@ -41,36 +42,39 @@ Param( [switch]$Verbose ) +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" + Write-Host "Preparing to run build script..." # Should we show verbose messages? -if($Verbose.IsPresent) +if ($Verbose.IsPresent) { $VerbosePreference = "continue" } $TOOLS_DIR = Join-Path $PSScriptRoot "tools" $NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe" -$CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe" $PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config" +$DOTNET = "dotnet.exe" # Should we use mono? $UseMono = ""; -if($Mono.IsPresent) { +if ($Mono.IsPresent) { Write-Verbose -Message "Using the Mono based scripting engine." $UseMono = "-mono" } # Should we use the new Roslyn? $UseExperimental = ""; -if($Experimental.IsPresent -and !($Mono.IsPresent)) { +if ($Experimental.IsPresent -and !($Mono.IsPresent)) { Write-Verbose -Message "Using experimental version of Roslyn." $UseExperimental = "-experimental" } # Is this a dry run? $UseDryRun = ""; -if($WhatIf.IsPresent) { +if ($WhatIf.IsPresent) { $UseDryRun = "-dryrun" } @@ -94,7 +98,7 @@ if (!(Test-Path $NUGET_EXE)) { $ENV:NUGET_EXE = $NUGET_EXE # Restore tools from NuGet? -if(-Not $SkipToolPackageRestore.IsPresent) +if (-Not $SkipToolPackageRestore.IsPresent) { # Restore tools from NuGet. Push-Location @@ -111,7 +115,7 @@ if(-Not $SkipToolPackageRestore.IsPresent) # Install just Cake if missing config else { - $NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install Cake -Version 0.38.5 -ExcludeVersion" # Pin Cake version to 0.38.5; see https://github.com/App-vNext/Polly/issues/416 + $NuGetOutput = Invoke-Expression "&`"$DOTNET`" tool install Cake.Tool --version 2.0.0" Write-Verbose ($NuGetOutput | Out-String) } Pop-Location @@ -121,12 +125,7 @@ if(-Not $SkipToolPackageRestore.IsPresent) } } -# Make sure that Cake has been installed. -if (!(Test-Path $CAKE_EXE)) { - Throw "Could not find Cake.exe" -} - # Start Cake Write-Host "Running build script..." -Invoke-Expression "$CAKE_EXE `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseMono $UseDryRun $UseExperimental" +Invoke-Expression "dotnet dotnet-cake `"$Script`" --target=`"$Target`" --configuration=`"$Configuration`" --verbosity=`"$Verbosity`" $UseMono $UseDryRun $UseExperimental" exit $LASTEXITCODE diff --git a/global.json b/global.json index 47a7fa60368..124ed58f386 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,7 @@ { "sdk": { - "allowPrerelease": false + "version": "6.0.404", + "allowPrerelease": false, + "rollForward": "latestMajor" } } diff --git a/src/Polly.Benchmarks/Bulkhead.cs b/src/Polly.Benchmarks/Bulkhead.cs index 70efe99d165..36a9449c838 100644 --- a/src/Polly.Benchmarks/Bulkhead.cs +++ b/src/Polly.Benchmarks/Bulkhead.cs @@ -45,4 +45,4 @@ public async Task Bulkhead_Asynchronous_With_Result_With_CancellationToken( { return await AsyncPolicy.ExecuteAsync((token) => Workloads.FuncAsync(token), CancellationToken.None); } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/Cache.cs b/src/Polly.Benchmarks/Cache.cs index 188c3d55296..c800251cddb 100644 --- a/src/Polly.Benchmarks/Cache.cs +++ b/src/Polly.Benchmarks/Cache.cs @@ -68,13 +68,13 @@ public MemoryCacheProvider(IMemoryCache memoryCache) public (bool, object) TryGet(string key) { - var cacheHit = _cache.TryGetValue(key, out var value); + bool cacheHit = _cache.TryGetValue(key, out var value); return (cacheHit, value); } public void Put(string key, object value, Ttl ttl) { - var remaining = DateTimeOffset.MaxValue - DateTimeOffset.UtcNow; + TimeSpan remaining = DateTimeOffset.MaxValue - DateTimeOffset.UtcNow; var options = new MemoryCacheEntryOptions(); if (ttl.SlidingExpiration) @@ -96,8 +96,10 @@ public void Put(string key, object value, Ttl ttl) _cache.Set(key, value, options); } - public Task<(bool, object)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) => - Task.FromResult(TryGet(key)); + public Task<(bool, object)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) + { + return Task.FromResult(TryGet(key)); + } public Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext) { @@ -105,4 +107,4 @@ public Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancel return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/CircuitBreaker.cs b/src/Polly.Benchmarks/CircuitBreaker.cs index 277d991b92d..b07e9c4d344 100644 --- a/src/Polly.Benchmarks/CircuitBreaker.cs +++ b/src/Polly.Benchmarks/CircuitBreaker.cs @@ -34,4 +34,4 @@ public async Task CircuitBreaker_Asynchronous_With_Result_Succeeds() { return await AsyncPolicy.ExecuteAsync((token) => Workloads.FuncAsync(token), CancellationToken.None); } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/Fallback.cs b/src/Polly.Benchmarks/Fallback.cs index 53e58eb937d..7b602777c0e 100644 --- a/src/Polly.Benchmarks/Fallback.cs +++ b/src/Polly.Benchmarks/Fallback.cs @@ -33,4 +33,4 @@ public async Task Fallback_Asynchronous_Throws() { return await AsyncPolicy.ExecuteAsync(() => Workloads.FuncThrowsAsync()); } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/NoOp.cs b/src/Polly.Benchmarks/NoOp.cs index 88dde9e91a0..4e8666ae9e4 100644 --- a/src/Polly.Benchmarks/NoOp.cs +++ b/src/Polly.Benchmarks/NoOp.cs @@ -33,4 +33,4 @@ public async Task NoOp_Asynchronous_With_Result() { return await AsyncPolicy.ExecuteAsync((token) => Workloads.FuncAsync(token), CancellationToken.None); } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/PolicyWrap.cs b/src/Polly.Benchmarks/PolicyWrap.cs index ab245ce4b06..9b8838ea65d 100644 --- a/src/Polly.Benchmarks/PolicyWrap.cs +++ b/src/Polly.Benchmarks/PolicyWrap.cs @@ -43,4 +43,4 @@ public async Task PolicyWrap_Asynchronous_With_Result() { return await AsyncPolicy.ExecuteAsync((token) => Workloads.FuncAsync(token), CancellationToken.None); } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/PollyConfig.cs b/src/Polly.Benchmarks/PollyConfig.cs index 0d79053be7e..03218e70c24 100644 --- a/src/Polly.Benchmarks/PollyConfig.cs +++ b/src/Polly.Benchmarks/PollyConfig.cs @@ -20,17 +20,17 @@ private static Job PollyJob(Job job, bool useNuGet) var result = job .WithId("Polly" + (useNuGet ? string.Empty : "-dev")) .WithArguments( - new[] - { - new MsBuildArgument("/p:BenchmarkFromNuGet=" + useNuGet), - new MsBuildArgument("/p:SignAssembly=false"), - }); + new[] + { + new MsBuildArgument("/p:BenchmarkFromNuGet=" + useNuGet), + new MsBuildArgument("/p:SignAssembly=false"), + }); if (useNuGet) { - result = result.WithNuGet("Polly", "7.2.1"); + result = result.WithNuGet("Polly", "7.2.3"); } return result; } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/RateLimit.cs b/src/Polly.Benchmarks/RateLimit.cs new file mode 100644 index 00000000000..c4267856168 --- /dev/null +++ b/src/Polly.Benchmarks/RateLimit.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading.Tasks; +using BenchmarkDotNet.Attributes; + +namespace Polly.Benchmarks; + +[Config(typeof(PollyConfig))] +public class RateLimit +{ + private static readonly Policy SyncPolicy = Policy.RateLimit(20, TimeSpan.FromSeconds(1), int.MaxValue); + private static readonly AsyncPolicy AsyncPolicy = Policy.RateLimitAsync(20, TimeSpan.FromSeconds(1), int.MaxValue); + + [Benchmark] + public void RateLimit_Synchronous_Succeeds() + { + SyncPolicy.Execute(() => Workloads.Action()); + } + + [Benchmark] + public async Task RateLimit_Asynchronous_Succeeds() + { + await AsyncPolicy.ExecuteAsync(() => Workloads.ActionAsync()); + } + + [Benchmark] + public int RateLimit_Synchronous_With_Result_Succeeds() + { + return SyncPolicy.Execute(() => Workloads.Func()); + } + + [Benchmark] + public async Task RateLimit_Asynchronous_With_Result_Succeeds() + { + return await AsyncPolicy.ExecuteAsync(() => Workloads.FuncAsync()); + } +} diff --git a/src/Polly.Benchmarks/Retry.cs b/src/Polly.Benchmarks/Retry.cs index def801e2455..ad4143c7669 100644 --- a/src/Polly.Benchmarks/Retry.cs +++ b/src/Polly.Benchmarks/Retry.cs @@ -50,7 +50,7 @@ public async Task Retry_Asynchronous_With_Result_Succeeds_With_Cancellation [Benchmark] public void Retry_Synchronous_Throws_Then_Succeeds() { - var count = 0; + int count = 0; SyncPolicy.Execute(() => { @@ -64,7 +64,7 @@ public void Retry_Synchronous_Throws_Then_Succeeds() [Benchmark] public async Task Retry_Asynchronous_Throws_Then_Succeeds() { - var count = 0; + int count = 0; await AsyncPolicy.ExecuteAsync(() => { @@ -76,4 +76,4 @@ await AsyncPolicy.ExecuteAsync(() => return Task.CompletedTask; }); } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/Timeout.cs b/src/Polly.Benchmarks/Timeout.cs index d5b0c1542cb..68f84becd9c 100644 --- a/src/Polly.Benchmarks/Timeout.cs +++ b/src/Polly.Benchmarks/Timeout.cs @@ -52,4 +52,4 @@ public async Task Timeout_Asynchronous_Times_Out_Optimistic() { await AsyncPolicy.ExecuteAsync((token) => Workloads.ActionInfiniteAsync(token), CancellationToken.None); } -} \ No newline at end of file +} diff --git a/src/Polly.Benchmarks/Workloads.cs b/src/Polly.Benchmarks/Workloads.cs index 837d25f4937..9d8d8e121d4 100644 --- a/src/Polly.Benchmarks/Workloads.cs +++ b/src/Polly.Benchmarks/Workloads.cs @@ -37,10 +37,14 @@ internal static async Task ActionInfiniteAsync(CancellationToken cancellationTok internal static Task FuncAsync(CancellationToken cancellationToken) => Task.FromResult(default); internal static TResult FuncThrows() - where TException : Exception, new() => + where TException : Exception, new() + { throw new TException(); + } internal static Task FuncThrowsAsync() - where TException : Exception, new() => + where TException : Exception, new() + { throw new TException(); -} \ No newline at end of file + } +} diff --git a/src/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs b/src/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs index 6b60386d662..6cbffac492a 100644 --- a/src/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs +++ b/src/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs @@ -52,24 +52,24 @@ public void Should_throw_when_onBulkheadRejected_is_null() #region onBulkheadRejected delegate [Fact] - public void Should_call_onBulkheadRejected_with_passed_context() + public async Task Should_call_onBulkheadRejected_with_passed_context() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnRejected = null; Func onRejectedAsync = async ctx => { contextPassedToOnRejected = ctx; await TaskHelper.EmptyTask; }; using (var bulkhead = Policy.BulkheadAsync(1, onRejectedAsync)) { - var tcs = new TaskCompletionSource(); - using (var cancellationSource = new CancellationTokenSource()) + TaskCompletionSource tcs = new TaskCompletionSource(); + using (CancellationTokenSource cancellationSource = new CancellationTokenSource()) { - Task.Run(() => { bulkhead.ExecuteAsync(async () => { await tcs.Task; }); }); + _ = Task.Run(() => { bulkhead.ExecuteAsync(async () => { await tcs.Task; }); }); Within(CohesionTimeLimit, () => Expect(0, () => bulkhead.BulkheadAvailableCount, nameof(bulkhead.BulkheadAvailableCount))); - bulkhead.Awaiting(b => b.ExecuteAsync(_ => TaskHelper.EmptyTask, contextPassedToExecute)).Should().Throw(); + await bulkhead.Awaiting(b => b.ExecuteAsync(_ => TaskHelper.EmptyTask, contextPassedToExecute)).Should().ThrowAsync(); cancellationSource.Cancel(); tcs.SetCanceled(); @@ -85,12 +85,16 @@ public void Should_call_onBulkheadRejected_with_passed_context() #region Bulkhead behaviour - protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) => - Policy.BulkheadAsync(maxParallelization, maxQueuingActions); + protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) + { + return Policy.BulkheadAsync(maxParallelization, maxQueuingActions); + } - protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) => - action.ExecuteOnBulkheadAsync((AsyncBulkheadPolicy)bulkhead); + protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) + { + return action.ExecuteOnBulkheadAsync((AsyncBulkheadPolicy)bulkhead); + } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Bulkhead/BulkheadScenario.cs b/src/Polly.Specs/Bulkhead/BulkheadScenario.cs index 64025aa39d5..66d96640201 100644 --- a/src/Polly.Specs/Bulkhead/BulkheadScenario.cs +++ b/src/Polly.Specs/Bulkhead/BulkheadScenario.cs @@ -11,16 +11,16 @@ internal struct BulkheadScenario public BulkheadScenario(int maxParallelization, int maxQueuingActions, int totalTestLoad, bool cancelQueuing, bool cancelExecuting, string scenario) { - _maxParallelization = maxParallelization; - _maxQueuingActions = maxQueuingActions; - _totalTestLoad = totalTestLoad; - _scenario = scenario; - _cancelQueuing = cancelQueuing; - _cancelExecuting = cancelExecuting; + _maxParallelization = maxParallelization; + _maxQueuingActions = maxQueuingActions; + _totalTestLoad = totalTestLoad; + _scenario = scenario; + _cancelQueuing = cancelQueuing; + _cancelExecuting = cancelExecuting; } public object[] ToTheoryData() { return new object[] {_maxParallelization, _maxQueuingActions, _totalTestLoad, _cancelQueuing, _cancelExecuting, _scenario }; } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Bulkhead/BulkheadScenarios.cs b/src/Polly.Specs/Bulkhead/BulkheadScenarios.cs index 3a334aee652..69d3e930b90 100644 --- a/src/Polly.Specs/Bulkhead/BulkheadScenarios.cs +++ b/src/Polly.Specs/Bulkhead/BulkheadScenarios.cs @@ -21,4 +21,4 @@ public IEnumerator GetEnumerator() } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Bulkhead/BulkheadSpecs.cs b/src/Polly.Specs/Bulkhead/BulkheadSpecs.cs index 47d10dc0e7e..dd1c684de75 100644 --- a/src/Polly.Specs/Bulkhead/BulkheadSpecs.cs +++ b/src/Polly.Specs/Bulkhead/BulkheadSpecs.cs @@ -52,15 +52,15 @@ public void Should_throw_when_onBulkheadRejected_is_null() [Fact] public void Should_call_onBulkheadRejected_with_passed_context() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnRejected = null; Action onRejected = ctx => { contextPassedToOnRejected = ctx; }; - using (var bulkhead = Policy.Bulkhead(1, onRejected)) + using (BulkheadPolicy bulkhead = Policy.Bulkhead(1, onRejected)) { - var tcs = new TaskCompletionSource(); + TaskCompletionSource tcs = new TaskCompletionSource(); Task.Run(() => { bulkhead.Execute(() => { tcs.Task.Wait(); }); }); @@ -82,12 +82,16 @@ public void Should_call_onBulkheadRejected_with_passed_context() #region Bulkhead behaviour - protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) => - Policy.Bulkhead(maxParallelization, maxQueuingActions); + protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) + { + return Policy.Bulkhead(maxParallelization, maxQueuingActions); + } - protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) => - action.ExecuteOnBulkhead((BulkheadPolicy) bulkhead); + protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) + { + return action.ExecuteOnBulkhead((BulkheadPolicy) bulkhead); + } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs b/src/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs index ea646a01526..c014bd99c43 100644 --- a/src/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs +++ b/src/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs @@ -23,7 +23,7 @@ public abstract class BulkheadSpecsBase : IDisposable public BulkheadSpecsBase(ITestOutputHelper testOutputHelper) { #if !DEBUG - TestOutputHelper = new SilentOutputHelper(); + TestOutputHelper = new SilentOutputHelper(); #else TestOutputHelper = new AnnotatedOutputHelper(testOutputHelper); #endif @@ -93,18 +93,18 @@ public void Should_control_executions_per_specification(int maxParallelization, TotalActions = totalActions; Scenario = $"MaxParallelization {maxParallelization}; MaxQueuing {maxQueuingActions}; TotalActions {totalActions}; CancelQueuing {cancelQueuing}; CancelExecuting {cancelExecuting}: {scenario}"; - var bulkhead = GetBulkhead(maxParallelization, maxQueuingActions); + IBulkheadPolicy bulkhead = GetBulkhead(maxParallelization, maxQueuingActions); using (bulkhead) { BulkheadForStats = bulkhead; // Set up delegates which we can track whether they've started; and control when we allow them to complete (to release their semaphore slot). Actions = new TraceableAction[totalActions]; - for (var i = 0; i < totalActions; i++) { Actions[i] = new TraceableAction(i, StatusChangedEvent, TestOutputHelper); } + for (int i = 0; i < totalActions; i++) { Actions[i] = new TraceableAction(i, StatusChangedEvent, TestOutputHelper); } // Throw all the delegates at the bulkhead simultaneously. Tasks = new Task[totalActions]; - for (var i = 0; i < totalActions; i++) { Tasks[i] = ExecuteOnBulkhead(bulkhead, Actions[i]); } + for (int i = 0; i < totalActions; i++) { Tasks[i] = ExecuteOnBulkhead(bulkhead, Actions[i]); } OutputStatus("Immediately after queueing..."); @@ -204,7 +204,7 @@ protected void UpdateActuals() { ActualCompleted = ActualCancelled = ActualExecuting = ActualRejects = ActualQueuing = ActualFaulted = 0; - foreach (var action in Actions) + foreach (TraceableAction action in Actions) { switch (action.Status) { @@ -285,7 +285,7 @@ protected AssertionFailure ActualsMatchExpecteds() protected AssertionFailure AllTasksCompleted() { - var countTasksCompleted = Tasks.Count(t => t.IsCompleted); + int countTasksCompleted = Tasks.Count(t => t.IsCompleted); if (countTasksCompleted < TotalActions) { return new AssertionFailure(TotalActions, countTasksCompleted, nameof(countTasksCompleted)); @@ -296,7 +296,7 @@ protected AssertionFailure AllTasksCompleted() protected void EnsureNoUnbservedTaskExceptions() { - for (var i = 0; i < Tasks.Length; i++) + for (int i = 0; i < Tasks.Length; i++) { try { @@ -313,14 +313,14 @@ protected void EnsureNoUnbservedTaskExceptions() protected AssertionFailure Expect(int expected, Func actualFunc, string measure) { - var actual = actualFunc(); + int actual = actualFunc(); return actual != expected ? new AssertionFailure(expected, actual, measure) : null; } protected void Within(TimeSpan timeSpan, Func actionContainingAssertions) { - var permitted = timeSpan; - var watch = Stopwatch.StartNew(); + TimeSpan permitted = timeSpan; + Stopwatch watch = Stopwatch.StartNew(); while (true) { var potentialFailure = actionContainingAssertions(); @@ -336,7 +336,7 @@ protected void Within(TimeSpan timeSpan, Func actionContaining throw new InvalidOperationException("Code should never reach here. Preceding assertion should fail."); } - var signaled = StatusChangedEvent.WaitOne(ShimTimeSpan); + bool signaled = StatusChangedEvent.WaitOne(ShimTimeSpan); if (signaled) { // Following TraceableAction.CaptureCompletion() signalling the AutoResetEvent, @@ -360,7 +360,7 @@ protected void OutputStatus(string statusHeading) TestOutputHelper.WriteLine("Bulkhead: {0} slots out of {1} available.", ActualBulkheadFree, MaxParallelization); TestOutputHelper.WriteLine("Bulkhead queue: {0} slots out of {1} available.", ActualQueueFree, MaxQueuingActions); - for (var i = 0; i < Actions.Length; i++) + for (int i = 0; i < Actions.Length; i++) { TestOutputHelper.WriteLine("Action {0}: {1}", i, Actions[i].Status); } @@ -382,7 +382,7 @@ public void Dispose() if (Actions != null) { - foreach (var action in Actions) + foreach (TraceableAction action in Actions) { action.Dispose(); } @@ -390,4 +390,4 @@ public void Dispose() StatusChangedEvent.Dispose(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs b/src/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs index 8b299766b8c..97c5abaf65c 100644 --- a/src/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs +++ b/src/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs @@ -53,20 +53,20 @@ public void Should_throw_when_onBulkheadRejected_is_null() #region onBulkheadRejected delegate [Fact] - public void Should_call_onBulkheadRejected_with_passed_context() + public async Task Should_call_onBulkheadRejected_with_passed_context() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnRejected = null; Func onRejectedAsync = async ctx => { contextPassedToOnRejected = ctx; await TaskHelper.EmptyTask; }; using (var bulkhead = Policy.BulkheadAsync(1, onRejectedAsync)) { - var tcs = new TaskCompletionSource(); - using (var cancellationSource = new CancellationTokenSource()) + TaskCompletionSource tcs = new TaskCompletionSource(); + using (CancellationTokenSource cancellationSource = new CancellationTokenSource()) { - Task.Run(() => { + _ = Task.Run(() => { bulkhead.ExecuteAsync(async () => { await tcs.Task; @@ -76,7 +76,7 @@ public void Should_call_onBulkheadRejected_with_passed_context() Within(CohesionTimeLimit, () => Expect(0, () => bulkhead.BulkheadAvailableCount, nameof(bulkhead.BulkheadAvailableCount))); - bulkhead.Awaiting(b => b.ExecuteAsync(_ => Task.FromResult(1), contextPassedToExecute)).Should().Throw(); + await bulkhead.Awaiting(b => b.ExecuteAsync(_ => Task.FromResult(1), contextPassedToExecute)).Should().ThrowAsync(); cancellationSource.Cancel(); tcs.SetCanceled(); @@ -85,6 +85,7 @@ public void Should_call_onBulkheadRejected_with_passed_context() contextPassedToOnRejected.Should().NotBeNull(); contextPassedToOnRejected.OperationKey.Should().Be(operationKey); contextPassedToOnRejected.Should().BeSameAs(contextPassedToExecute); + } } @@ -93,12 +94,16 @@ public void Should_call_onBulkheadRejected_with_passed_context() #region Bulkhead behaviour - protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) => - Policy.BulkheadAsync(maxParallelization, maxQueuingActions); + protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) + { + return Policy.BulkheadAsync(maxParallelization, maxQueuingActions); + } - protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) => - action.ExecuteOnBulkheadAsync((AsyncBulkheadPolicy)bulkhead); + protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) + { + return action.ExecuteOnBulkheadAsync((AsyncBulkheadPolicy)bulkhead); + } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs b/src/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs index 374bfa81bf4..3100343ba2e 100644 --- a/src/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs +++ b/src/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs @@ -55,16 +55,16 @@ public void Should_throw_when_onBulkheadRejected_is_null() [Fact] public void Should_call_onBulkheadRejected_with_passed_context() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnRejected = null; Action onRejected = ctx => { contextPassedToOnRejected = ctx; }; - using (var bulkhead = Policy.Bulkhead(1, onRejected)) + using (BulkheadPolicy bulkhead = Policy.Bulkhead(1, onRejected)) { - var tcs = new TaskCompletionSource(); - using (var cancellationSource = new CancellationTokenSource()) + TaskCompletionSource tcs = new TaskCompletionSource(); + using (CancellationTokenSource cancellationSource = new CancellationTokenSource()) { Task.Run(() => { bulkhead.Execute(() => @@ -92,11 +92,15 @@ public void Should_call_onBulkheadRejected_with_passed_context() #region Bulkhead behaviour - protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) => - Policy.Bulkhead(maxParallelization, maxQueuingActions); + protected override IBulkheadPolicy GetBulkhead(int maxParallelization, int maxQueuingActions) + { + return Policy.Bulkhead(maxParallelization, maxQueuingActions); + } - protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) => - action.ExecuteOnBulkhead((BulkheadPolicy) bulkhead); + protected override Task ExecuteOnBulkhead(IBulkheadPolicy bulkhead, TraceableAction action) + { + return action.ExecuteOnBulkhead((BulkheadPolicy) bulkhead); + } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs b/src/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs index 193bcae6aa7..4b6d5b1904a 100644 --- a/src/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs +++ b/src/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs @@ -21,4 +21,4 @@ public void Should_be_able_to_use_QueueAvailableCount_via_interface() bulkhead.QueueAvailableCount.Should().Be(10); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/AbsoluteTtlSpecs.cs b/src/Polly.Specs/Caching/AbsoluteTtlSpecs.cs index 090aba34c1d..ebd4c427fda 100644 --- a/src/Polly.Specs/Caching/AbsoluteTtlSpecs.cs +++ b/src/Polly.Specs/Caching/AbsoluteTtlSpecs.cs @@ -37,7 +37,7 @@ public void Should_be_able_to_configure_for_past() [Fact] public void Should_return_zero_ttl_if_configured_to_expire_in_past() { - var ttlStrategy = new AbsoluteTtl(SystemClock.DateTimeOffsetUtcNow().Subtract(TimeSpan.FromTicks(1))); + AbsoluteTtl ttlStrategy = new AbsoluteTtl(SystemClock.DateTimeOffsetUtcNow().Subtract(TimeSpan.FromTicks(1))); ttlStrategy.GetTtl(new Context("someOperationKey"), null).Timespan.Should().Be(TimeSpan.Zero); } @@ -45,10 +45,10 @@ public void Should_return_zero_ttl_if_configured_to_expire_in_past() [Fact] public void Should_return_timespan_reflecting_time_until_expiry() { - var today = DateTime.Today; - var tomorrow = today.AddDays(1); + DateTime today = DateTime.Today; + DateTime tomorrow = today.AddDays(1); - var ttlStrategy = new AbsoluteTtl(tomorrow); + AbsoluteTtl ttlStrategy = new AbsoluteTtl(tomorrow); SystemClock.DateTimeOffsetUtcNow = () => today; ttlStrategy.GetTtl(new Context("someOperationKey"), null).Timespan.Should().Be(TimeSpan.FromDays(1)); @@ -58,4 +58,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/CacheAsyncSpecs.cs b/src/Polly.Specs/Caching/CacheAsyncSpecs.cs index 6982fb80f77..0d6f59c5c9a 100644 --- a/src/Polly.Specs/Caching/CacheAsyncSpecs.cs +++ b/src/Polly.Specs/Caching/CacheAsyncSpecs.cs @@ -56,14 +56,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -78,13 +78,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -96,14 +96,14 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp const string operationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var ttl = TimeSpan.FromMinutes(30); + TimeSpan ttl = TimeSpan.FromMinutes(30); var cache = Policy.CacheAsync(stubCacheProvider, ttl); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func> func = async _ => { delegateInvocations++; @@ -111,13 +111,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp return valueToReturn; }; - var fixedTime = SystemClock.DateTimeOffsetUtcNow(); + DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); delegateInvocations.Should().Be(1); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); @@ -144,13 +144,13 @@ public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_do IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.Zero); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -163,7 +163,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_pri var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; + int delegateInvocations = 0; Func> func = async _ => { delegateInvocations++; @@ -187,12 +187,12 @@ public async Task Should_allow_custom_FuncCacheKeyStrategy() IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); - var person1 = new object(); + object person1 = new object(); await stubCacheProvider.PutAsync("person1", person1, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var person2 = new object(); + object person2 = new object(); await stubCacheProvider.PutAsync("person2", person2, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var funcExecuted = false; + bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new object(); }; (await cache.ExecuteAsync(func, new Context("person", new { id = "1" }.AsDictionary()))).Should().BeSameAs(person1); @@ -212,12 +212,12 @@ public async Task Should_allow_custom_ICacheKeyStrategy() ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); - var person1 = new object(); + object person1 = new object(); await stubCacheProvider.PutAsync("person1", person1, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var person2 = new object(); + object person2 = new object(); await stubCacheProvider.PutAsync("person2", person2, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var funcExecuted = false; + bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new object(); }; (await cache.ExecuteAsync(func, new Context("person", new { id = "1" }.AsDictionary()))).Should().BeSameAs(person1); @@ -240,13 +240,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -255,21 +255,21 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_reference_type() { ResultClass valueToReturnFromCache = default; - var valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); + ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string operationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -284,13 +284,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -299,7 +299,7 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_value_type() { ResultPrimitive valueToReturnFromCache = default; - var valueToReturnFromExecution = ResultPrimitive.Good; + ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); const string operationKey = "SomeOperationKey"; @@ -307,14 +307,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -338,14 +338,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await wrap.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -365,14 +365,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await wrap.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -392,14 +392,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await wrap.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -412,12 +412,12 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_always_execute_delegate_if_execution_key_not_set() { - var valueToReturn = Guid.NewGuid().ToString(); + string valueToReturn = Guid.NewGuid().ToString(); var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; - var func = async () => { + int delegateInvocations = 0; + Func> func = async () => { delegateInvocations++; await TaskHelper.EmptyTask; return valueToReturn; @@ -433,11 +433,11 @@ public async Task Should_always_execute_delegate_if_execution_key_not_set() [Fact] public void Should_always_execute_delegate_if_execution_is_void_returning() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; + int delegateInvocations = 0; Func action = async _ => { delegateInvocations++; await TaskHelper.EmptyTask; }; cache.ExecuteAsync(action, new Context(operationKey)); @@ -459,9 +459,9 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func> func = async (_, _) => { // delegate does not observe cancellation token; test is whether CacheEngine does. @@ -475,8 +475,8 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( tokenSource.Cancel(); - cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) - .Should().Throw(); + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + .Should().ThrowAsync(); delegateInvocations.Should().Be(1); } @@ -489,7 +489,7 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); Func> func = async (_, ct) => { @@ -499,10 +499,10 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p return valueToReturn; }; - cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) - .Should().Throw(); + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + .Should().ThrowAsync(); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } @@ -514,7 +514,7 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p [Fact] public async Task Should_call_onError_delegate_if_cache_get_errors() { - var ex = new Exception(); + Exception ex = new Exception(); IAsyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null); Exception exceptionFromCacheProvider = null; @@ -529,18 +529,18 @@ public async Task Should_call_onError_delegate_if_cache_get_errors() await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; // Even though value is in cache, get will error; so value is returned from execution. (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromExecution); + }, new Context(operationKey))) + .Should().Be(valueToReturnFromExecution); delegateExecuted.Should().BeTrue(); // And error should be captured by onError delegate. @@ -550,7 +550,7 @@ public async Task Should_call_onError_delegate_if_cache_get_errors() [Fact] public async Task Should_call_onError_delegate_if_cache_put_errors() { - var ex = new Exception(); + Exception ex = new Exception(); IAsyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex); Exception exceptionFromCacheProvider = null; @@ -562,7 +562,7 @@ public async Task Should_call_onError_delegate_if_cache_put_errors() var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -572,7 +572,7 @@ public async Task Should_call_onError_delegate_if_cache_put_errors() exceptionFromCacheProvider.Should().Be(ex); // failed to put it in the cache - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -586,7 +586,7 @@ public async Task Should_execute_oncacheget_after_got_from_cache() const string operationKey = "SomeOperationKey"; string keyPassedToDelegate = null; - var contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(operationKey); Context contextPassedToDelegate = null; Action noErrorHandling = (_, _, _) => { }; @@ -597,13 +597,13 @@ public async Task Should_execute_oncacheget_after_got_from_cache() var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, onCacheAction, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, contextToExecute)) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, contextToExecute)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -620,7 +620,7 @@ public async Task Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_ho string keyPassedToOnCacheMiss = null; string keyPassedToOnCachePut = null; - var contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(operationKey); Context contextPassedToOnCacheMiss = null; Context contextPassedToOnCachePut = null; @@ -632,13 +632,13 @@ public async Task Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_ho IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, contextToExecute)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); @@ -655,7 +655,7 @@ public async Task Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_no string keyPassedToOnCacheMiss = null; string keyPassedToOnCachePut = null; - var contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(operationKey); Context contextPassedToOnCacheMiss = null; Context contextPassedToOnCachePut = null; @@ -667,7 +667,7 @@ public async Task Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_no IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.Zero), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); @@ -680,22 +680,22 @@ public async Task Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_no [Fact] public async Task Should_not_execute_oncachemiss_if_dont_query_cache_because_cache_key_not_set() { - var valueToReturn = Guid.NewGuid().ToString(); + string valueToReturn = Guid.NewGuid().ToString(); Action noErrorHandling = (_, _, _) => { }; Action emptyDelegate = (_, _) => { }; - var onCacheMissExecuted = false; + bool onCacheMissExecuted = false; Action onCacheMiss = (_, _) => { onCacheMissExecuted = true; }; var cache = Policy.CacheAsync(new StubCacheProvider(), new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, emptyDelegate, noErrorHandling, noErrorHandling); (await cache.ExecuteAsync(async () => - { - await TaskHelper.EmptyTask; - return valueToReturn; - } /*, no operation key */)) - .Should().Be(valueToReturn); + { + await TaskHelper.EmptyTask; + return valueToReturn; + } /*, no operation key */)) + .Should().Be(valueToReturn); onCacheMissExecuted.Should().BeFalse(); } @@ -706,4 +706,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/CacheSpecs.cs b/src/Polly.Specs/Caching/CacheSpecs.cs index 8e81b9cafa1..bcad643baf9 100644 --- a/src/Polly.Specs/Caching/CacheSpecs.cs +++ b/src/Polly.Specs/Caching/CacheSpecs.cs @@ -53,16 +53,16 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; cache.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -75,15 +75,15 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -95,28 +95,28 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var ttl = TimeSpan.FromMinutes(30); - var cache = Policy.Cache(stubCacheProvider, ttl); + TimeSpan ttl = TimeSpan.FromMinutes(30); + CachePolicy cache = Policy.Cache(stubCacheProvider, ttl); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func func = _ => { delegateInvocations++; return valueToReturn; }; - var fixedTime = SystemClock.DateTimeOffsetUtcNow(); + DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); delegateInvocations.Should().Be(1); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); @@ -141,15 +141,15 @@ public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -160,9 +160,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_exe const string valueToReturn = "valueToReturn"; const string operationKey = "SomeOperationKey"; - var cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; + int delegateInvocations = 0; Func func = _ => { delegateInvocations++; @@ -183,14 +183,14 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_exe public void Should_allow_custom_FuncCacheKeyStrategy() { ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); - var person1 = new object(); + object person1 = new object(); stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue)); - var person2 = new object(); + object person2 = new object(); stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue)); - var funcExecuted = false; + bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new object(); }; cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1); @@ -208,14 +208,14 @@ public void Should_allow_custom_ICacheKeyStrategy() ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); - var cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); + CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); - var person1 = new object(); + object person1 = new object(); stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue)); - var person2 = new object(); + object person2 = new object(); stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue)); - var funcExecuted = false; + bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new object(); }; cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1); @@ -236,15 +236,15 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -253,14 +253,14 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_reference_type() { ResultClass valueToReturnFromCache = default; - var valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); + ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; cache.Execute(_ => { @@ -279,15 +279,15 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -296,15 +296,15 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_value_type() { ResultPrimitive valueToReturnFromCache = default; - var valueToReturnFromExecution = ResultPrimitive.Good; + ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; cache.Execute(_ => { @@ -328,19 +328,19 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); - var wrap = Policy.Wrap(cache, noop); + PolicyWrap wrap = Policy.Wrap(cache, noop); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; wrap.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -354,19 +354,19 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); - var wrap = Policy.Wrap(noop, cache); + PolicyWrap wrap = Policy.Wrap(noop, cache); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; wrap.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -380,19 +380,19 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); - var wrap = Policy.Wrap(noop, cache, noop); + PolicyWrap wrap = Policy.Wrap(noop, cache, noop); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; wrap.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -405,12 +405,12 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_always_execute_delegate_if_execution_key_not_set() { - var valueToReturn = Guid.NewGuid().ToString(); + string valueToReturn = Guid.NewGuid().ToString(); - var cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; - var func = () => + int delegateInvocations = 0; + Func func = () => { delegateInvocations++; return valueToReturn; @@ -426,11 +426,11 @@ public void Should_always_execute_delegate_if_execution_key_not_set() [Fact] public void Should_always_execute_delegate_if_execution_is_void_returning() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; - var cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; + int delegateInvocations = 0; Action action = _ => { delegateInvocations++; }; cache.Execute(action, new Context(operationKey)); @@ -450,11 +450,11 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() const string valueToReturn = "valueToReturn"; const string operationKey = "SomeOperationKey"; - var cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func func = (_, _) => { // delegate does not observe cancellation token; test is whether CacheEngine does. @@ -479,9 +479,9 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); Func func = (_, ct) => { @@ -493,7 +493,7 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token)) .Should().Throw(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(operationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } @@ -505,7 +505,7 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ [Fact] public void Should_call_onError_delegate_if_cache_get_errors() { - var ex = new Exception(); + Exception ex = new Exception(); ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null); Exception exceptionFromCacheProvider = null; @@ -516,11 +516,11 @@ public void Should_call_onError_delegate_if_cache_get_errors() Action onError = (_, _, exc) => { exceptionFromCacheProvider = exc; }; - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; // Even though value is in cache, get will error; so value is returned from execution. @@ -539,7 +539,7 @@ public void Should_call_onError_delegate_if_cache_get_errors() [Fact] public void Should_call_onError_delegate_if_cache_put_errors() { - var ex = new Exception(); + Exception ex = new Exception(); ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex); Exception exceptionFromCacheProvider = null; @@ -549,9 +549,9 @@ public void Should_call_onError_delegate_if_cache_put_errors() Action onError = (_, _, exc) => { exceptionFromCacheProvider = exc; }; - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -561,7 +561,7 @@ public void Should_call_onError_delegate_if_cache_put_errors() exceptionFromCacheProvider.Should().Be(ex); // failed to put it in the cache - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); @@ -576,7 +576,7 @@ public void Should_execute_oncacheget_after_got_from_cache() const string operationKey = "SomeOperationKey"; string keyPassedToDelegate = null; - var contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(operationKey); Context contextPassedToDelegate = null; Action noErrorHandling = (_, _, _) => { }; @@ -584,10 +584,10 @@ public void Should_execute_oncacheget_after_got_from_cache() Action onCacheAction = (ctx, key) => { contextPassedToDelegate = ctx; keyPassedToDelegate = key; }; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, onCacheAction, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); + CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, onCacheAction, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; cache.Execute(_ => { delegateExecuted = true; @@ -609,7 +609,7 @@ public void Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_hold_val string keyPassedToOnCacheMiss = null; string keyPassedToOnCachePut = null; - var contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(operationKey); Context contextPassedToOnCacheMiss = null; Context contextPassedToOnCachePut = null; @@ -619,15 +619,15 @@ public void Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_hold_val Action onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; }; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); + CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, contextToExecute).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); @@ -647,7 +647,7 @@ public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold string keyPassedToOnCacheMiss = null; string keyPassedToOnCachePut = null; - var contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(operationKey); Context contextPassedToOnCacheMiss = null; Context contextPassedToOnCachePut = null; @@ -657,9 +657,9 @@ public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold Action onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; }; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.Zero), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); + CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.Zero), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(operationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); @@ -675,15 +675,15 @@ public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold [Fact] public void Should_not_execute_oncachemiss_if_dont_query_cache_because_cache_key_not_set() { - var valueToReturn = Guid.NewGuid().ToString(); + string valueToReturn = Guid.NewGuid().ToString(); Action noErrorHandling = (_, _, _) => { }; Action emptyDelegate = (_, _) => { }; - var onCacheMissExecuted = false; + bool onCacheMissExecuted = false; Action onCacheMiss = (_, _) => { onCacheMissExecuted = true; }; - var cache = Policy.Cache(new StubCacheProvider(), new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, emptyDelegate, noErrorHandling, noErrorHandling); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, emptyDelegate, noErrorHandling, noErrorHandling); cache.Execute(() => valueToReturn /*, no operation key */).Should().Be(valueToReturn); @@ -696,4 +696,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs b/src/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs index d29202cc882..21aa1bc4f92 100644 --- a/src/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs +++ b/src/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs @@ -55,14 +55,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -77,13 +77,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -95,14 +95,14 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp const string operationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var ttl = TimeSpan.FromMinutes(30); + TimeSpan ttl = TimeSpan.FromMinutes(30); var cache = Policy.CacheAsync(stubCacheProvider, ttl); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func> func = async _ => { delegateInvocations++; @@ -110,14 +110,14 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp return valueToReturn; }; - var fixedTime = SystemClock.DateTimeOffsetUtcNow(); + DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); delegateInvocations.Should().Be(1); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); @@ -144,13 +144,13 @@ public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_do IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.Zero); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -163,7 +163,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_pri var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; + int delegateInvocations = 0; Func> func = async _ => { delegateInvocations++; @@ -192,7 +192,7 @@ public async Task Should_allow_custom_FuncCacheKeyStrategy() object person2 = new ResultClass(ResultPrimitive.Good, "person2"); await stubCacheProvider.PutAsync("person2", person2, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var funcExecuted = false; + bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; (await cache.ExecuteAsync(func, new Context("person", new { id = "1" }.AsDictionary()))).Should().BeSameAs(person1); @@ -218,7 +218,7 @@ public async Task Should_allow_custom_ICacheKeyStrategy() object person2 = new ResultClass(ResultPrimitive.Good, "person2"); await stubCacheProvider.PutAsync("person2", person2, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var funcExecuted = false; + bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; (await cache.ExecuteAsync(func, new Context("person", new { id = "1" }.AsDictionary()))).Should().BeSameAs(person1); @@ -241,13 +241,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -256,21 +256,21 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_reference_type() { ResultClass valueToReturnFromCache = default; - var valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); + ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string operationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -285,13 +285,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -300,7 +300,7 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_value_type() { ResultPrimitive valueToReturnFromCache = default; - var valueToReturnFromExecution = ResultPrimitive.Good; + ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); const string operationKey = "SomeOperationKey"; @@ -308,14 +308,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -339,14 +339,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await wrap.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -366,14 +366,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await wrap.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -393,14 +393,14 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); - var delegateExecuted = false; + bool delegateExecuted = false; (await wrap.ExecuteAsync(async _ => - { - delegateExecuted = true; - await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) + { + delegateExecuted = true; + await TaskHelper.EmptyTask; + return valueToReturnFromExecution; + }, new Context(operationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -413,12 +413,12 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_always_execute_delegate_if_execution_key_not_set() { - var valueToReturn = Guid.NewGuid().ToString(); + string valueToReturn = Guid.NewGuid().ToString(); var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; - var func = async () => { + int delegateInvocations = 0; + Func> func = async () => { delegateInvocations++; await TaskHelper.EmptyTask; return valueToReturn; @@ -443,9 +443,9 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func> func = async (_, _) => { // delegate does not observe cancellation token; test is whether CacheEngine does. @@ -459,8 +459,8 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( tokenSource.Cancel(); - cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) - .Should().Throw(); + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + .Should().ThrowAsync(); delegateInvocations.Should().Be(1); } @@ -473,7 +473,7 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); Func> func = async (_, ct) => { @@ -483,10 +483,10 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p return valueToReturn; }; - cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) - .Should().Throw(); + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + .Should().ThrowAsync(); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } @@ -497,4 +497,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/CacheTResultSpecs.cs b/src/Polly.Specs/Caching/CacheTResultSpecs.cs index 504e1f1127e..161d2916ef2 100644 --- a/src/Polly.Specs/Caching/CacheTResultSpecs.cs +++ b/src/Polly.Specs/Caching/CacheTResultSpecs.cs @@ -52,16 +52,16 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; cache.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -74,15 +74,15 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -94,28 +94,28 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var ttl = TimeSpan.FromMinutes(30); - var cache = Policy.Cache(stubCacheProvider, ttl); + TimeSpan ttl = TimeSpan.FromMinutes(30); + CachePolicy cache = Policy.Cache(stubCacheProvider, ttl); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func func = _ => { delegateInvocations++; return valueToReturn; }; - var fixedTime = SystemClock.DateTimeOffsetUtcNow(); + DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); delegateInvocations.Should().Be(1); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); @@ -140,15 +140,15 @@ public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -159,9 +159,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_exe const string valueToReturn = "valueToReturn"; const string operationKey = "SomeOperationKey"; - var cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; + int delegateInvocations = 0; Func func = _ => { delegateInvocations++; @@ -183,14 +183,14 @@ public void Should_allow_custom_FuncICacheKeyStrategy() { ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); object person1 = new ResultClass(ResultPrimitive.Good, "person1"); stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue)); object person2 = new ResultClass(ResultPrimitive.Good, "person2"); stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue)); - var funcExecuted = false; + bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1); @@ -208,14 +208,14 @@ public void Should_allow_custom_ICacheKeyStrategy() ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); - var cache = Policy.Cache(stubCacheProvider.For(), new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); + CachePolicy cache = Policy.Cache(stubCacheProvider.For(), new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); object person1 = new ResultClass(ResultPrimitive.Good, "person1"); stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue)); object person2 = new ResultClass(ResultPrimitive.Good, "person2"); stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue)); - var funcExecuted = false; + bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1); @@ -236,15 +236,15 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -253,20 +253,20 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_reference_type() { ResultClass valueToReturnFromCache = default; - var valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); + ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; cache.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -279,15 +279,15 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -296,21 +296,21 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_value_type() { ResultPrimitive valueToReturnFromCache = default; - var valueToReturnFromExecution = ResultPrimitive.Good; + ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; cache.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -328,19 +328,19 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); - var wrap = cache.Wrap(noop); + PolicyWrap wrap = cache.Wrap(noop); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; wrap.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -354,19 +354,19 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); - var wrap = noop.Wrap(cache); + PolicyWrap wrap = noop.Wrap(cache); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; wrap.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -380,19 +380,19 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); - var wrap = Policy.Wrap(noop, cache, noop); + PolicyWrap wrap = Policy.Wrap(noop, cache, noop); stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); - var delegateExecuted = false; + bool delegateExecuted = false; wrap.Execute(_ => - { - delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) + { + delegateExecuted = true; + return valueToReturnFromExecution; + }, new Context(operationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -405,12 +405,12 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_always_execute_delegate_if_execution_key_not_set() { - var valueToReturn = Guid.NewGuid().ToString(); + string valueToReturn = Guid.NewGuid().ToString(); - var cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); - var delegateInvocations = 0; - var func = () => + int delegateInvocations = 0; + Func func = () => { delegateInvocations++; return valueToReturn; @@ -433,11 +433,11 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() const string valueToReturn = "valueToReturn"; const string operationKey = "SomeOperationKey"; - var cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); - var delegateInvocations = 0; + int delegateInvocations = 0; Func func = (_, _) => { // delegate does not observe cancellation token; test is whether CacheEngine does. @@ -462,9 +462,9 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - var tokenSource = new CancellationTokenSource(); + CancellationTokenSource tokenSource = new CancellationTokenSource(); Func func = (_, ct) => { @@ -476,7 +476,7 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token)) .Should().Throw(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(operationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } @@ -487,4 +487,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/ContextualTtlSpecs.cs b/src/Polly.Specs/Caching/ContextualTtlSpecs.cs index b9ea3511bb4..a0318b99931 100644 --- a/src/Polly.Specs/Caching/ContextualTtlSpecs.cs +++ b/src/Polly.Specs/Caching/ContextualTtlSpecs.cs @@ -17,22 +17,22 @@ public void Should_return_zero_if_no_value_set_on_context() [Fact] public void Should_return_zero_if_invalid_value_set_on_context() { - var contextData = new Dictionary(); + Dictionary contextData = new Dictionary(); contextData[ContextualTtl.TimeSpanKey] = new object(); - var context = new Context(String.Empty, contextData); + Context context = new Context(String.Empty, contextData); new ContextualTtl().GetTtl(context, null).Timespan.Should().Be(TimeSpan.Zero); } [Fact] public void Should_return_value_set_on_context() { - var ttl = TimeSpan.FromSeconds(30); - var contextData = new Dictionary(); + TimeSpan ttl = TimeSpan.FromSeconds(30); + Dictionary contextData = new Dictionary(); contextData[ContextualTtl.TimeSpanKey] = ttl; - var context = new Context(String.Empty, contextData); - var gotTtl = new ContextualTtl().GetTtl(context, null); + Context context = new Context(String.Empty, contextData); + Ttl gotTtl = new ContextualTtl().GetTtl(context, null); gotTtl.Timespan.Should().Be(ttl); gotTtl.SlidingExpiration.Should().BeFalse(); } @@ -40,13 +40,13 @@ public void Should_return_value_set_on_context() [Fact] public void Should_return_negative_value_set_on_context() { - var ttl = TimeSpan.FromTicks(-1); - var contextData = new Dictionary(); + TimeSpan ttl = TimeSpan.FromTicks(-1); + Dictionary contextData = new Dictionary(); contextData[ContextualTtl.TimeSpanKey] = ttl; - var context = new Context(String.Empty, contextData); - var gotTtl = new ContextualTtl().GetTtl(context, null); + Context context = new Context(String.Empty, contextData); + Ttl gotTtl = new ContextualTtl().GetTtl(context, null); gotTtl.Timespan.Should().Be(ttl); gotTtl.SlidingExpiration.Should().BeFalse(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs b/src/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs index 49badefd935..53b746e66db 100644 --- a/src/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs +++ b/src/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs @@ -9,11 +9,11 @@ public class DefaultCacheKeyStrategySpecs [Fact] public void Should_return_Context_OperationKey_as_cache_key() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; - var context = new Context(operationKey); + Context context = new Context(operationKey); DefaultCacheKeyStrategy.Instance.GetCacheKey(context) .Should().Be(operationKey); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs b/src/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs index 657bfa159c2..2acc731cec2 100644 --- a/src/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs +++ b/src/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs @@ -18,17 +18,17 @@ public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache { const string operationKey = "SomeOperationKey"; - var onErrorCalled = false; + bool onErrorCalled = false; Action onError = (_, _, _) => { onErrorCalled = true; }; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); - var result = await cache.ExecuteAsync(async _ => + ResultPrimitive result = await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ResultPrimitive.Substitute; @@ -46,7 +46,7 @@ public async Task Should_execute_delegate_and_put_value_in_cache_for_non_nullabl IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -56,7 +56,7 @@ public async Task Should_execute_delegate_and_put_value_in_cache_for_non_nullabl return ResultPrimitive.Substitute; }, new Context(operationKey))).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -65,4 +65,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/GenericCacheProviderSpecs.cs b/src/Polly.Specs/Caching/GenericCacheProviderSpecs.cs index 2715a9483b9..19b1c368bd2 100644 --- a/src/Polly.Specs/Caching/GenericCacheProviderSpecs.cs +++ b/src/Polly.Specs/Caching/GenericCacheProviderSpecs.cs @@ -16,17 +16,17 @@ public void Should_not_error_for_executions_on_non_nullable_types_if_cache_does_ { const string operationKey = "SomeOperationKey"; - var onErrorCalled = false; + bool onErrorCalled = false; Action onError = (_, _, _) => { onErrorCalled = true; }; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(operationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); - var result = cache.Execute(_ => ResultPrimitive.Substitute, new Context(operationKey)); + ResultPrimitive result = cache.Execute(_ => ResultPrimitive.Substitute, new Context(operationKey)); onErrorCalled.Should().BeFalse(); } @@ -38,16 +38,16 @@ public void Should_execute_delegate_and_put_value_in_cache_for_non_nullable_type const string operationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (var cacheHit1, var fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); - (var cacheHit2, var fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); @@ -57,4 +57,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/RelativeTtlSpecs.cs b/src/Polly.Specs/Caching/RelativeTtlSpecs.cs index d00443be42f..815834df3a4 100644 --- a/src/Polly.Specs/Caching/RelativeTtlSpecs.cs +++ b/src/Polly.Specs/Caching/RelativeTtlSpecs.cs @@ -35,28 +35,28 @@ public void Should_allow_timespan_max_value() [Fact] public void Should_return_configured_timespan() { - var ttl = TimeSpan.FromSeconds(30); + TimeSpan ttl = TimeSpan.FromSeconds(30); - var ttlStrategy = new RelativeTtl(ttl); + RelativeTtl ttlStrategy = new RelativeTtl(ttl); - var retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); - retrieved.Timespan.Should().BeCloseTo(ttl); + Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); + retrieved.Timespan.Should().BeCloseTo(ttl, TimeSpan.Zero); retrieved.SlidingExpiration.Should().BeFalse(); } [Fact] public void Should_return_configured_timespan_from_time_requested() { - var fixedTime = SystemClock.DateTimeOffsetUtcNow(); - var ttl = TimeSpan.FromSeconds(30); - var delay = TimeSpan.FromSeconds(5); + DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); + TimeSpan ttl = TimeSpan.FromSeconds(30); + TimeSpan delay = TimeSpan.FromSeconds(5); - var ttlStrategy = new RelativeTtl(ttl); + RelativeTtl ttlStrategy = new RelativeTtl(ttl); SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(delay); - var retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); - retrieved.Timespan.Should().BeCloseTo(ttl); + Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); + retrieved.Timespan.Should().BeCloseTo(ttl, TimeSpan.Zero); retrieved.SlidingExpiration.Should().BeFalse(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/ResultTtlSpecs.cs b/src/Polly.Specs/Caching/ResultTtlSpecs.cs index aca14c5acd6..eb2f634a5ed 100644 --- a/src/Polly.Specs/Caching/ResultTtlSpecs.cs +++ b/src/Polly.Specs/Caching/ResultTtlSpecs.cs @@ -42,12 +42,12 @@ public void Should_not_throw_when_func_is_set_using_context() [Fact] public void Should_return_func_result() { - var ttl = TimeSpan.FromMinutes(1); + TimeSpan ttl = TimeSpan.FromMinutes(1); Func func = result => new Ttl(result.Ttl); - var ttlStrategy = new ResultTtl(func); + ResultTtl ttlStrategy = new ResultTtl(func); - var retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), new { Ttl = ttl }); + Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), new { Ttl = ttl }); retrieved.Timespan.Should().Be(ttl); retrieved.SlidingExpiration.Should().BeFalse(); } @@ -57,12 +57,12 @@ public void Should_return_func_result_using_context() { const string specialKey = "specialKey"; - var ttl = TimeSpan.FromMinutes(1); + TimeSpan ttl = TimeSpan.FromMinutes(1); Func func = (context, result) => context.OperationKey == specialKey ? new Ttl(TimeSpan.Zero) : new Ttl(result.Ttl); - var ttlStrategy = new ResultTtl(func); + ResultTtl ttlStrategy = new ResultTtl(func); ttlStrategy.GetTtl(new Context("someOperationKey"), new { Ttl = ttl }).Timespan.Should().Be(ttl); ttlStrategy.GetTtl(new Context(specialKey), new { Ttl = ttl }).Timespan.Should().Be(TimeSpan.Zero); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/SerializingCacheProviderAsyncSpecs.cs b/src/Polly.Specs/Caching/SerializingCacheProviderAsyncSpecs.cs index 7e2d3f2e75d..730baa2f61a 100644 --- a/src/Polly.Specs/Caching/SerializingCacheProviderAsyncSpecs.cs +++ b/src/Polly.Specs/Caching/SerializingCacheProviderAsyncSpecs.cs @@ -16,7 +16,7 @@ public class AsyncSerializingCacheProviderSpecs [Fact] public void Single_generic_constructor_should_throw_on_no_wrapped_cache_provider() { - var stubObjectSerializer = new StubSerializer( + StubSerializer stubObjectSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => s.Original ); @@ -48,21 +48,21 @@ public void Single_generic_extension_syntax_should_throw_on_no_serializer() [Fact] public async Task Single_generic_SerializingCacheProvider_should_serialize_on_put() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + StubCacheProvider stubCacheProvider = new StubCacheProvider(); + object objectToCache = new object(); + string key = "some key"; - var serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); + AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -72,21 +72,21 @@ public async Task Single_generic_SerializingCacheProvider_should_serialize_on_pu [Fact] public async Task Single_generic_SerializingCacheProvider_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); object objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); + AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -96,20 +96,20 @@ public async Task Single_generic_SerializingCacheProvider_should_serialize_on_pu [Fact] public async Task Single_generic_SerializingCacheProvider_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + object objectToCache = new object(); + string key = "some key"; await stubCacheProvider.PutAsync(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); - var serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); - (var cacheHit, var fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); + (bool cacheHit, object fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -119,18 +119,18 @@ public async Task Single_generic_SerializingCacheProvider_should_deserialize_on_ [Fact] public async Task Single_generic_SerializingCacheProvider_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); - var serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); - (var cacheHit, var fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); + (bool cacheHit, object fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -140,21 +140,21 @@ public async Task Single_generic_SerializingCacheProvider_should_not_deserialize [Fact] public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + StubCacheProvider stubCacheProvider = new StubCacheProvider(); + object objectToCache = new object(); + string key = "some key"; - var serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); + AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -164,21 +164,21 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ [Fact] public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); object objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); + AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -188,19 +188,19 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ [Fact] public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + object objectToCache = new object(); + string key = "some key"; await stubCacheProvider.PutAsync(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); - var serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); - (var cacheHit, var fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); + (bool cacheHit, object fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -210,18 +210,18 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ [Fact] public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); - var serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); - (var cacheHit, var fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); + (bool cacheHit, object fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -235,7 +235,7 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ [Fact] public void Double_generic_constructor_should_throw_on_no_wrapped_cache_provider() { - var stubTResultSerializer = new StubSerializer>( + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => s.Original ); @@ -267,21 +267,21 @@ public void Double_generic_extension_syntax_should_throw_on_no_serializer() [Fact] public async Task Double_generic_SerializingCacheProvider_should_serialize_on_put() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); + AsyncSerializingCacheProvider> serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() @@ -291,21 +291,21 @@ public async Task Double_generic_SerializingCacheProvider_should_serialize_on_pu [Fact] public async Task Double_generic_SerializingCacheProvider_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); ResultPrimitive objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); + AsyncSerializingCacheProvider> serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() @@ -315,19 +315,19 @@ public async Task Double_generic_SerializingCacheProvider_should_serialize_on_pu [Fact] public async Task Double_generic_SerializingCacheProvider_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); + AsyncSerializingCacheProvider> serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); await stubCacheProvider.PutAsync(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); - (var cacheHit, object fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -337,18 +337,18 @@ public async Task Double_generic_SerializingCacheProvider_should_deserialize_on_ [Fact] public async Task Double_generic_SerializingCacheProvider_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); - var serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); - (var cacheHit, var fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + AsyncSerializingCacheProvider> serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); + (bool cacheHit, ResultPrimitive fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -358,22 +358,22 @@ public async Task Double_generic_SerializingCacheProvider_should_not_deserialize [Fact] public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = + AsyncSerializingCacheProvider> serializingCacheProvider = stubCacheProvider.AsyncFor>().WithSerializer(stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); + (bool cacheHit, object fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() .Which.Original.Should().Be(objectToCache); @@ -382,23 +382,23 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ [Fact] public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); ResultPrimitive objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = + AsyncSerializingCacheProvider> serializingCacheProvider = stubCacheProvider.AsyncFor>().WithSerializer(stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); - + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); + cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() .Which.Original.Should().Be(objectToCache); @@ -407,20 +407,20 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ [Fact] public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = + AsyncSerializingCacheProvider> serializingCacheProvider = stubCacheProvider.AsyncFor>().WithSerializer(stubTResultSerializer); await stubCacheProvider.PutAsync(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1)), CancellationToken.None, false); - (var cacheHit, var fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + (bool cacheHit, ResultPrimitive fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -430,19 +430,19 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ [Fact] public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); - var serializingCacheProvider = + AsyncSerializingCacheProvider> serializingCacheProvider = stubCacheProvider.AsyncFor>().WithSerializer(stubTResultSerializer); - (var cacheHit, var fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); + (bool cacheHit, ResultPrimitive fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken.None, false); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -450,4 +450,4 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs b/src/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs index 4b2c6c10cb6..28b9627536e 100644 --- a/src/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs +++ b/src/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs @@ -14,12 +14,12 @@ public class SerializingCacheProviderSpecs [Fact] public void Single_generic_constructor_should_throw_on_no_wrapped_cache_provider() { - var stubObjectSerializer = new StubSerializer( + StubSerializer stubObjectSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => s.Original ); - Action configure = () => new SerializingCacheProvider(null, stubObjectSerializer); + Action configure = () => new SerializingCacheProvider(null, stubObjectSerializer); configure.Should().Throw() .And.ParamName.Should().Be("wrappedCacheProvider"); @@ -46,21 +46,21 @@ public void Single_generic_extension_syntax_should_throw_on_no_serializer() [Fact] public void Single_generic_SerializingCacheProvider_should_serialize_on_put() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o);}, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + StubCacheProvider stubCacheProvider = new StubCacheProvider(); + object objectToCache = new object(); + string key = "some key"; - var serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); + SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -70,21 +70,21 @@ public void Single_generic_SerializingCacheProvider_should_serialize_on_put() [Fact] public void Single_generic_SerializingCacheProvider_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); object objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); + SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -94,20 +94,20 @@ public void Single_generic_SerializingCacheProvider_should_serialize_on_put_for_ [Fact] public void Single_generic_SerializingCacheProvider_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + object objectToCache = new object(); + string key = "some key"; stubCacheProvider.Put(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1))); - var serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); - (var cacheHit, var fromCache) = serializingCacheProvider.TryGet(key); + SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); + (bool cacheHit, object fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -117,18 +117,18 @@ public void Single_generic_SerializingCacheProvider_should_deserialize_on_get() [Fact] public void Single_generic_SerializingCacheProvider_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); - var serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); - (var cacheHit, var fromCache) = serializingCacheProvider.TryGet(key); + SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); + (bool cacheHit, object fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -138,21 +138,21 @@ public void Single_generic_SerializingCacheProvider_should_not_deserialize_on_ge [Fact] public void Single_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + StubCacheProvider stubCacheProvider = new StubCacheProvider(); + object objectToCache = new object(); + string key = "some key"; - var serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); + SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -162,21 +162,21 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should [Fact] public void Single_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubSerializer = new StubSerializer( + bool serializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); object objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); + SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType() @@ -186,19 +186,19 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should [Fact] public void Single_generic_SerializingCacheProvider_from_extension_syntax_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = new object(); - var key = "some key"; + object objectToCache = new object(); + string key = "some key"; stubCacheProvider.Put(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1))); - var serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); - (var cacheHit, var fromCache) = serializingCacheProvider.TryGet(key); + SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); + (bool cacheHit, object fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -208,18 +208,18 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should [Fact] public void Single_generic_SerializingCacheProvider_from_extension_syntax_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubSerializer = new StubSerializer( + bool deserializeInvoked = false; + StubSerializer stubSerializer = new StubSerializer( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); - var serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); - (var cacheHit, var fromCache) = serializingCacheProvider.TryGet(key); + SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); + (bool cacheHit, object fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -233,12 +233,12 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should [Fact] public void Double_generic_constructor_should_throw_on_no_wrapped_cache_provider() { - var stubTResultSerializer = new StubSerializer>( - serialize: o => new StubSerialized(o), - deserialize: s => s.Original + StubSerializer> stubTResultSerializer = new StubSerializer>( + serialize: o => new StubSerialized(o), + deserialize: s => s.Original ); - Action configure = () => new SerializingCacheProvider>(null, stubTResultSerializer); + Action configure = () => new SerializingCacheProvider>(null, stubTResultSerializer); configure.Should().Throw() .And.ParamName.Should().Be("wrappedCacheProvider"); @@ -265,21 +265,21 @@ public void Double_generic_extension_syntax_should_throw_on_no_serializer() [Fact] public void Double_generic_SerializingCacheProvider_should_serialize_on_put() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); + SerializingCacheProvider> serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() @@ -289,21 +289,21 @@ public void Double_generic_SerializingCacheProvider_should_serialize_on_put() [Fact] public void Double_generic_SerializingCacheProvider_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); ResultPrimitive objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); + SerializingCacheProvider> serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() @@ -313,19 +313,19 @@ public void Double_generic_SerializingCacheProvider_should_serialize_on_put_for_ [Fact] public void Double_generic_SerializingCacheProvider_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); + SerializingCacheProvider> serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); stubCacheProvider.Put(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1))); - (var cacheHit, object fromCache) = serializingCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -335,18 +335,18 @@ public void Double_generic_SerializingCacheProvider_should_deserialize_on_get() [Fact] public void Double_generic_SerializingCacheProvider_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); - var serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); - (var cacheHit, var fromCache) = serializingCacheProvider.TryGet(key); + SerializingCacheProvider> serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); + (bool cacheHit, ResultPrimitive fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -356,22 +356,22 @@ public void Double_generic_SerializingCacheProvider_should_not_deserialize_on_ge [Fact] public void Double_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = + SerializingCacheProvider> serializingCacheProvider = stubCacheProvider.For>().WithSerializer(stubTResultSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() @@ -381,23 +381,23 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should [Fact] public void Double_generic_SerializingCacheProvider_from_extension_syntax_should_serialize_on_put_for_defaultTResult() { - var serializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool serializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => { serializeInvoked = true; return new StubSerialized(o); }, deserialize: s => s.Original ); - var stubCacheProvider = new StubCacheProvider(); + StubCacheProvider stubCacheProvider = new StubCacheProvider(); ResultPrimitive objectToCache = default; - var key = "some key"; + string key = "some key"; - var serializingCacheProvider = + SerializingCacheProvider> serializingCacheProvider = stubCacheProvider.For>().WithSerializer(stubTResultSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); serializeInvoked.Should().BeTrue(); - (var cacheHit, var fromCache) = stubCacheProvider.TryGet(key); + (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); fromCache.Should().BeOfType>() @@ -407,20 +407,20 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should [Fact] public void Double_generic_SerializingCacheProvider_from_extension_syntax_should_deserialize_on_get() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var objectToCache = ResultPrimitive.Good; - var key = "some key"; + ResultPrimitive objectToCache = ResultPrimitive.Good; + string key = "some key"; - var serializingCacheProvider = + SerializingCacheProvider> serializingCacheProvider = stubCacheProvider.For>().WithSerializer(stubTResultSerializer); stubCacheProvider.Put(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1))); - (var cacheHit, var fromCache) = serializingCacheProvider.TryGet(key); + (bool cacheHit, ResultPrimitive fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeTrue(); deserializeInvoked.Should().BeTrue(); @@ -430,19 +430,19 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should [Fact] public void Double_generic_SerializingCacheProvider_from_extension_syntax_should_not_deserialize_on_get_when_item_not_in_cache() { - var deserializeInvoked = false; - var stubTResultSerializer = new StubSerializer>( + bool deserializeInvoked = false; + StubSerializer> stubTResultSerializer = new StubSerializer>( serialize: o => new StubSerialized(o), deserialize: s => { deserializeInvoked = true; return s.Original; } ); var stubCacheProvider = new StubCacheProvider(); - var key = "some key"; + string key = "some key"; stubCacheProvider.TryGet(key).Item2.Should().BeNull(); - var serializingCacheProvider = + SerializingCacheProvider> serializingCacheProvider = stubCacheProvider.For>().WithSerializer(stubTResultSerializer); - (var cacheHit, var fromCache) = serializingCacheProvider.TryGet(key); + (bool cacheHit, ResultPrimitive fromCache) = serializingCacheProvider.TryGet(key); cacheHit.Should().BeFalse(); deserializeInvoked.Should().BeFalse(); @@ -450,4 +450,4 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Caching/SlidingTtlSpecs.cs b/src/Polly.Specs/Caching/SlidingTtlSpecs.cs index 2bd32116264..5539b9361f4 100644 --- a/src/Polly.Specs/Caching/SlidingTtlSpecs.cs +++ b/src/Polly.Specs/Caching/SlidingTtlSpecs.cs @@ -34,12 +34,12 @@ public void Should_allow_timespan_max_value() [Fact] public void Should_return_configured_timespan() { - var ttl = TimeSpan.FromSeconds(30); + TimeSpan ttl = TimeSpan.FromSeconds(30); - var ttlStrategy = new SlidingTtl(ttl); + SlidingTtl ttlStrategy = new SlidingTtl(ttl); - var retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); + Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); retrieved.Timespan.Should().Be(ttl); retrieved.SlidingExpiration.Should().BeTrue(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs b/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs index f1fe5bc5783..a0cf44c38c6 100644 --- a/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs @@ -19,14 +19,14 @@ public class AdvancedCircuitBreakerAsyncSpecs : IDisposable #region Configuration tests [Fact] - public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() + public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() { var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.MaxValue); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] @@ -170,7 +170,7 @@ public void Should_initialise_to_closed_state() // These provide easy values for testing for failure and throughput thresholds each being met and non-met, in combination. [Fact] - public void Should_not_open_circuit_if_failure_threshold_and_minimum_threshold_is_equalled_but_last_call_is_success() + public async Task Should_not_open_circuit_if_failure_threshold_and_minimum_threshold_is_equalled_but_last_call_is_success() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -185,28 +185,28 @@ public void Should_not_open_circuit_if_failure_threshold_and_minimum_threshold_i ); // Three of three actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Failure threshold exceeded, but throughput threshold not yet. // Throughput threshold will be exceeded by the below successful call, but we never break on a successful call; hence don't break on this. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice } [Fact] - public void Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_specified_exceptions() + public async Task Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_specified_exceptions() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -222,20 +222,20 @@ public void Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_spec ); // Four of four actions in this test throw unhandled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -250,7 +250,7 @@ public void Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_spec // These provide easy values for testing for failure and throughput thresholds each being met and non-met, in combination. [Fact] - public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_same_window() + public async Task Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_same_window() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -265,36 +265,36 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + bool delegateExecutedWhenBroken = false; + var ex = await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); delegateExecutedWhenBroken.Should().BeFalse(); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_different_windows() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -311,16 +311,16 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later @@ -328,20 +328,20 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh // They are still placed within same timeslice. SystemClock.UtcNow = () => time.AddSeconds(samplingDuration.Seconds / 2d + 1); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_same_window() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_same_window() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -356,33 +356,33 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Three of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_different_windows() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -399,20 +399,20 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Three of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later @@ -420,16 +420,16 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh // They are still placed within same timeslice SystemClock.UtcNow = () => time.AddSeconds(samplingDuration.Seconds / 2d + 1); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_same_window() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_same_window() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -444,33 +444,33 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Two of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_different_windows() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -487,20 +487,20 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Two of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later @@ -508,16 +508,16 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh // They are still placed within same timeslice SystemClock.UtcNow = () => time.AddSeconds(samplingDuration.Seconds / 2d + 1); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires() + public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -534,29 +534,29 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput ); // Four of four actions in this test throw handled failures; but only the first three within the timeslice. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Adjust SystemClock so that timeslice (clearly) expires; fourth exception thrown in next-recorded timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration).Add(samplingDuration); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly() + public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -573,29 +573,29 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput ); // Four of four actions in this test throw handled failures; but only the first three within the timeslice. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_error_occurring_just_at_the_end_of_the_duration() + public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_error_occurring_just_at_the_end_of_the_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -614,32 +614,32 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput // Four of four actions in this test throw handled failures; but only the first three within the original timeslice. // Two actions at the start of the original timeslice. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Creates a new window right at the end of the original timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. If timeslice/window rollover is precisely defined, this should cause first two actions to be forgotten from statistics (rolled out of the window of relevance), and thus the circuit not to break. SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -656,35 +656,35 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Adjust SystemClock so that timeslice doesn't quite expire; fourth exception thrown in same timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met() + public async Task Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -699,22 +699,22 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_ ); // One of three actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice } [Fact] - public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires() + public async Task Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -729,26 +729,26 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_ ); // One of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice } [Fact] - public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold() + public async Task Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -766,8 +766,8 @@ public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failu // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring @@ -775,16 +775,16 @@ public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failu SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Three of four actions in this test occur within the first timeslice. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Setting the time to just barely into the new timeslice @@ -793,13 +793,13 @@ public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failu // This failure opens the circuit, because it is the second failure of four calls // equalling the failure threshold. The minimum threshold within the defined // sampling duration is met, when using rolling windows. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_failures_in_beginning_of_new_timeslice_when_below_minimum_throughput_threshold() + public async Task Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_failures_in_beginning_of_new_timeslice_when_below_minimum_throughput_threshold() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -817,8 +817,8 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_fai // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring @@ -826,12 +826,12 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_fai SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Two of three actions in this test occur within the first timeslice. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Setting the time to just barely into the new timeslice @@ -840,13 +840,13 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_fai // A third failure occurs just at the beginning of the new timeslice making // the number of failures above the failure threshold. However, the throughput is // below the minimum threshold as to open the circuit. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_open_circuit_if_failures_in_second_window_of_last_timeslice_and_failures_in_first_window_in_next_timeslice_exceeds_failure_threshold_and_minimum_threshold() + public async Task Should_open_circuit_if_failures_in_second_window_of_last_timeslice_and_failures_in_first_window_in_next_timeslice_exceeds_failure_threshold_and_minimum_threshold() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -865,31 +865,31 @@ public void Should_open_circuit_if_failures_in_second_window_of_last_timeslice_a // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Setting the time to the second window in the rolling metrics SystemClock.UtcNow = () => time.AddSeconds(samplingDuration.Seconds / (double)numberOfWindowsDefinedInCircuitBreaker); // Three actions occur in the second window of the first timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); } @@ -904,7 +904,7 @@ public void Should_open_circuit_if_failures_in_second_window_of_last_timeslice_a // These provide easy values for testing for failure and throughput thresholds each being met and non-met, in combination. [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -919,34 +919,34 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -961,33 +961,33 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Three of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1002,33 +1002,33 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Two of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_low_sampling_duration() + public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1045,29 +1045,29 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput ); // Four of four actions in this test throw handled failures; but only the first within the timeslice. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Adjust SystemClock so that timeslice (clearly) expires; fourth exception thrown in next-recorded timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration).Add(samplingDuration); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly_low_sampling_duration() + public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1084,29 +1084,29 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput ); // Two of four actions in this test throw handled failures; but only the first within the timeslice. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice_low_sampling_duration() + public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1123,35 +1123,35 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Adjust SystemClock so that timeslice doesn't quite expire; fourth exception thrown in same timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met_low_sampling_duration() + public async Task Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1166,22 +1166,22 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_ ); // One of three actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice } [Fact] - public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires_low_sampling_duration() + public async Task Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1196,26 +1196,26 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_ ); // One of four actions in this test throw handled failures. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice } [Fact] - public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold_low_sampling_duration() + public async Task Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold_low_sampling_duration() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1233,8 +1233,8 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_f // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring @@ -1242,16 +1242,16 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_f SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Three of four actions in this test occur within the first timeslice. - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Setting the time to just barely into the new timeslice @@ -1259,8 +1259,8 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_f // This failure does not open the circuit, because a new duration should have // started and with such low sampling duration, windows should not be used. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -1271,7 +1271,7 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_f #region Circuit-breaker open->half-open->open/closed tests [Fact] - public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_same_window() + public async Task Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_same_window() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1288,20 +1288,20 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1309,12 +1309,12 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_different_windows() + public async Task Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_different_windows() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1332,16 +1332,16 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later @@ -1350,8 +1350,8 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with var anotherWindowDuration = samplingDuration.Seconds / 2d + 1; SystemClock.UtcNow = () => time.AddSeconds(anotherWindowDuration); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1364,12 +1364,12 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() + public async Task Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1386,20 +1386,20 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1409,11 +1409,11 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if breaker.CircuitState.Should().Be(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should open again - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } @@ -1435,20 +1435,20 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1463,7 +1463,7 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i } [Fact] - public void Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() + public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1478,10 +1478,10 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ durationOfBreak: durationOfBreak ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1501,7 +1501,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ } [Fact] - public void Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() + public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1516,10 +1516,10 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ durationOfBreak: durationOfBreak ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1547,7 +1547,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ } [Fact] - public void Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() + public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1562,10 +1562,10 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ durationOfBreak: durationOfBreak ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exceptions raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1577,19 +1577,19 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(async () => { - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -1602,7 +1602,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ await TaskHelper.EmptyTask; firstExecutionActive = false; - })).Should().NotThrow(); + })).Should().NotThrowAsync(); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -1653,7 +1653,7 @@ await breaker.ExecuteAsync(async () => } [Fact] - public void Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() + public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1668,10 +1668,10 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ durationOfBreak: durationOfBreak ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1684,19 +1684,19 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. // The second execution should be accepted in the halfopen state due to being requested after one breakDuration later. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(async () => { - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -1708,7 +1708,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); await TaskHelper.EmptyTask; firstExecutionActive = false; - })).Should().NotThrow(); + })).Should().NotThrowAsync(); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -1765,7 +1765,7 @@ await breaker.ExecuteAsync(async () => #region Isolate and reset tests [Fact] - public void Should_open_circuit_and_block_calls_if_manual_override_open() + public async Task Should_open_circuit_and_block_calls_if_manual_override_open() { var breaker = Policy .Handle() @@ -1777,16 +1777,16 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() breaker.CircuitState.Should().Be(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().Throw(); + bool delegateExecutedWhenBroken = false; + await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Isolated); breaker.LastException.Should().BeOfType(); delegateExecutedWhenBroken.Should().BeFalse(); } [Fact] - public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() + public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1803,14 +1803,14 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope SystemClock.UtcNow = () => time.Add(durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Isolated); - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().Throw(); + bool delegateExecutedWhenBroken = false; + await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) + .Should().ThrowAsync(); delegateExecutedWhenBroken.Should().BeFalse(); } [Fact] - public void Should_close_circuit_again_on_reset_after_manual_override() + public async Task Should_close_circuit_again_on_reset_after_manual_override() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1823,17 +1823,17 @@ public void Should_close_circuit_again_on_reset_after_manual_override() breaker.Isolate(); breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().ThrowAsync(); breaker.Reset(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); } [Fact] - public void Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() + public async Task Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1850,28 +1850,28 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); SystemClock.UtcNow().Should().Be(time); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); } #endregion @@ -1882,8 +1882,8 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi public void Should_not_call_onreset_on_initialise() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; var durationOfBreak = TimeSpan.FromSeconds(30); Policy @@ -1894,11 +1894,11 @@ public void Should_not_call_onreset_on_initialise() } [Fact] - public void Should_call_onbreak_when_breaking_circuit_automatically() + public async Task Should_call_onbreak_when_breaking_circuit_automatically() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1915,22 +1915,22 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().BeTrue(); @@ -1939,9 +1939,9 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var durationOfBreak = TimeSpan.FromSeconds(30); var breaker = Policy @@ -1956,11 +1956,11 @@ public void Should_call_onbreak_when_breaking_circuit_manually() } [Fact] - public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() + public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1977,43 +1977,43 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); // call through circuit when already broken - should not retrigger onBreak - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); } [Fact] - public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() + public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy .Handle() @@ -2027,29 +2027,29 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub ); // Start an execution when the breaker is in the closed state, but hold it from returning (its failure) until the breaker has opened. This call, a failure hitting an already open breaker, should indicate its fail, but should not cause onBreak() to be called a second time. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) - using (var permitMainThreadToOpenCircuit = new ManualResetEvent(false)) + using (ManualResetEvent permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) + using (ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false)) { - var longRunningExecution = Task.Factory.StartNew(() => + Task longRunningExecution = Task.Factory.StartNew(async () => { breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { await TaskHelper.EmptyTask; permitMainThreadToOpenCircuit.Set(); - // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). - permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); + // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). + permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); - // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + // Throw a further failure when rest of test has already broken the circuit. + breaker.CircuitState.Should().Be(CircuitState.Open); throw new DivideByZeroException(); - })).Should().Throw(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + })).Should().ThrowAsync(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. }, TaskCreationOptions.LongRunning); permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); @@ -2057,10 +2057,10 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub // Break circuit in the normal manner: onBreak() should be called once. breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -2081,10 +2081,10 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub [Fact] public async Task Should_call_onreset_when_automatically_closing_circuit_but_not_when_halfopen() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -2103,22 +2103,22 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -2140,8 +2140,8 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not public async Task Should_not_call_onreset_on_successive_successful_calls() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; var durationOfBreak = TimeSpan.FromSeconds(30); var breaker = Policy @@ -2162,12 +2162,12 @@ public async Task Should_not_call_onreset_on_successive_successful_calls() [Fact] public async Task Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -2187,25 +2187,25 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -2222,14 +2222,14 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal } [Fact] - public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() + public async Task Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -2249,25 +2249,25 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -2279,12 +2279,12 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ } [Fact] - public void Should_call_onreset_when_manually_resetting_circuit() + public async Task Should_call_onreset_when_manually_resetting_circuit() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -2299,22 +2299,22 @@ public void Should_call_onreset_when_manually_resetting_circuit() onBreakCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().ThrowAsync(); onResetCalled.Should().Be(0); breaker.Reset(); onResetCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().NotThrowAsync(); } #region Tests of supplied parameters to onBreak delegate [Fact] - public void Should_call_onbreak_with_the_last_raised_exception() + public async Task Should_call_onbreak_with_the_last_raised_exception() { Exception passedException = null; @@ -2333,35 +2333,35 @@ public void Should_call_onbreak_with_the_last_raised_exception() ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); passedException?.Should().BeOfType(); } [Fact] - public void Should_call_onbreak_with_a_state_of_closed() + public async Task Should_call_onbreak_with_a_state_of_closed() { CircuitState? transitionedState = null; Action onBreak = (_, state, _, _) => { transitionedState = state; }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; var breaker = Policy .Handle() @@ -2375,35 +2375,35 @@ public void Should_call_onbreak_with_a_state_of_closed() onHalfOpen: onHalfOpen ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); transitionedState?.Should().Be(CircuitState.Closed); } [Fact] - public void Should_call_onbreak_with_a_state_of_half_open() + public async Task Should_call_onbreak_with_a_state_of_half_open() { - var transitionedStates = new List(); + List transitionedStates = new List(); Action onBreak = (_, state, _, _) => { transitionedStates.Add(state); }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -2423,20 +2423,20 @@ public void Should_call_onbreak_with_a_state_of_half_open() ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -2446,25 +2446,25 @@ public void Should_call_onbreak_with_a_state_of_half_open() breaker.CircuitState.Should().Be(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should open again - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); transitionedStates[0].Should().Be(CircuitState.Closed); transitionedStates[1].Should().Be(CircuitState.HalfOpen); } [Fact] - public void Should_call_onbreak_with_the_correct_timespan() + public async Task Should_call_onbreak_with_the_correct_timespan() { TimeSpan? passedBreakTimespan = null; Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() @@ -2478,22 +2478,22 @@ public void Should_call_onbreak_with_the_correct_timespan() ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); passedBreakTimespan.Should().Be(durationOfBreak); @@ -2533,7 +2533,7 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() #region Tests that supplied context is passed to stage-change delegates [Fact] - public void Should_call_onbreak_with_the_passed_context() + public async Task Should_call_onbreak_with_the_passed_context() { IDictionary contextData = null; @@ -2555,21 +2555,21 @@ public void Should_call_onbreak_with_the_passed_context() ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync( + await breaker.Awaiting(x => x.RaiseExceptionAsync( new { key1 = "value1", key2 = "value2" }.AsDictionary() - )).Should().Throw(); + )).Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); contextData.Should() @@ -2602,20 +2602,20 @@ public async Task Should_call_onreset_with_the_passed_context() ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -2633,9 +2633,9 @@ public async Task Should_call_onreset_with_the_passed_context() } [Fact] - public void Context_should_be_empty_if_execute_not_called_with_any_context_data() + public async Task Context_should_be_empty_if_execute_not_called_with_any_context_data() { - var contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); + IDictionary contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); Action onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; @@ -2655,20 +2655,20 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -2702,20 +2702,20 @@ public async Task Should_create_new_context_for_each_call_to_execute() ); // Four of four actions in this test throw handled failures. - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync(new { key = "original_value" }.AsDictionary())) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync(new { key = "original_value" }.AsDictionary())) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); contextValue.Should().Be("original_value"); @@ -2754,7 +2754,7 @@ public void Should_initialise_LastException_to_null_on_creation() } [Fact] - public void Should_set_LastException_on_handling_exception_even_when_not_breaking() + public async Task Should_set_LastException_on_handling_exception_even_when_not_breaking() { var breaker = Policy .Handle() @@ -2765,15 +2765,15 @@ public void Should_set_LastException_on_handling_exception_even_when_not_breakin durationOfBreak: TimeSpan.FromSeconds(30) ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.LastException.Should().BeOfType(); } [Fact] - public void Should_set_LastException_to_last_raised_exception_when_breaking() + public async Task Should_set_LastException_to_last_raised_exception_when_breaking() { var breaker = Policy .Handle() @@ -2784,19 +2784,19 @@ public void Should_set_LastException_to_last_raised_exception_when_breaking() durationOfBreak: TimeSpan.FromSeconds(30) ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.LastException.Should().BeOfType(); } [Fact] - public void Should_set_LastException_to_null_on_circuit_reset() + public async Task Should_set_LastException_to_null_on_circuit_reset() { var breaker = Policy .Handle() @@ -2807,12 +2807,12 @@ public void Should_set_LastException_to_null_on_circuit_reset() durationOfBreak: TimeSpan.FromSeconds(30) ); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.LastException.Should().BeOfType(); @@ -2827,45 +2827,45 @@ public void Should_set_LastException_to_null_on_circuit_reset() #region Cancellation support [Fact] - public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -2873,139 +2873,139 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_faulting_from_faulting_action_execution_when_user_delegate_does_not_observe_cancellation() + public async Task Should_report_faulting_from_faulting_action_execution_when_user_delegate_does_not_observe_cancellation() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_when_both_open_circuit_and_cancellation() + public async Task Should_report_cancellation_when_both_open_circuit_and_cancellation() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 2, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); // Circuit is now broken. - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; cancellationTokenSource.Cancel(); - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, // Cancelled manually instead - see above. ActionObservesCancellation = false }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex2 = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex2.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_honour_different_cancellationToken_captured_implicitly_by_action() + public async Task Should_honour_different_cancellationToken_captured_implicitly_by_action() { // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish TaskCanceledExceptions thrown with different CancellationTokens. @@ -3014,53 +3014,54 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var policyCancellationTokenSource = new CancellationTokenSource(); - var policyCancellationToken = policyCancellationTokenSource.Token; + CancellationTokenSource policyCancellationTokenSource = new CancellationTokenSource(); + CancellationToken policyCancellationToken = policyCancellationTokenSource.Token; - var implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); - var implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; + CancellationTokenSource implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); + CancellationToken implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; implicitlyCapturedActionCancellationTokenSource.Cancel(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; - breaker.Awaiting(x => x.ExecuteAsync(async _ => - { - attemptsInvoked++; - await TaskHelper.EmptyTask; - implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - }, policyCancellationToken)) - .Should().Throw() - .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + var ex = await breaker.Awaiting(x => x.ExecuteAsync(async _ => + { + attemptsInvoked++; + await TaskHelper.EmptyTask; + implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); + }, policyCancellationToken)) + .Should().ThrowAsync(); + + ex.And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() + public async Task Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - breaker.Awaiting(action) - .Should().NotThrow(); + await breaker.Awaiting(action) + .Should().NotThrowAsync(); result.Should().BeTrue(); @@ -3068,22 +3069,22 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance } [Fact] - public void Should_honour_and_report_cancellation_during_func_execution() + public async Task Should_honour_and_report_cancellation_during_func_execution() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -3091,8 +3092,9 @@ public void Should_honour_and_report_cancellation_during_func_execution() }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - breaker.Awaiting(action) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(action) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); result.Should().Be(null); @@ -3105,4 +3107,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs b/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs index 1168916f35d..3504018b616 100644 --- a/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs @@ -13,6 +13,7 @@ namespace Polly.Specs.CircuitBreaker; + [Collection(Constants.SystemClockDependentTestCollection)] public class AdvancedCircuitBreakerSpecs : IDisposable { @@ -21,7 +22,7 @@ public class AdvancedCircuitBreakerSpecs : IDisposable [Fact] public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.MaxValue); @@ -150,7 +151,7 @@ public void Should_be_able_to_handle_a_duration_of_break_of_zero() [Fact] public void Should_initialise_to_closed_state() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); @@ -175,7 +176,7 @@ public void Should_not_open_circuit_if_failure_threshold_and_minimum_threshold_i var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -211,7 +212,7 @@ public void Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_spec var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .Or() .AdvancedCircuitBreaker( @@ -255,7 +256,7 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -283,7 +284,7 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) .Should().Throw() .WithMessage("The circuit is now open and is not allowing calls.") @@ -301,7 +302,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -346,7 +347,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -389,7 +390,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -434,7 +435,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -477,7 +478,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -524,7 +525,7 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -563,7 +564,7 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -602,7 +603,7 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -646,7 +647,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -689,7 +690,7 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_ var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -719,7 +720,7 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_ var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -755,7 +756,7 @@ public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failu var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -806,7 +807,7 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_fai var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -854,7 +855,7 @@ public void Should_open_circuit_if_failures_in_second_window_of_last_timeslice_a var samplingDuration = TimeSpan.FromSeconds(10); var numberOfWindowsDefinedInCircuitBreaker = 10; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -909,7 +910,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -951,7 +952,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -992,7 +993,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1035,7 +1036,7 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput var samplingDuration = TimeSpan.FromMilliseconds(199); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1074,7 +1075,7 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput var samplingDuration = TimeSpan.FromMilliseconds(199); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1113,7 +1114,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh var samplingDuration = TimeSpan.FromMilliseconds(199); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1156,7 +1157,7 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_ var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1186,7 +1187,7 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_ var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1222,7 +1223,7 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_f var samplingDuration = TimeSpan.FromMilliseconds(199); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1278,7 +1279,7 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1322,7 +1323,7 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with var durationOfBreak = TimeSpan.FromSeconds(30); var samplingDuration = TimeSpan.FromSeconds(10); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1376,7 +1377,7 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1412,7 +1413,7 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if breaker.Invoking(x => x.RaiseException()) .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); - + } [Fact] @@ -1423,7 +1424,7 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1468,7 +1469,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1507,7 +1508,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1554,7 +1555,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1578,17 +1579,17 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(() => { breaker.Invoking(x => x.Execute(() => { @@ -1608,7 +1609,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks); - var secondExecution = Task.Factory.StartNew(() => + Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). firstExecutionActive.Should().BeTrue(); @@ -1659,7 +1660,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1684,17 +1685,17 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. // The second execution should be accepted in the halfopen state due to being requested after one breakDuration later. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(() => { breaker.Invoking(x => x.Execute(() => { @@ -1714,7 +1715,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks); - var secondExecution = Task.Factory.StartNew(() => + Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). firstExecutionActive.Should().BeTrue(); @@ -1765,7 +1766,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ [Fact] public void Should_open_circuit_and_block_calls_if_manual_override_open() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -1775,7 +1776,7 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() breaker.CircuitState.Should().Be(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Isolated); @@ -1790,7 +1791,7 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -1801,7 +1802,7 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope SystemClock.UtcNow = () => time.Add(durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Isolated); - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) .Should().Throw(); delegateExecutedWhenBroken.Should().BeFalse(); @@ -1814,7 +1815,7 @@ public void Should_close_circuit_again_on_reset_after_manual_override() SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -1837,7 +1838,7 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1878,8 +1879,8 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi public void Should_not_call_onreset_on_initialise() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; var durationOfBreak = TimeSpan.FromSeconds(30); Policy @@ -1892,14 +1893,14 @@ public void Should_not_call_onreset_on_initialise() [Fact] public void Should_call_onbreak_when_breaking_circuit_automatically() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -1935,12 +1936,12 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); @@ -1954,14 +1955,14 @@ public void Should_call_onbreak_when_breaking_circuit_manually() [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2007,11 +2008,11 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2023,11 +2024,11 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub ); // Start an execution when the breaker is in the closed state, but hold it from returning (its failure) until the breaker has opened. This call, a failure hitting an already open breaker, should indicate its fail, but should not cause onBreak() to be called a second time. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) - using (var permitMainThreadToOpenCircuit = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) + using (ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false)) { - var longRunningExecution = Task.Factory.StartNew(() => + Task longRunningExecution = Task.Factory.StartNew(() => { breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -2035,11 +2036,11 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub { permitMainThreadToOpenCircuit.Set(); - // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). - permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); + // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). + permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); - // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + // Throw a further failure when rest of test has already broken the circuit. + breaker.CircuitState.Should().Be(CircuitState.Open); throw new DivideByZeroException(); })).Should().Throw(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. @@ -2074,17 +2075,17 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub [Fact] public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_halfopen() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2133,11 +2134,11 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ public void Should_not_call_onreset_on_successive_successful_calls() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); @@ -2155,19 +2156,19 @@ public void Should_not_call_onreset_on_successive_successful_calls() [Fact] public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2217,19 +2218,19 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ [Fact] public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2274,16 +2275,16 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ [Fact] public void Should_call_onreset_when_manually_resetting_circuit() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); @@ -2313,7 +2314,7 @@ public void Should_call_onbreak_with_the_last_raised_exception() Action onBreak = (exception, _, _) => { passedException = exception; }; Action onReset = _ => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2350,9 +2351,9 @@ public void Should_call_onbreak_with_a_state_of_closed() Action onBreak = (_, state, _, _) => { transitionedState = state; }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2386,18 +2387,18 @@ public void Should_call_onbreak_with_a_state_of_closed() [Fact] public void Should_call_onbreak_with_a_state_of_half_open() { - var transitionedStates = new List(); + List transitionedStates = new List(); Action onBreak = (_, state, _, _) => { transitionedStates.Add(state); }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2449,9 +2450,9 @@ public void Should_call_onbreak_with_the_correct_timespan() Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromSeconds(30); + TimeSpan durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2490,8 +2491,8 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() var time = 1.January(2000); SystemClock.UtcNow = () => time; - - var breaker = Policy + + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2525,7 +2526,7 @@ public void Should_call_onbreak_with_the_passed_context() var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2551,7 +2552,7 @@ public void Should_call_onbreak_with_the_passed_context() breaker.Invoking(x => x.RaiseException( new { key1 = "value1", key2 = "value2" }.AsDictionary() - )).Should().Throw(); + )).Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); contextData.Should() @@ -2572,7 +2573,7 @@ public void Should_call_onreset_with_the_passed_context() var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2617,7 +2618,7 @@ public void Should_call_onreset_with_the_passed_context() [Fact] public void Context_should_be_empty_if_execute_not_called_with_any_context_data() { - var contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); + IDictionary contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); Action onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; @@ -2625,7 +2626,7 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( var time = 1.January(2000); SystemClock.UtcNow = () => time; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2672,7 +2673,7 @@ public void Should_create_new_context_for_each_call_to_execute() var durationOfBreak = TimeSpan.FromSeconds(30); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2722,7 +2723,7 @@ public void Should_create_new_context_for_each_call_to_execute() [Fact] public void Should_initialise_LastException_to_null_on_creation() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2737,7 +2738,7 @@ public void Should_initialise_LastException_to_null_on_creation() [Fact] public void Should_set_LastException_on_handling_exception_even_when_not_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2756,7 +2757,7 @@ public void Should_set_LastException_on_handling_exception_even_when_not_breakin [Fact] public void Should_set_LastException_to_last_raised_exception_when_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2779,7 +2780,7 @@ public void Should_set_LastException_to_last_raised_exception_when_breaking() [Fact] public void Should_set_LastException_to_null_on_circuit_reset() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker( failureThreshold: 0.5, @@ -2811,16 +2812,16 @@ public void Should_set_LastException_to_null_on_circuit_reset() public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, @@ -2836,17 +2837,17 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -2865,17 +2866,17 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -2893,17 +2894,17 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec public void Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, @@ -2921,16 +2922,16 @@ public void Should_report_cancellation_during_faulting_action_execution_when_use public void Should_report_faulting_from_faulting_action_execution_when_user_delegate_does_not_observe_cancellation() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, @@ -2947,7 +2948,7 @@ public void Should_report_faulting_from_faulting_action_execution_when_user_dele public void Should_report_cancellation_when_both_open_circuit_and_cancellation() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 2, durationOfBreak); @@ -2963,15 +2964,15 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() .WithInnerException(); // Circuit is now broken. - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; cancellationTokenSource.Cancel(); - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, // Cancelled manually instead - see above. @@ -2991,25 +2992,25 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish OperationCanceledExceptions thrown with different CancellationTokens. var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var policyCancellationTokenSource = new CancellationTokenSource(); - var policyCancellationToken = policyCancellationTokenSource.Token; + CancellationTokenSource policyCancellationTokenSource = new CancellationTokenSource(); + CancellationToken policyCancellationToken = policyCancellationTokenSource.Token; - var implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); - var implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; + CancellationTokenSource implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); + CancellationToken implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; implicitlyCapturedActionCancellationTokenSource.Cancel(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; breaker.Invoking(x => x.Execute(_ => - { - attemptsInvoked++; - implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - }, policyCancellationToken)) + { + attemptsInvoked++; + implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); + }, policyCancellationToken)) .Should().Throw() .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); @@ -3020,19 +3021,19 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, @@ -3050,19 +3051,19 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance public void Should_honour_and_report_cancellation_during_func_execution() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -3084,4 +3085,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs b/src/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs index 30d6ce0e0f1..4b1fe9dec51 100644 --- a/src/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs @@ -19,34 +19,34 @@ public class CircuitBreakerAsyncSpecs : IDisposable #region Configuration tests [Fact] - public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() + public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() { var breaker = Policy - .Handle() - .CircuitBreakerAsync(1, TimeSpan.MaxValue); + .Handle() + .CircuitBreakerAsync(1, TimeSpan.MaxValue); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] public void Should_throw_if_exceptions_allowed_before_breaking_is_less_than_one() { - Action action = () => Policy - .Handle() - .CircuitBreakerAsync(0, TimeSpan.FromSeconds(10)); + Action action = () => Policy + .Handle() + .CircuitBreakerAsync(0, TimeSpan.FromSeconds(10)); action.Should().Throw() - .And.ParamName.Should() - .Be("exceptionsAllowedBeforeBreaking"); + .And.ParamName.Should() + .Be("exceptionsAllowedBeforeBreaking"); } [Fact] public void Should_throw_if_duration_of_break_is_less_than_zero() { Action action = () => Policy - .Handle() - .CircuitBreakerAsync(1, -TimeSpan.FromSeconds(1)); + .Handle() + .CircuitBreakerAsync(1, -TimeSpan.FromSeconds(1)); action.Should().Throw() .And.ParamName.Should() @@ -57,8 +57,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() public void Should_be_able_to_handle_a_duration_of_break_of_zero() { Action action = () => Policy - .Handle() - .CircuitBreakerAsync(1, TimeSpan.Zero); + .Handle() + .CircuitBreakerAsync(1, TimeSpan.Zero); action.Should().NotThrow(); } @@ -79,113 +79,113 @@ public void Should_initialise_to_closed_state() #region Circuit-breaker threshold-to-break tests [Fact] - public void Should_not_open_circuit_if_specified_number_of_specified_exception_are_not_raised_consecutively() + public async Task Should_not_open_circuit_if_specified_number_of_specified_exception_are_not_raised_consecutively() { var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(b => b.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrow(); + await breaker.Awaiting(b => b.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_after_specified_number_of_specified_exception_have_been_raised() + public async Task Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_after_specified_number_of_specified_exception_have_been_raised() { var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + bool delegateExecutedWhenBroken = false; + var ex = await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); delegateExecutedWhenBroken.Should().BeFalse(); } [Fact] - public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_after_specified_number_of_one_of_the_specified_exceptions_have_been_raised() + public async Task Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_after_specified_number_of_one_of_the_specified_exceptions_have_been_raised() { var breaker = Policy - .Handle() - .Or() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .Handle() + .Or() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + bool delegateExecutedWhenBroken = false; + var ex = await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); delegateExecutedWhenBroken.Should().BeFalse(); } [Fact] - public void Should_not_open_circuit_if_exception_raised_is_not_the_specified_exception() + public async Task Should_not_open_circuit_if_exception_raised_is_not_the_specified_exception() { var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] - public void Should_not_open_circuit_if_exception_raised_is_not_one_of_the_specified_exceptions() + public async Task Should_not_open_circuit_if_exception_raised_is_not_one_of_the_specified_exceptions() { var breaker = Policy - .Handle() - .Or() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .Handle() + .Or() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -194,7 +194,7 @@ public void Should_not_open_circuit_if_exception_raised_is_not_one_of_the_specif #region Circuit-breaker open->half-open->open/closed tests [Fact] - public void Should_halfopen_circuit_after_the_specified_duration_has_passed() + public async Task Should_halfopen_circuit_after_the_specified_duration_has_passed() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -202,32 +202,32 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed() var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() + public async Task Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -235,20 +235,20 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -256,12 +256,11 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); - + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] @@ -273,20 +272,20 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -298,32 +297,32 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i breaker.CircuitState.Should().Be(CircuitState.Closed); // circuit has been reset so should once again allow 2 exceptions to be raised before breaking - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); } [Fact] - public void Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() + public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(1, durationOfBreak); + .Handle() + .CircuitBreakerAsync(1, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -343,18 +342,18 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ } [Fact] - public void Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() + public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(1, durationOfBreak); + .Handle() + .CircuitBreakerAsync(1, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -362,7 +361,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - + // OnActionPreExecute() should permit first execution. breaker._breakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); @@ -382,18 +381,18 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ } [Fact] - public void Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() + public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(1, durationOfBreak); + .Handle() + .CircuitBreakerAsync(1, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -405,19 +404,19 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(async () => { - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -430,7 +429,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ await TaskHelper.EmptyTask; firstExecutionActive = false; - })).Should().NotThrow(); + })).Should().NotThrowAsync(); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -481,18 +480,18 @@ await breaker.ExecuteAsync(async () => } [Fact] - public void Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() + public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(1, durationOfBreak); + .Handle() + .CircuitBreakerAsync(1, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -505,19 +504,19 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. // The second execution should be accepted in the halfopen state due to being requested after one breakDuration later. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(async () => { - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -529,7 +528,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); await TaskHelper.EmptyTask; firstExecutionActive = false; - })).Should().NotThrow(); + })).Should().NotThrowAsync(); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -586,7 +585,7 @@ await breaker.ExecuteAsync(async () => #region Isolate and reset tests [Fact] - public void Should_open_circuit_and_block_calls_if_manual_override_open() + public async Task Should_open_circuit_and_block_calls_if_manual_override_open() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -603,9 +602,9 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() breaker.CircuitState.Should().Be(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().Throw(); + bool delegateExecutedWhenBroken = false; + await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Isolated); breaker.LastException.Should().BeOfType(); delegateExecutedWhenBroken.Should().BeFalse(); @@ -613,7 +612,7 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() } [Fact] - public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() + public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -630,14 +629,14 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope SystemClock.UtcNow = () => time.Add(durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Isolated); - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().Throw(); + bool delegateExecutedWhenBroken = false; + await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) + .Should().ThrowAsync(); delegateExecutedWhenBroken.Should().BeFalse(); } [Fact] - public void Should_close_circuit_again_on_reset_after_manual_override() + public async Task Should_close_circuit_again_on_reset_after_manual_override() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -651,16 +650,16 @@ public void Should_close_circuit_again_on_reset_after_manual_override() breaker.Isolate(); breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().ThrowAsync(); breaker.Reset(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); } [Fact] - public void Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() + public async Task Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -668,27 +667,27 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); SystemClock.UtcNow().Should().Be(time); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); } #endregion @@ -699,8 +698,8 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi public void Should_not_call_onreset_on_initialise() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; Policy .Handle() @@ -710,24 +709,24 @@ public void Should_not_call_onreset_on_initialise() } [Fact] - public void Should_call_onbreak_when_breaking_circuit_automatically() + public async Task Should_call_onbreak_when_breaking_circuit_automatically() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().BeFalse(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().BeTrue(); @@ -736,9 +735,9 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy .Handle() @@ -751,70 +750,70 @@ public void Should_call_onbreak_when_breaking_circuit_manually() } [Fact] - public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() + public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); // call through circuit when already broken - should not retrigger onBreak - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); } [Fact] - public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() + public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy - .Handle() - .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1), onBreak, onReset); // Start an execution when the breaker is in the closed state, but hold it from returning (its failure) until the breaker has opened. This call, a failure hitting an already open breaker, should indicate its fail, but should not cause onBreak() to be called a second time. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) - using (var permitMainThreadToOpenCircuit = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) + using (ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false)) { - var longRunningExecution = Task.Factory.StartNew(() => + Task longRunningExecution = Task.Factory.StartNew(async () => { breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { await TaskHelper.EmptyTask; permitMainThreadToOpenCircuit.Set(); - // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). - permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); + // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). + permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); - // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + // Throw a further failure when rest of test has already broken the circuit. + breaker.CircuitState.Should().Be(CircuitState.Open); throw new DivideByZeroException(); - })).Should().Throw(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + })).Should().ThrowAsync(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. }, TaskCreationOptions.LongRunning); permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); @@ -822,8 +821,8 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub // Break circuit in the normal manner: onBreak() should be called once. breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -842,12 +841,12 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub } [Fact] - public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_halfopen() + public async Task Should_call_onreset_when_automatically_closing_circuit_but_not_when_halfopen() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -855,22 +854,22 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -882,17 +881,17 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ onResetCalled.Should().Be(0); // first call after duration is successful, so circuit should reset - breaker.ExecuteAsync(() => TaskHelper.EmptyTask); + await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().Be(1); } [Fact] - public void Should_not_call_onreset_on_successive_successful_calls() + public async Task Should_not_call_onreset_on_successive_successful_calls() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; var breaker = Policy .Handle() @@ -900,24 +899,24 @@ public void Should_not_call_onreset_on_successive_successful_calls() onResetCalled.Should().BeFalse(); - breaker.ExecuteAsync(() => TaskHelper.EmptyTask); + await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().BeFalse(); - breaker.ExecuteAsync(() => TaskHelper.EmptyTask); + await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().BeFalse(); } [Fact] - public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution() + public async Task Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -925,22 +924,22 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -949,21 +948,21 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset - breaker.ExecuteAsync(() => TaskHelper.EmptyTask); + await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); onHalfOpenCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().Be(1); } [Fact] - public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() + public async Task Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -971,22 +970,22 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); onBreakCalled.Should().Be(0); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -997,12 +996,12 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ } [Fact] - public void Should_call_onreset_when_manually_resetting_circuit() + public async Task Should_call_onreset_when_manually_resetting_circuit() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1010,29 +1009,29 @@ public void Should_call_onreset_when_manually_resetting_circuit() var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); breaker.Isolate(); onBreakCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) + .Should().ThrowAsync(); onResetCalled.Should().Be(0); breaker.Reset(); onResetCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); } #region Tests of supplied parameters to onBreak delegate [Fact] - public void Should_call_onbreak_with_the_last_raised_exception() + public async Task Should_call_onbreak_with_the_last_raised_exception() { Exception passedException = null; @@ -1040,52 +1039,52 @@ public void Should_call_onbreak_with_the_last_raised_exception() Action onReset = _ => { }; var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); passedException?.Should().BeOfType(); } [Fact] - public void Should_call_onbreak_with_a_state_of_closed() + public async Task Should_call_onbreak_with_a_state_of_closed() { CircuitState? transitionedState = null; Action onBreak = (_, state, _, _) => { transitionedState = state; }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); transitionedState?.Should().Be(CircuitState.Closed); } [Fact] - public void Should_call_onbreak_with_a_state_of_half_open() + public async Task Should_call_onbreak_with_a_state_of_half_open() { - var transitionedStates = new List(); + List transitionedStates = new List(); Action onBreak = (_, state, _, _) => { transitionedStates.Add(state); }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1093,20 +1092,20 @@ public void Should_call_onbreak_with_a_state_of_half_open() var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -1114,25 +1113,25 @@ public void Should_call_onbreak_with_a_state_of_half_open() // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); transitionedStates[0].Should().Be(CircuitState.Closed); transitionedStates[1].Should().Be(CircuitState.HalfOpen); } [Fact] - public void Should_rethrow_and_call_onbreak_with_the_last_raised_exception_unwrapped_if_matched_as_inner() + public async Task Should_rethrow_and_call_onbreak_with_the_last_raised_exception_unwrapped_if_matched_as_inner() { Exception passedException = null; Action onBreak = (exception, _, _) => { passedException = exception; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .HandleInner() @@ -1142,11 +1141,12 @@ public void Should_rethrow_and_call_onbreak_with_the_last_raised_exception_unwra Exception toRaiseAsInner = new DivideByZeroException(); Exception withInner = new AggregateException(toRaiseAsInner); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync(withInner)) - .Should().Throw().Which.Should().BeSameAs(toRaiseAsInner); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync(withInner)) + .Should().ThrowAsync(); + ex.Which.Should().BeSameAs(toRaiseAsInner); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1154,25 +1154,25 @@ public void Should_rethrow_and_call_onbreak_with_the_last_raised_exception_unwra } [Fact] - public void Should_call_onbreak_with_the_correct_timespan() + public async Task Should_call_onbreak_with_the_correct_timespan() { TimeSpan? passedBreakTimespan = null; Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); passedBreakTimespan.Should().Be(durationOfBreak); @@ -1189,8 +1189,8 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() SystemClock.UtcNow = () => time; var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.CircuitState.Should().Be(CircuitState.Closed); // manually break circuit @@ -1205,7 +1205,7 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() #region Tests that supplied context is passed to stage-change delegates [Fact] - public void Should_call_onbreak_with_the_passed_context() + public async Task Should_call_onbreak_with_the_passed_context() { IDictionary contextData = null; @@ -1213,15 +1213,15 @@ public void Should_call_onbreak_with_the_passed_context() Action onReset = _ => { }; var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync( + await breaker.Awaiting(x => x.RaiseExceptionAsync( new { key1 = "value1", key2 = "value2" }.AsDictionary() - )).Should().Throw(); + )).Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1244,13 +1244,13 @@ public async Task Should_call_onreset_with_the_passed_context() var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -1265,22 +1265,22 @@ public async Task Should_call_onreset_with_the_passed_context() } [Fact] - public void Context_should_be_empty_if_execute_not_called_with_any_context_data() + public async Task Context_should_be_empty_if_execute_not_called_with_any_context_data() { - var contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); + IDictionary contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); Action onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1288,7 +1288,7 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( } [Fact] - public void Should_create_new_context_for_each_call_to_execute() + public async Task Should_create_new_context_for_each_call_to_execute() { string contextValue = null; @@ -1296,20 +1296,20 @@ public void Should_create_new_context_for_each_call_to_execute() Action onReset = context => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; }; var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); // 2 exception raised, circuit is now open - breaker.Awaiting(x => x.RaiseExceptionAsync(new { key = "original_value" }.AsDictionary())) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync(new { key = "original_value" }.AsDictionary())) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); contextValue.Should().Be("original_value"); @@ -1320,7 +1320,7 @@ public void Should_create_new_context_for_each_call_to_execute() // but not yet reset // first call after duration is successful, so circuit should reset - breaker.ExecuteAsync(_ => TaskHelper.EmptyTask, new { key = "new_value" }.AsDictionary()); + await breaker.ExecuteAsync(_ => TaskHelper.EmptyTask, new { key = "new_value" }.AsDictionary()); breaker.CircuitState.Should().Be(CircuitState.Closed); contextValue.Should().Be("new_value"); } @@ -1342,14 +1342,14 @@ public void Should_initialise_LastException_to_null_on_creation() } [Fact] - public void Should_set_LastException_on_handling_exception_even_when_not_breaking() + public async Task Should_set_LastException_on_handling_exception_even_when_not_breaking() { var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -1357,7 +1357,7 @@ public void Should_set_LastException_on_handling_exception_even_when_not_breakin } [Fact] - public void Should_set_LastException_on_handling_inner_exception_even_when_not_breaking() + public async Task Should_set_LastException_on_handling_inner_exception_even_when_not_breaking() { var breaker = Policy .HandleInner() @@ -1366,8 +1366,9 @@ public void Should_set_LastException_on_handling_inner_exception_even_when_not_b Exception toRaiseAsInner = new DivideByZeroException(); Exception withInner = new AggregateException(toRaiseAsInner); - breaker.Awaiting(x => x.RaiseExceptionAsync(withInner)) - .Should().Throw().Which.Should().BeSameAs(toRaiseAsInner); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync(withInner)) + .Should().ThrowAsync(); + ex.Which.Should().BeSameAs(toRaiseAsInner); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -1375,17 +1376,17 @@ public void Should_set_LastException_on_handling_inner_exception_even_when_not_b } [Fact] - public void Should_set_LastException_to_last_raised_exception_when_breaking() + public async Task Should_set_LastException_to_last_raised_exception_when_breaking() { var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1393,17 +1394,17 @@ public void Should_set_LastException_to_last_raised_exception_when_breaking() } [Fact] - public void Should_set_LastException_to_null_on_circuit_reset() + public async Task Should_set_LastException_to_null_on_circuit_reset() { var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1419,45 +1420,45 @@ public void Should_set_LastException_to_null_on_circuit_reset() #region Cancellation support [Fact] - public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -1465,190 +1466,190 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_faulting_from_faulting_action_execution_when_user_delegate_does_not_observe_cancellation() + public async Task Should_report_faulting_from_faulting_action_execution_when_user_delegate_does_not_observe_cancellation() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_when_both_open_circuit_and_cancellation() + public async Task Should_report_cancellation_when_both_open_circuit_and_cancellation() { var breaker = Policy .Handle() .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1)); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); - breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync() + .WithMessage("The circuit is now open and is not allowing calls."); + ex.WithInnerException(); // Circuit is now broken. - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; cancellationTokenSource.Cancel(); - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, // Cancelled manually instead - see above. ActionObservesCancellation = false }; - breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex2 = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex2.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_honour_different_cancellationToken_captured_implicitly_by_action() + public async Task Should_honour_different_cancellationToken_captured_implicitly_by_action() { // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish TaskCanceledExceptions thrown with different CancellationTokens. var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - var policyCancellationTokenSource = new CancellationTokenSource(); - var policyCancellationToken = policyCancellationTokenSource.Token; + CancellationTokenSource policyCancellationTokenSource = new CancellationTokenSource(); + CancellationToken policyCancellationToken = policyCancellationTokenSource.Token; - var implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); - var implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; + CancellationTokenSource implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); + CancellationToken implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; implicitlyCapturedActionCancellationTokenSource.Cancel(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; - breaker.Awaiting(x => x.ExecuteAsync(async _ => - { - attemptsInvoked++; - await TaskHelper.EmptyTask; - implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - }, policyCancellationToken)) - .Should().Throw() - .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + var ex = await breaker.Awaiting(x => x.ExecuteAsync(async _ => + { + attemptsInvoked++; + await TaskHelper.EmptyTask; + implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); + }, policyCancellationToken)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() + public async Task Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, durationOfBreak); + .Handle() + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - breaker.Awaiting(action) - .Should().NotThrow(); + await breaker.Awaiting(action) + .Should().NotThrowAsync(); result.Should().BeTrue(); @@ -1656,21 +1657,21 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance } [Fact] - public void Should_honour_and_report_cancellation_during_func_execution() + public async Task Should_honour_and_report_cancellation_during_func_execution() { var breaker = Policy - .Handle() - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .Handle() + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1678,8 +1679,9 @@ public void Should_honour_and_report_cancellation_during_func_execution() }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - breaker.Awaiting(action) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(action) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); result.Should().Be(null); @@ -1692,4 +1694,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs b/src/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs index e93546836d1..b6039630023 100644 --- a/src/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs @@ -19,32 +19,32 @@ public class CircuitBreakerSpecs : IDisposable [Fact] public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() { - var breaker = Policy - .Handle() - .CircuitBreaker(1, TimeSpan.MaxValue); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(1, TimeSpan.MaxValue); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] public void Should_throw_if_exceptions_allowed_before_breaking_is_less_than_one() { - Action action = () => Policy - .Handle() - .CircuitBreaker(0, TimeSpan.FromSeconds(10)); + Action action = () => Policy + .Handle() + .CircuitBreaker(0, TimeSpan.FromSeconds(10)); action.Should().Throw() - .And.ParamName.Should() - .Be("exceptionsAllowedBeforeBreaking"); + .And.ParamName.Should() + .Be("exceptionsAllowedBeforeBreaking"); } [Fact] public void Should_throw_if_duration_of_break_is_less_than_zero() { Action action = () => Policy - .Handle() - .CircuitBreaker(1, -TimeSpan.FromSeconds(1)); + .Handle() + .CircuitBreaker(1, -TimeSpan.FromSeconds(1)); action.Should().Throw() .And.ParamName.Should() @@ -55,8 +55,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() public void Should_be_able_to_handle_a_duration_of_break_of_zero() { Action action = () => Policy - .Handle() - .CircuitBreaker(1, TimeSpan.Zero); + .Handle() + .CircuitBreaker(1, TimeSpan.Zero); action.Should().NotThrow(); } @@ -65,7 +65,7 @@ public void Should_initialise_to_closed_state() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak); @@ -79,7 +79,7 @@ public void Should_initialise_to_closed_state() [Fact] public void Should_not_open_circuit_if_specified_number_of_specified_exception_are_not_raised_consecutively() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -98,23 +98,23 @@ public void Should_not_open_circuit_if_specified_number_of_specified_exception_a [Fact] public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_after_specified_number_of_specified_exception_have_been_raised() { - var breaker = Policy - .Handle() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + .Should().Throw() + .WithMessage("The circuit is now open and is not allowing calls.") + .WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); delegateExecutedWhenBroken.Should().BeFalse(); } @@ -122,25 +122,25 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e [Fact] public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_after_specified_number_of_one_of_the_specified_exceptions_have_been_raised() { - var breaker = Policy - .Handle() - .Or() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .Handle() + .Or() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + .Should().Throw() + .WithMessage("The circuit is now open and is not allowing calls.") + .WithInnerException(); breaker.CircuitState.Should().Be(CircuitState.Open); delegateExecutedWhenBroken.Should().BeFalse(); } @@ -148,41 +148,41 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e [Fact] public void Should_not_open_circuit_if_exception_raised_is_not_the_specified_exception() { - var breaker = Policy - .Handle() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_exception_raised_is_not_one_of_the_specified_exceptions() { - var breaker = Policy - .Handle() - .Or() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .Handle() + .Or() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -198,21 +198,21 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -220,7 +220,7 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed() // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -231,21 +231,21 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -254,11 +254,11 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if breaker.CircuitState.Should().Be(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - + .Should().Throw(); + } [Fact] @@ -269,21 +269,21 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -296,15 +296,15 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ // circuit has been reset so should once again allow 2 exceptions to be raised before breaking breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); } @@ -315,12 +315,12 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(1, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(1, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -346,12 +346,12 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(1, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(1, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -385,12 +385,12 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(1, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(1, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -402,17 +402,17 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(() => { breaker.Invoking(x => x.Execute(() => { @@ -432,7 +432,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks); - var secondExecution = Task.Factory.StartNew(() => + Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). firstExecutionActive.Should().BeTrue(); @@ -483,12 +483,12 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(1, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(1, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -501,17 +501,17 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. // The second execution should be accepted in the halfopen state due to being requested after one breakDuration later. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(() => { breaker.Invoking(x => x.Execute(() => { @@ -531,7 +531,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks); - var secondExecution = Task.Factory.StartNew(() => + Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). firstExecutionActive.Should().BeTrue(); @@ -587,7 +587,7 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -597,7 +597,7 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() breaker.CircuitState.Should().Be(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Isolated); @@ -613,7 +613,7 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -623,7 +623,7 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope SystemClock.UtcNow = () => time.Add(durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Isolated); - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })) .Should().Throw(); delegateExecutedWhenBroken.Should().BeFalse(); @@ -637,7 +637,7 @@ public void Should_close_circuit_again_on_reset_after_manual_override() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -660,21 +660,21 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // reset circuit, with no time having passed @@ -692,8 +692,8 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi public void Should_not_call_onreset_on_initialise() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; Policy .Handle() @@ -705,22 +705,22 @@ public void Should_not_call_onreset_on_initialise() [Fact] public void Should_call_onbreak_when_breaking_circuit_automatically() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy - .Handle() - .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().BeFalse(); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().BeTrue(); @@ -729,11 +729,11 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { - var onBreakCalled = false; + bool onBreakCalled = false; Action onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); onBreakCalled.Should().BeFalse(); @@ -746,29 +746,29 @@ public void Should_call_onbreak_when_breaking_circuit_manually() [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy - .Handle() - .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); // call through circuit when already broken - should not retrigger onBreak breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -777,20 +777,20 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy - .Handle() - .CircuitBreaker(1, TimeSpan.FromMinutes(1), onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(1, TimeSpan.FromMinutes(1), onBreak, onReset); // Start an execution when the breaker is in the closed state, but hold it from returning (its failure) until the breaker has opened. This call, a failure hitting an already open breaker, should indicate its fail, but should not cause onBreak() to be called a second time. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) - using (var permitMainThreadToOpenCircuit = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) + using (ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false)) { - var longRunningExecution = Task.Factory.StartNew(() => + Task longRunningExecution = Task.Factory.StartNew(() => { breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -798,11 +798,11 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub { permitMainThreadToOpenCircuit.Set(); - // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). - permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); + // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). + permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); - // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + // Throw a further failure when rest of test has already broken the circuit. + breaker.CircuitState.Should().Be(CircuitState.Open); throw new DivideByZeroException(); })).Should().Throw(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. @@ -814,7 +814,7 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -835,33 +835,33 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub [Fact] public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_halfopen() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak, onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -882,10 +882,10 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ public void Should_not_call_onreset_on_successive_successful_calls() { Action onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -903,35 +903,35 @@ public void Should_not_call_onreset_on_successive_successful_calls() [Fact] public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -949,35 +949,35 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ [Fact] public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); onBreakCalled.Should().Be(0); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -990,19 +990,19 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ [Fact] public void Should_call_onreset_when_manually_resetting_circuit() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak, onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); breaker.Isolate(); @@ -1030,9 +1030,9 @@ public void Should_call_onbreak_with_the_last_raised_exception() Action onBreak = (exception, _, _) => { passedException = exception; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -1054,9 +1054,9 @@ public void Should_call_onbreak_with_a_state_of_closed() Action onBreak = (_, state, _, _) => { transitionedState = state; }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); @@ -1074,32 +1074,32 @@ public void Should_call_onbreak_with_a_state_of_closed() [Fact] public void Should_call_onbreak_with_a_state_of_half_open() { - var transitionedStates = new List(); + List transitionedStates = new List(); Action onBreak = (_, state, _, _) => { transitionedStates.Add(state); }; Action onReset = _ => { }; - var onHalfOpen = () => { }; + Action onHalfOpen = () => { }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -1108,10 +1108,10 @@ public void Should_call_onbreak_with_a_state_of_half_open() breaker.CircuitState.Should().Be(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); transitionedStates[0].Should().Be(CircuitState.Closed); transitionedStates[1].Should().Be(CircuitState.HalfOpen); @@ -1125,9 +1125,9 @@ public void Should_rethrow_and_call_onbreak_with_the_last_raised_exception_unwra Action onBreak = (exception, _, _) => { passedException = exception; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleInner() .Or() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -1154,9 +1154,9 @@ public void Should_call_onbreak_with_the_correct_timespan() Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -1183,7 +1183,7 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -1207,7 +1207,7 @@ public void Should_call_onbreak_with_the_passed_context() Action onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -1216,7 +1216,7 @@ public void Should_call_onbreak_with_the_passed_context() breaker.Invoking(x => x.RaiseException( new {key1 = "value1", key2 = "value2"}.AsDictionary() - )).Should().Throw(); + )).Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1238,7 +1238,7 @@ public void Should_call_onreset_with_the_passed_context() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -1262,12 +1262,12 @@ public void Should_call_onreset_with_the_passed_context() [Fact] public void Context_should_be_empty_if_execute_not_called_with_any_context_data() { - var contextData = new {key1 = "value1", key2 = "value2"}.AsDictionary(); + IDictionary contextData = new {key1 = "value1", key2 = "value2"}.AsDictionary(); Action onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -1290,7 +1290,7 @@ public void Should_create_new_context_for_each_call_to_execute() Action onBreak = (_, _, context) => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; }; Action onReset = context => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -1339,7 +1339,7 @@ public void Should_initialise_LastException_to_null_on_creation() [Fact] public void Should_set_LastException_on_handling_exception_even_when_not_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1354,7 +1354,7 @@ public void Should_set_LastException_on_handling_exception_even_when_not_breakin [Fact] public void Should_set_LastException_on_handling_inner_exception_even_when_not_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleInner() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1373,7 +1373,7 @@ public void Should_set_LastException_on_handling_inner_exception_even_when_not_b [Fact] public void Should_set_LastException_to_last_raised_exception_when_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1391,7 +1391,7 @@ public void Should_set_LastException_to_last_raised_exception_when_breaking() [Fact] public void Should_set_LastException_to_null_on_circuit_reset() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1417,7 +1417,7 @@ public void Should_set_LastException_to_null_on_circuit_reset() [Fact] public void Should_set_PolicyResult_on_handling_inner_exception() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleInner() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1425,7 +1425,7 @@ public void Should_set_PolicyResult_on_handling_inner_exception() Exception toRaiseAsInner = new DivideByZeroException(); Exception withInner = new AggregateException(toRaiseAsInner); - var policyResult = breaker.ExecuteAndCapture(() => throw withInner); + PolicyResult policyResult = breaker.ExecuteAndCapture(() => throw withInner); policyResult.ExceptionType.Should().Be(ExceptionType.HandledByThisPolicy); policyResult.FinalException.Should().BeSameAs(toRaiseAsInner); @@ -1439,16 +1439,16 @@ public void Should_set_PolicyResult_on_handling_inner_exception() public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, @@ -1464,17 +1464,17 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -1493,17 +1493,17 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1521,17 +1521,17 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec public void Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, @@ -1549,16 +1549,16 @@ public void Should_report_cancellation_during_faulting_action_execution_when_use public void Should_report_faulting_from_faulting_action_execution_when_user_delegate_does_not_observe_cancellation() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, @@ -1574,7 +1574,7 @@ public void Should_report_faulting_from_faulting_action_execution_when_user_dele [Fact] public void Should_report_cancellation_when_both_open_circuit_and_cancellation() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(1, TimeSpan.FromMinutes(1)); @@ -1587,15 +1587,15 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() .WithInnerException(); // Circuit is now broken. - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; cancellationTokenSource.Cancel(); - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, // Cancelled manually instead - see above. @@ -1615,25 +1615,25 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish OperationCanceledExceptions thrown with different CancellationTokens. var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); - var policyCancellationTokenSource = new CancellationTokenSource(); - var policyCancellationToken = policyCancellationTokenSource.Token; + CancellationTokenSource policyCancellationTokenSource = new CancellationTokenSource(); + CancellationToken policyCancellationToken = policyCancellationTokenSource.Token; - var implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); - var implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; + CancellationTokenSource implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); + CancellationToken implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; implicitlyCapturedActionCancellationTokenSource.Cancel(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; breaker.Invoking(x => x.Execute(_ => - { - attemptsInvoked++; - implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - }, policyCancellationToken)) + { + attemptsInvoked++; + implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); + }, policyCancellationToken)) .Should().Throw() .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); @@ -1644,19 +1644,19 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .Handle() - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, @@ -1673,19 +1673,19 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance [Fact] public void Should_honour_and_report_cancellation_during_func_execution() { - var breaker = Policy - .Handle() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1707,4 +1707,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs b/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs index 62158388007..6922ce5464d 100644 --- a/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs @@ -22,8 +22,8 @@ public class CircuitBreakerTResultAsyncSpecs : IDisposable public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() { var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(1, TimeSpan.MaxValue); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(1, TimeSpan.MaxValue); var result = await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault); result.Should().Be(ResultPrimitive.Fault); @@ -33,20 +33,20 @@ public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() public void Should_throw_if_faults_allowed_before_breaking_is_less_than_one() { Action action = () => Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(0, TimeSpan.FromSeconds(10)); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(0, TimeSpan.FromSeconds(10)); action.Should().Throw() - .And.ParamName.Should() - .Be("handledEventsAllowedBeforeBreaking"); + .And.ParamName.Should() + .Be("handledEventsAllowedBeforeBreaking"); } [Fact] public void Should_throw_if_duration_of_break_is_less_than_zero() { Action action = () => Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(1, -TimeSpan.FromSeconds(1)); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(1, -TimeSpan.FromSeconds(1)); action.Should().Throw() .And.ParamName.Should() @@ -57,8 +57,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() public void Should_be_able_to_handle_a_duration_of_break_of_zero() { Action action = () => Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(1, TimeSpan.Zero); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(1, TimeSpan.Zero); action.Should().NotThrow(); } @@ -82,19 +82,19 @@ public void Should_initialise_to_closed_state() public async Task Should_not_open_circuit_if_specified_number_of_specified_handled_result_are_not_raised_consecutively() { var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .Should().Be(ResultPrimitive.Good); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -102,19 +102,19 @@ public async Task Should_not_open_circuit_if_specified_number_of_specified_handl public async Task Should_open_circuit_with_the_last_handled_result_after_specified_number_of_specified_handled_result_have_been_returned() { var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw>() + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync>() .WithMessage("The circuit is now open and is not allowing calls.") .Where(e => e.Result == ResultPrimitive.Fault); @@ -125,21 +125,21 @@ public async Task Should_open_circuit_with_the_last_handled_result_after_specifi public async Task Should_open_circuit_with_the_last_handled_result_after_specified_number_of_one_of_the_specified_handled_results_have_been_raised() { var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw>() + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync>() .WithMessage("The circuit is now open and is not allowing calls.") .Where(e => e.Result == ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -149,19 +149,19 @@ public async Task Should_open_circuit_with_the_last_handled_result_after_specifi public async Task Should_open_circuit_with_the_last_handled_result_after_specified_number_of_specified_handled_result_with_predicate_have_been_returned() { var breaker = Policy - .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault))) - .ResultCode.Should().Be(ResultPrimitive.Fault); + .ResultCode.Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault))) - .ResultCode.Should().Be(ResultPrimitive.Fault); + .ResultCode.Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(b => b.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Good))) - .Should().Throw>() + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Good))) + .Should().ThrowAsync>() .WithMessage("The circuit is now open and is not allowing calls.") .Where(e => e.Result.ResultCode == ResultPrimitive.Fault); @@ -172,19 +172,19 @@ public async Task Should_open_circuit_with_the_last_handled_result_after_specifi public async Task Should_not_open_circuit_if_result_returned_is_not_the_handled_result() { var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -192,9 +192,9 @@ public async Task Should_not_open_circuit_if_result_returned_is_not_the_handled_ public async Task Should_not_open_circuit_if_result_returned_is_not_one_of_the_handled_results() { var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultYetAgain) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultYetAgain) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) .Should().Be(ResultPrimitive.FaultAgain); @@ -213,8 +213,8 @@ public async Task Should_not_open_circuit_if_result_returned_is_not_one_of_the_h public async Task Should_not_open_circuit_if_result_returned_does_not_match_result_predicate() { var breaker = Policy - .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); + .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain))) .ResultCode.Should().Be(ResultPrimitive.FaultAgain); @@ -263,20 +263,20 @@ public async Task Should_halfopen_circuit_after_the_specified_duration_has_passe var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw(); + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -284,7 +284,7 @@ public async Task Should_halfopen_circuit_after_the_specified_duration_has_passe // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); } [Fact] @@ -296,20 +296,20 @@ public async Task Should_open_circuit_again_after_the_specified_duration_has_pas var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw(); + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -319,10 +319,10 @@ public async Task Should_open_circuit_again_after_the_specified_duration_has_pas // first call after duration returns a fault, so circuit should break again (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw(); + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync(); } [Fact] @@ -334,20 +334,20 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw(); + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -361,15 +361,15 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i // circuit has been reset so should once again allow 2 faults to be raised before breaking (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw(); + await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); } @@ -385,7 +385,7 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -416,7 +416,7 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -455,7 +455,7 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -467,19 +467,19 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(async () => { - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -493,7 +493,7 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ firstExecutionActive = false; return ResultPrimitive.Good; - })).Should().NotThrow(); + })).Should().NotThrowAsync(); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -558,7 +558,7 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -571,19 +571,19 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. // The second execution should be accepted in the halfopen state due to being requested after one breakDuration later. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(async () => { - breaker.Awaiting(x => x.ExecuteAsync(async () => + await breaker.Awaiting(x => x.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -597,7 +597,7 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s firstExecutionActive = false; return ResultPrimitive.Good; - })).Should().NotThrow(); + })).Should().NotThrowAsync(); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -656,7 +656,7 @@ await breaker.ExecuteAsync(async () => #region Isolate and reset tests [Fact] - public void Should_open_circuit_and_block_calls_if_manual_override_open() + public async Task Should_open_circuit_and_block_calls_if_manual_override_open() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -673,9 +673,9 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() breaker.CircuitState.Should().Be(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-fault-returning executions should not reset circuit - var delegateExecutedWhenBroken = false; - breaker.Awaiting(b => b.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })) - .Should().Throw(); + bool delegateExecutedWhenBroken = false; + await breaker.Awaiting(b => b.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Isolated); breaker.LastException.Should().BeOfType(); delegateExecutedWhenBroken.Should().BeFalse(); @@ -683,7 +683,7 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() } [Fact] - public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() + public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -701,14 +701,14 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope SystemClock.UtcNow = () => time.Add(durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Isolated); - var delegateExecutedWhenBroken = false; - breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })) - .Should().Throw(); + bool delegateExecutedWhenBroken = false; + await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })) + .Should().ThrowAsync(); delegateExecutedWhenBroken.Should().BeFalse(); } [Fact] - public void Should_close_circuit_again_on_reset_after_manual_override() + public async Task Should_close_circuit_again_on_reset_after_manual_override() { var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -722,12 +722,12 @@ public void Should_close_circuit_again_on_reset_after_manual_override() breaker.Isolate(); breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().ThrowAsync(); breaker.Reset(); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); } [Fact] @@ -739,27 +739,27 @@ public async Task Should_be_able_to_reset_automatically_opened_circuit_without_s var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); SystemClock.UtcNow().Should().Be(time); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); } #endregion @@ -770,8 +770,8 @@ public async Task Should_be_able_to_reset_automatically_opened_circuit_without_s public void Should_not_call_onreset_on_initialise() { Action, TimeSpan> onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; Policy .HandleResult(ResultPrimitive.Fault) @@ -783,22 +783,22 @@ public void Should_not_call_onreset_on_initialise() [Fact] public async Task Should_call_onbreak_when_breaking_circuit_automatically() { - var onBreakCalled = false; + bool onBreakCalled = false; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().BeFalse(); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().BeTrue(); @@ -807,9 +807,9 @@ public async Task Should_call_onbreak_when_breaking_circuit_automatically() [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { - var onBreakCalled = false; + bool onBreakCalled = false; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy .HandleResult(ResultPrimitive.Fault) @@ -824,29 +824,29 @@ public void Should_call_onbreak_when_breaking_circuit_manually() [Fact] public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); // call through circuit when already broken - should not retrigger onBreak - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -855,18 +855,18 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f [Fact] public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1), onBreak, onReset); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1), onBreak, onReset); // Start an execution when the breaker is in the closed state, but hold it from returning (its failure) until the breaker has opened. This call, a failure hitting an already open breaker, should indicate its fail, but should not cause onBreak() to be called a second time. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) - using (var permitMainThreadToOpenCircuit = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) + using (ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false)) { Task longRunningExecution = Task.Factory.StartNew(async () => { @@ -878,11 +878,11 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f permitMainThreadToOpenCircuit.Set(); - // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). - permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); + // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). + permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); - // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + // Throw a further failure when rest of test has already broken the circuit. + breaker.CircuitState.Should().Be(CircuitState.Open); return ResultPrimitive.Fault; })).Should().Be(ResultPrimitive.Fault); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original fault should still be returned. @@ -894,7 +894,7 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -915,10 +915,10 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f [Fact] public async Task Should_call_onreset_when_automatically_closing_circuit_but_not_when_halfopen() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -926,22 +926,22 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(1); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -953,17 +953,17 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not onResetCalled.Should().Be(0); // first call after duration is successful, so circuit should reset - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().Be(1); } [Fact] - public void Should_not_call_onreset_on_successive_successful_calls() + public async Task Should_not_call_onreset_on_successive_successful_calls() { Action, TimeSpan> onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; var breaker = Policy .HandleResult(ResultPrimitive.Fault) @@ -971,11 +971,11 @@ public void Should_not_call_onreset_on_successive_successful_calls() onResetCalled.Should().BeFalse(); - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().BeFalse(); - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().BeFalse(); } @@ -983,12 +983,12 @@ public void Should_not_call_onreset_on_successive_successful_calls() [Fact] public async Task Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -996,22 +996,22 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(1); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -1020,8 +1020,8 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().NotThrowAsync(); onHalfOpenCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Closed); onResetCalled.Should().Be(1); @@ -1030,12 +1030,12 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal [Fact] public async Task Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1043,22 +1043,22 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(1); // 2 exception or fault raised, circuit is now open - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -1069,12 +1069,12 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal } [Fact] - public void Should_call_onreset_when_manually_resetting_circuit() + public async Task Should_call_onreset_when_manually_resetting_circuit() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; @@ -1082,24 +1082,24 @@ public void Should_call_onreset_when_manually_resetting_circuit() var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); breaker.Isolate(); onBreakCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().Throw(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().ThrowAsync(); onResetCalled.Should().Be(0); breaker.Reset(); onResetCalled.Should().Be(1); breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().NotThrow(); + await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) + .Should().NotThrowAsync(); } #region Tests of supplied parameters to onBreak delegate @@ -1112,7 +1112,7 @@ public async Task Should_call_onbreak_with_the_last_handled_result() Action, TimeSpan, Context> onBreak = (outcome, _, _) => { handledResult = outcome.Result; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .HandleResult(ResultPrimitive.Fault) @@ -1137,7 +1137,7 @@ public async Task Should_call_onbreak_with_the_correct_timespan() Action, TimeSpan, Context> onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .HandleResult(ResultPrimitive.Fault) @@ -1198,7 +1198,7 @@ public async Task Should_call_onbreak_with_the_passed_context() .Should().Be(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(new { key1 = "value1", key2 = "value2" }.AsDictionary(), - ResultPrimitive.Fault)) + ResultPrimitive.Fault)) .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1245,7 +1245,7 @@ public async Task Should_call_onreset_with_the_passed_context() [Fact] public async Task Context_should_be_empty_if_execute_not_called_with_any_context_data() { - var contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); + IDictionary contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); Action, TimeSpan, Context> onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; @@ -1390,111 +1390,111 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; (await breaker.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good)) + ResultPrimitive.Good)) .Should().Be(ResultPrimitive.Good); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. }; cancellationTokenSource.Cancel(); - breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Good, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } @@ -1504,23 +1504,23 @@ public async Task Should_report_faulting_from_faulting_action_execution_when_use { var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; (await breaker.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); attemptsInvoked.Should().Be(1); } @@ -1535,63 +1535,63 @@ public async Task Should_report_cancellation_when_both_open_circuit_and_cancella (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) .Should().Be(ResultPrimitive.Fault); - breaker.Awaiting(x => x.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Throw() + var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAsync(ResultPrimitive.Fault)) + .Should().ThrowAsync() .WithMessage("The circuit is now open and is not allowing calls."); // Circuit is now broken. - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; cancellationTokenSource.Cancel(); - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancelled manually instead - see above. ActionObservesCancellation = false }; - breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex2 = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex2.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_honour_different_cancellationToken_captured_implicitly_by_action() + public async Task Should_honour_different_cancellationToken_captured_implicitly_by_action() { // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish TaskCanceledExceptions thrown with different CancellationTokens. var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreakerAsync(2, durationOfBreak); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreakerAsync(2, durationOfBreak); - var policyCancellationTokenSource = new CancellationTokenSource(); - var policyCancellationToken = policyCancellationTokenSource.Token; + CancellationTokenSource policyCancellationTokenSource = new CancellationTokenSource(); + CancellationToken policyCancellationToken = policyCancellationTokenSource.Token; - var implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); - var implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; + CancellationTokenSource implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); + CancellationToken implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; implicitlyCapturedActionCancellationTokenSource.Cancel(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; - breaker.Awaiting(x => x.ExecuteAsync(async _ => - { - attemptsInvoked++; - await TaskHelper.EmptyTask; - implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - return ResultPrimitive.Good; - }, policyCancellationToken)) - .Should().Throw() - .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + var ex = await breaker.Awaiting(x => x.ExecuteAsync(async _ => + { + attemptsInvoked++; + await TaskHelper.EmptyTask; + implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); + return ResultPrimitive.Good; + }, policyCancellationToken)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); attemptsInvoked.Should().Be(1); } @@ -1601,4 +1601,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs b/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs index bc883068581..bdd320ef772 100644 --- a/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs @@ -16,9 +16,9 @@ public class CircuitBreakerTResultMixedResultExceptionSpecs : IDisposable [Fact] public void Should_open_circuit_with_exception_after_specified_number_of_specified_exception_have_been_returned_when_result_policy_handling_exceptions_only() { - var breaker = Policy - .Handle() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .Handle() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) .Should().Throw(); @@ -39,13 +39,13 @@ public void Should_open_circuit_with_exception_after_specified_number_of_specifi [Fact] public void Should_open_circuit_with_the_last_exception_after_specified_number_of_exceptions_and_results_have_been_raised__breaking_on_result__when_configuring_result_first() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .Or() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .Or() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) @@ -64,17 +64,17 @@ public void Should_open_circuit_with_the_last_exception_after_specified_number_o [Fact] public void Should_open_circuit_with_the_last_handled_result_after_specified_number_of_exceptions_and_results_have_been_raised__breaking_on_result__when_configuring_result_first() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .Or() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .Or() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open @@ -89,13 +89,13 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num [Fact] public void Should_open_circuit_with_the_last_exception_after_specified_number_of_exceptions_and_results_have_been_raised__breaking_on_result__when_configuring_exception_first() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) @@ -114,7 +114,7 @@ public void Should_open_circuit_with_the_last_exception_after_specified_number_o [Fact] public void Should_open_circuit_with_the_last_handled_result_after_specified_number_of_exceptions_and_results_have_been_raised__breaking_on_result__when_configuring_exception_first() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -124,7 +124,7 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open @@ -139,7 +139,7 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num [Fact] public void Should_open_circuit_if_results_and_exceptions_returned_match_combination_of_the_result_and_exception_predicates() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle(e => e.ParamName == "key") .OrResult(r => r.ResultCode == ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -149,7 +149,7 @@ public void Should_open_circuit_if_results_and_exceptions_returned_match_combina breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault)) - .ResultCode.Should().Be(ResultPrimitive.Fault); + .ResultCode.Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open @@ -164,28 +164,28 @@ public void Should_open_circuit_if_results_and_exceptions_returned_match_combina [Fact] public void Should_not_open_circuit_if_result_returned_is_not_one_of_the_configured_results_or_exceptions() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_exception_thrown_is_not_one_of_the_configured_results_or_exceptions() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -206,22 +206,22 @@ public void Should_not_open_circuit_if_exception_thrown_is_not_one_of_the_config [Fact] public void Should_not_open_circuit_if_result_returned_does_not_match_any_of_the_result_predicates() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle(e => e.ParamName == "key") .OrResult(r => r.ResultCode == ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); // non-matched result predicate breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); // non-matched exception predicate @@ -240,7 +240,7 @@ public void Should_not_open_circuit_if_result_returned_does_not_match_any_of_the [Fact] public void Should_open_circuit_with_the_last_exception_after_specified_number_of_exceptions_and_results_have_been_raised__configuring_multiple_results_and_exceptions() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .Or() @@ -248,7 +248,7 @@ [Fact] public void Should_open_circuit_with_the_last_exception_after_specified_n .CircuitBreaker(4, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) @@ -256,7 +256,7 @@ [Fact] public void Should_open_circuit_with_the_last_exception_after_specified_n breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) @@ -275,7 +275,7 @@ [Fact] public void Should_open_circuit_with_the_last_exception_after_specified_n [Fact] public void Should_open_circuit_with_the_last_handled_result_after_specified_number_of_exceptions_and_results_have_been_raised__when_configuring_multiple_results_and_exceptions() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .Or() @@ -287,7 +287,7 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) @@ -295,7 +295,7 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Open); // 4 exception raised, circuit is now open @@ -306,17 +306,17 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num breaker.CircuitState.Should().Be(CircuitState.Open); } - + [Fact] public void Should_not_open_circuit_if_result_raised_or_exception_thrown_is_not_one_of_the_handled_results_or_exceptions() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .Or() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .Or() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) @@ -324,7 +324,7 @@ public void Should_not_open_circuit_if_result_raised_or_exception_thrown_is_not_ breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) @@ -344,13 +344,13 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .Or() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .Or() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) @@ -359,7 +359,7 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if // 2 exception raised, circuit is now open breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -369,10 +369,10 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if // first call after duration returns a fault, so circuit should break again breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); } @@ -384,13 +384,13 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .Or() - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .Or() + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) @@ -399,7 +399,7 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if // 2 exception raised, circuit is now open breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -412,7 +412,7 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); } @@ -430,9 +430,9 @@ public void Should_call_onbreak_with_the_last_handled_result() Action, TimeSpan, Context> onBreak = (outcome, _, _) => { handledResult = outcome.Result; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -456,9 +456,9 @@ public void Should_call_onbreak_with_the_last_raised_exception() Action, TimeSpan, Context> onBreak = (outcome, _, _) => { lastException = outcome.Exception; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -483,7 +483,7 @@ public void Should_call_onbreak_with_the_last_raised_exception() [Fact] public void Should_initialise_LastHandledResult_and_LastResult_to_default_on_creation() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -495,7 +495,7 @@ public void Should_initialise_LastHandledResult_and_LastResult_to_default_on_cre [Fact] public void Should_set_LastHandledResult_on_handling_result_even_when_not_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -512,7 +512,7 @@ public void Should_set_LastHandledResult_on_handling_result_even_when_not_breaki [Fact] public void Should_set_LastException_on_exception_even_when_not_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -529,7 +529,7 @@ public void Should_set_LastException_on_exception_even_when_not_breaking() [Fact] public void Should_set_LastHandledResult_to_last_handled_result_when_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -549,7 +549,7 @@ public void Should_set_LastHandledResult_to_last_handled_result_when_breaking() [Fact] public void Should_set_LastException_to_last_exception_when_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -569,7 +569,7 @@ public void Should_set_LastException_to_last_exception_when_breaking() [Fact] public void Should_set_LastHandledResult_and_LastException_to_default_on_circuit_reset() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .Handle() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -598,4 +598,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs b/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs index d0b933a7ebc..0516e371075 100644 --- a/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs @@ -21,9 +21,9 @@ public class CircuitBreakerTResultSpecs : IDisposable [Fact] public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(1, TimeSpan.MaxValue); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(1, TimeSpan.MaxValue); var result = breaker.RaiseResultSequence(ResultPrimitive.Fault); result.Should().Be(ResultPrimitive.Fault); @@ -33,20 +33,20 @@ public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() public void Should_throw_if_faults_allowed_before_breaking_is_less_than_one() { Action action = () => Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(0, TimeSpan.FromSeconds(10)); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(0, TimeSpan.FromSeconds(10)); action.Should().Throw() - .And.ParamName.Should() - .Be("handledEventsAllowedBeforeBreaking"); + .And.ParamName.Should() + .Be("handledEventsAllowedBeforeBreaking"); } [Fact] public void Should_throw_if_duration_of_break_is_less_than_zero() { Action action = () => Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(1, -TimeSpan.FromSeconds(1)); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(1, -TimeSpan.FromSeconds(1)); action.Should().Throw() .And.ParamName.Should() @@ -57,8 +57,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() public void Should_be_able_to_handle_a_duration_of_break_of_zero() { Action action = () => Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(1, TimeSpan.Zero); + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(1, TimeSpan.Zero); action.Should().NotThrow(); } @@ -67,7 +67,7 @@ public void Should_initialise_to_closed_state() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); @@ -81,36 +81,36 @@ public void Should_initialise_to_closed_state() [Fact] public void Should_not_open_circuit_if_specified_number_of_specified_handled_result_are_not_raised_consecutively() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .Should().Be(ResultPrimitive.Good); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] public void Should_open_circuit_with_the_last_handled_result_after_specified_number_of_specified_handled_result_have_been_returned() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) @@ -124,17 +124,17 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num [Fact] public void Should_open_circuit_with_the_last_handled_result_after_specified_number_of_one_of_the_specified_handled_results_have_been_raised() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open @@ -148,7 +148,7 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num [Fact] public void Should_open_circuit_with_the_last_handled_result_after_specified_number_of_specified_handled_result_with_predicate_have_been_returned() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -171,82 +171,82 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num [Fact] public void Should_not_open_circuit_if_result_returned_is_not_the_handled_result() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_result_returned_is_not_one_of_the_handled_results() { - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultYetAgain) - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultYetAgain) + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_result_returned_does_not_match_result_predicate() { - var breaker = Policy - .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) - .CircuitBreaker(2, TimeSpan.FromMinutes(1)); + CircuitBreakerPolicy breaker = Policy + .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) + .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_result_returned_does_not_match_any_of_the_result_predicates() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .OrResult(r => r.ResultCode == ResultPrimitive.FaultYetAgain) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); + .ResultCode.Should().Be(ResultPrimitive.FaultAgain); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -262,16 +262,16 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open @@ -284,7 +284,7 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed() // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); } [Fact] @@ -295,21 +295,21 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -319,10 +319,10 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if // first call after duration returns a fault, so circuit should break again breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); } @@ -334,21 +334,21 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); @@ -361,15 +361,15 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ // circuit has been reset so should once again allow 2 faults to be raised before breaking breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); } @@ -380,7 +380,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, durationOfBreak); @@ -411,7 +411,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, durationOfBreak); @@ -450,12 +450,12 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -467,17 +467,17 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(() => { breaker.Invoking(x => x.Execute(() => { @@ -498,7 +498,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks); - var secondExecution = Task.Factory.StartNew(() => + Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). firstExecutionActive.Should().BeTrue(); @@ -550,12 +550,12 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); // exception raised, circuit is now open. breaker.CircuitState.Should().Be(CircuitState.Open); @@ -568,17 +568,17 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. // The second execution should be accepted in the halfopen state due to being requested after one breakDuration later. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitSecondExecutionAttempt = new ManualResetEvent(false)) - using (var permitFirstExecutionEnd = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitSecondExecutionAttempt = new ManualResetEvent(false)) + using (ManualResetEvent permitFirstExecutionEnd = new ManualResetEvent(false)) { bool? firstDelegateExecutedInHalfOpenState = null; bool? secondDelegateExecutedInHalfOpenState = null; bool? secondDelegateRejectedInHalfOpenState = null; - var firstExecutionActive = false; + bool firstExecutionActive = false; // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. - var firstExecution = Task.Factory.StartNew(() => + Task firstExecution = Task.Factory.StartNew(() => { breaker.Invoking(x => x.Execute(() => { @@ -599,7 +599,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks); - var secondExecution = Task.Factory.StartNew(() => + Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). firstExecutionActive.Should().BeTrue(); @@ -657,7 +657,7 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -667,7 +667,7 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() breaker.CircuitState.Should().Be(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-fault-returning executions should not reset circuit - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good;})) .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Isolated); @@ -684,7 +684,7 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -695,7 +695,7 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope SystemClock.UtcNow = () => time.Add(durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Isolated); - var delegateExecutedWhenBroken = false; + bool delegateExecutedWhenBroken = false; breaker.Invoking(x => x.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })) .Should().Throw(); delegateExecutedWhenBroken.Should().BeFalse(); @@ -709,7 +709,7 @@ public void Should_close_circuit_again_on_reset_after_manual_override() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -732,21 +732,21 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // 2 exception raised, circuit is now open breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); // reset circuit, with no time having passed @@ -764,8 +764,8 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi public void Should_not_call_onreset_on_initialise() { Action, TimeSpan> onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; Policy .HandleResult(ResultPrimitive.Fault) @@ -777,22 +777,22 @@ public void Should_not_call_onreset_on_initialise() [Fact] public void Should_call_onbreak_when_breaking_circuit_automatically() { - var onBreakCalled = false; + bool onBreakCalled = false; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().BeFalse(); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().BeTrue(); @@ -801,11 +801,11 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { - var onBreakCalled = false; + bool onBreakCalled = false; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled = true; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); onBreakCalled.Should().BeFalse(); @@ -818,29 +818,29 @@ public void Should_call_onbreak_when_breaking_circuit_manually() [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); // call through circuit when already broken - should not retrigger onBreak breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -849,20 +849,20 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { - var onBreakCalled = 0; + int onBreakCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { }; + Action onReset = () => { }; - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(1, TimeSpan.FromMinutes(1), onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(1, TimeSpan.FromMinutes(1), onBreak, onReset); // Start an execution when the breaker is in the closed state, but hold it from returning (its failure) until the breaker has opened. This call, a failure hitting an already open breaker, should indicate its fail, but should not cause onBreak() to be called a second time. - var testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); - using (var permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) - using (var permitMainThreadToOpenCircuit = new ManualResetEvent(false)) + TimeSpan testTimeoutToExposeDeadlocks = TimeSpan.FromSeconds(5); + using (ManualResetEvent permitLongRunningExecutionToReturnItsFailure = new ManualResetEvent(false)) + using (ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false)) { - var longRunningExecution = Task.Factory.StartNew(() => + Task longRunningExecution = Task.Factory.StartNew(() => { breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -870,11 +870,11 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub { permitMainThreadToOpenCircuit.Set(); - // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). - permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); + // Hold this execution until rest of the test indicates it can proceed (or timeout, to expose deadlocks). + permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); - // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + // Throw a further failure when rest of test has already broken the circuit. + breaker.CircuitState.Should().Be(CircuitState.Open); return ResultPrimitive.Fault; }).Should().Be(ResultPrimitive.Fault); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original fault should still be returned. @@ -886,7 +886,7 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub breaker.CircuitState.Should().Be(CircuitState.Closed); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -907,33 +907,33 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub [Fact] public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_halfopen() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak, onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -954,10 +954,10 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ public void Should_not_call_onreset_on_successive_successful_calls() { Action, TimeSpan> onBreak = (_, _) => { }; - var onResetCalled = false; - var onReset = () => { onResetCalled = true; }; + bool onResetCalled = false; + Action onReset = () => { onResetCalled = true; }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -975,35 +975,35 @@ public void Should_not_call_onreset_on_successive_successful_calls() [Fact] public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -1021,35 +1021,35 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ [Fact] public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_state_read() { - var onBreakCalled = 0; - var onResetCalled = 0; - var onHalfOpenCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; + int onHalfOpenCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; - var onHalfOpen = () => { onHalfOpenCalled++; }; + Action onReset = () => { onResetCalled++; }; + Action onHalfOpen = () => { onHalfOpenCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); onBreakCalled.Should().Be(1); // 2 exception raised, circuit is now open breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + .Should().Throw(); breaker.CircuitState.Should().Be(CircuitState.Open); onBreakCalled.Should().Be(1); @@ -1062,19 +1062,19 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ [Fact] public void Should_call_onreset_when_manually_resetting_circuit() { - var onBreakCalled = 0; - var onResetCalled = 0; + int onBreakCalled = 0; + int onResetCalled = 0; Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - var onReset = () => { onResetCalled++; }; + Action onReset = () => { onResetCalled++; }; var time = 1.January(2000); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak, onBreak, onReset); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak, onBreak, onReset); onBreakCalled.Should().Be(0); breaker.Isolate(); @@ -1102,9 +1102,9 @@ public void Should_call_onbreak_with_the_last_handled_result() Action, TimeSpan, Context> onBreak = (outcome, _, _) => { handledResult = outcome.Result; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -1127,9 +1127,9 @@ public void Should_call_onbreak_with_the_correct_timespan() Action, TimeSpan, Context> onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; Action onReset = _ => { }; - var durationOfBreak = TimeSpan.FromMinutes(1); + TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -1156,7 +1156,7 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); breaker.CircuitState.Should().Be(CircuitState.Closed); @@ -1180,7 +1180,7 @@ public void Should_call_onbreak_with_the_passed_context() Action, TimeSpan, Context> onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -1188,7 +1188,7 @@ public void Should_call_onbreak_with_the_passed_context() .Should().Be(ResultPrimitive.Fault); breaker.RaiseResultSequence(new {key1 = "value1", key2 = "value2"}.AsDictionary(), - ResultPrimitive.Fault) + ResultPrimitive.Fault) .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); @@ -1211,7 +1211,7 @@ public void Should_call_onreset_with_the_passed_context() var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); @@ -1235,12 +1235,12 @@ public void Should_call_onreset_with_the_passed_context() [Fact] public void Context_should_be_empty_if_execute_not_called_with_any_context_data() { - var contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); + IDictionary contextData = new { key1 = "value1", key2 = "value2" }.AsDictionary(); Action, TimeSpan, Context> onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -1263,7 +1263,7 @@ public void Should_create_new_context_for_each_call_to_execute() Action, TimeSpan, Context> onBreak = (_, _, context) => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; }; Action onReset = context => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; }; - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); @@ -1302,7 +1302,7 @@ public void Should_create_new_context_for_each_call_to_execute() [Fact] public void Should_initialise_LastHandledResult_and_LastResult_to_default_on_creation() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1313,7 +1313,7 @@ public void Should_initialise_LastHandledResult_and_LastResult_to_default_on_cre [Fact] public void Should_set_LastHandledResult_on_handling_result_even_when_not_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1329,7 +1329,7 @@ public void Should_set_LastHandledResult_on_handling_result_even_when_not_breaki [Fact] public void Should_set_LastHandledResult_to_last_handled_result_when_breaking() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1348,7 +1348,7 @@ public void Should_set_LastHandledResult_to_last_handled_result_when_breaking() [Fact] public void Should_set_LastHandledResult_to_default_on_circuit_reset() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); @@ -1377,22 +1377,22 @@ public void Should_set_LastHandledResult_to_default_on_circuit_reset() public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; breaker.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good) + ResultPrimitive.Good) .Should().Be(ResultPrimitive.Good); attemptsInvoked.Should().Be(1); @@ -1402,17 +1402,17 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. }; @@ -1420,11 +1420,11 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().Throw() + .And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } @@ -1433,25 +1433,25 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good)) + ResultPrimitive.Good, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -1462,25 +1462,25 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec public void Should_report_cancellation_during_faulting_action_execution_when_user_delegate_observes_cancellationToken() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -1491,23 +1491,23 @@ public void Should_report_cancellation_during_faulting_action_execution_when_use public void Should_report_faulting_from_faulting_action_execution_when_user_delegate_does_not_observe_cancellation() { var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; breaker.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); attemptsInvoked.Should().Be(1); } @@ -1515,7 +1515,7 @@ public void Should_report_faulting_from_faulting_action_execution_when_user_dele [Fact] public void Should_report_cancellation_when_both_open_circuit_and_cancellation() { - var breaker = Policy + CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, TimeSpan.FromMinutes(1)); @@ -1527,23 +1527,23 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() .WithMessage("The circuit is now open and is not allowing calls."); // Circuit is now broken. - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; cancellationTokenSource.Cancel(); - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancelled manually instead - see above. ActionObservesCancellation = false }; breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -1556,26 +1556,26 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish OperationCanceledExceptions thrown with different CancellationTokens. var durationOfBreak = TimeSpan.FromMinutes(1); - var breaker = Policy - .HandleResult(ResultPrimitive.Fault) - .CircuitBreaker(2, durationOfBreak); + CircuitBreakerPolicy breaker = Policy + .HandleResult(ResultPrimitive.Fault) + .CircuitBreaker(2, durationOfBreak); - var policyCancellationTokenSource = new CancellationTokenSource(); - var policyCancellationToken = policyCancellationTokenSource.Token; + CancellationTokenSource policyCancellationTokenSource = new CancellationTokenSource(); + CancellationToken policyCancellationToken = policyCancellationTokenSource.Token; - var implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); - var implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; + CancellationTokenSource implicitlyCapturedActionCancellationTokenSource = new CancellationTokenSource(); + CancellationToken implicitlyCapturedActionCancellationToken = implicitlyCapturedActionCancellationTokenSource.Token; implicitlyCapturedActionCancellationTokenSource.Cancel(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; breaker.Invoking(x => x.Execute(_ => - { - attemptsInvoked++; - implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - return ResultPrimitive.Good; - }, policyCancellationToken)) + { + attemptsInvoked++; + implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); + return ResultPrimitive.Good; + }, policyCancellationToken)) .Should().Throw() .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); @@ -1588,4 +1588,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs b/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs index 7a3ad592bf1..a8869877448 100644 --- a/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs @@ -54,4 +54,4 @@ public void Should_be_able_to_use_LastException_via_interface() } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicyTResultSpecs.cs b/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicyTResultSpecs.cs index b679b3b2418..91a94bd8e22 100644 --- a/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicyTResultSpecs.cs +++ b/src/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicyTResultSpecs.cs @@ -19,4 +19,4 @@ public void Should_be_able_to_use_LastHandledResult_via_interface() } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/ContextSpecs.cs b/src/Polly.Specs/ContextSpecs.cs index 18e88e7f4ba..dcdcf1ab036 100644 --- a/src/Polly.Specs/ContextSpecs.cs +++ b/src/Polly.Specs/ContextSpecs.cs @@ -10,7 +10,7 @@ public class ContextSpecs [Fact] public void Should_assign_OperationKey_from_constructor() { - var context = new Context("SomeKey"); + Context context = new Context("SomeKey"); context.OperationKey.Should().Be("SomeKey"); @@ -20,7 +20,7 @@ public void Should_assign_OperationKey_from_constructor() [Fact] public void Should_assign_OperationKey_and_context_data_from_constructor() { - var context = new Context("SomeKey", new { key1 = "value1", key2 = "value2" }.AsDictionary()); + Context context = new Context("SomeKey", new { key1 = "value1", key2 = "value2" }.AsDictionary()); context.OperationKey.Should().Be("SomeKey"); context["key1"].Should().Be("value1"); @@ -30,7 +30,7 @@ public void Should_assign_OperationKey_and_context_data_from_constructor() [Fact] public void NoArgsCtor_should_assign_no_OperationKey() { - var context = new Context(); + Context context = new Context(); context.OperationKey.Should().BeNull(); } @@ -38,7 +38,7 @@ public void NoArgsCtor_should_assign_no_OperationKey() [Fact] public void Should_assign_CorrelationId_when_accessed() { - var context = new Context("SomeKey"); + Context context = new Context("SomeKey"); context.CorrelationId.Should().NotBeEmpty(); } @@ -46,11 +46,11 @@ public void Should_assign_CorrelationId_when_accessed() [Fact] public void Should_return_consistent_CorrelationId() { - var context = new Context("SomeKey"); + Context context = new Context("SomeKey"); - var retrieved1 = context.CorrelationId; - var retrieved2 = context.CorrelationId; + Guid retrieved1 = context.CorrelationId; + Guid retrieved2 = context.CorrelationId; retrieved1.Should().Be(retrieved2); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Custom/CustomAsyncSpecs.cs b/src/Polly.Specs/Custom/CustomAsyncSpecs.cs index cc8447b3c23..05c7043aad4 100644 --- a/src/Polly.Specs/Custom/CustomAsyncSpecs.cs +++ b/src/Polly.Specs/Custom/CustomAsyncSpecs.cs @@ -12,9 +12,9 @@ public class CustomAsyncSpecs [Fact] public void Should_be_able_to_construct_active_policy() { - var construct = () => + Action construct = () => { - var policy = AsyncPreExecutePolicy.CreateAsync(async () => + AsyncPreExecutePolicy policy = AsyncPreExecutePolicy.CreateAsync(async () => { // Placeholder for more substantive async work. Console.WriteLine("Do something"); @@ -26,15 +26,15 @@ public void Should_be_able_to_construct_active_policy() } [Fact] - public void Active_policy_should_execute() + public async Task Active_policy_should_execute() { - var preExecuted = false; - var policy = AsyncPreExecutePolicy.CreateAsync(() => { preExecuted = true; return Task.CompletedTask; }); + bool preExecuted = false; + AsyncPreExecutePolicy policy = AsyncPreExecutePolicy.CreateAsync(() => { preExecuted = true; return Task.CompletedTask; }); - var executed = false; + bool executed = false; - policy.Awaiting(x => x.ExecuteAsync(() => { executed = true; return Task.CompletedTask; })) - .Should().NotThrow(); + await policy.Awaiting(x => x.ExecuteAsync(() => { executed = true; return Task.CompletedTask; })) + .Should().NotThrowAsync(); executed.Should().BeTrue(); preExecuted.Should().BeTrue(); @@ -43,9 +43,9 @@ public void Active_policy_should_execute() [Fact] public void Should_be_able_to_construct_reactive_policy() { - var construct = () => + Action construct = () => { - var policy = Policy.Handle().WithBehaviourAsync(async ex => + AsyncAddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviourAsync(async ex => { // Placeholder for more substantive async work. Console.WriteLine("Handling " + ex.Message); @@ -57,42 +57,44 @@ public void Should_be_able_to_construct_reactive_policy() } [Fact] - public void Reactive_policy_should_handle_exception() + public async Task Reactive_policy_should_handle_exception() { Exception handled = null; - var policy = Policy.Handle().WithBehaviourAsync(async ex => { handled = ex; await Task.CompletedTask; }); + AsyncAddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviourAsync(async ex => { handled = ex; await Task.CompletedTask; }); Exception toThrow = new InvalidOperationException(); - var executed = false; + bool executed = false; - policy.Awaiting(x => x.ExecuteAsync(() => - { - executed = true; - throw toThrow; - })) - .Should().Throw().Which.Should().Be(toThrow); + var ex = await policy.Awaiting(x => x.ExecuteAsync(() => + { + executed = true; + throw toThrow; + })) + .Should().ThrowAsync(); + ex.Which.Should().Be(toThrow); executed.Should().BeTrue(); handled.Should().Be(toThrow); } [Fact] - public void Reactive_policy_should_be_able_to_ignore_unhandled_exception() + public async Task Reactive_policy_should_be_able_to_ignore_unhandled_exception() { Exception handled = null; - var policy = Policy.Handle().WithBehaviourAsync(async ex => { handled = ex; await Task.CompletedTask; }); + AsyncAddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviourAsync(async ex => { handled = ex; await Task.CompletedTask; }); Exception toThrow = new NotImplementedException(); - var executed = false; + bool executed = false; - policy.Awaiting(x => x.ExecuteAsync(() => + var ex = await policy.Awaiting(x => x.ExecuteAsync(() => { executed = true; throw toThrow; })) - .Should().Throw().Which.Should().Be(toThrow); + .Should().ThrowAsync(); + ex.Which.Should().Be(toThrow); executed.Should().BeTrue(); handled.Should().Be(null); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Custom/CustomSpecs.cs b/src/Polly.Specs/Custom/CustomSpecs.cs index f69217fd199..86779914890 100644 --- a/src/Polly.Specs/Custom/CustomSpecs.cs +++ b/src/Polly.Specs/Custom/CustomSpecs.cs @@ -11,9 +11,9 @@ public class CustomSpecs [Fact] public void Should_be_able_to_construct_active_policy() { - var construct = () => + Action construct = () => { - var policy = PreExecutePolicy.Create(() => Console.WriteLine("Do something")); + PreExecutePolicy policy = PreExecutePolicy.Create(() => Console.WriteLine("Do something")); }; construct.Should().NotThrow(); @@ -22,10 +22,10 @@ public void Should_be_able_to_construct_active_policy() [Fact] public void Active_policy_should_execute() { - var preExecuted = false; - var policy = PreExecutePolicy.Create(() => preExecuted = true); + bool preExecuted = false; + PreExecutePolicy policy = PreExecutePolicy.Create(() => preExecuted = true); - var executed = false; + bool executed = false; policy.Invoking(x => x.Execute(() => { executed = true; })) .Should().NotThrow(); @@ -37,9 +37,9 @@ public void Active_policy_should_execute() [Fact] public void Should_be_able_to_construct_reactive_policy() { - var construct = () => + Action construct = () => { - var policy = Policy.Handle().WithBehaviour(ex => Console.WriteLine("Handling " + ex.Message)); + AddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviour(ex => Console.WriteLine("Handling " + ex.Message)); }; construct.Should().NotThrow(); @@ -49,10 +49,10 @@ public void Should_be_able_to_construct_reactive_policy() public void Reactive_policy_should_handle_exception() { Exception handled = null; - var policy = Policy.Handle().WithBehaviour(ex => handled = ex); + AddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviour(ex => handled = ex); Exception toThrow = new InvalidOperationException(); - var executed = false; + bool executed = false; policy.Invoking(x => x.Execute(() => { executed = true; @@ -68,10 +68,10 @@ public void Reactive_policy_should_handle_exception() public void Reactive_policy_should_be_able_to_ignore_unhandled_exception() { Exception handled = null; - var policy = Policy.Handle().WithBehaviour(ex => handled = ex); + AddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviour(ex => handled = ex); Exception toThrow = new NotImplementedException(); - var executed = false; + bool executed = false; policy.Invoking(x => x.Execute(() => { executed = true; @@ -82,4 +82,4 @@ public void Reactive_policy_should_be_able_to_ignore_unhandled_exception() executed.Should().BeTrue(); handled.Should().Be(null); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs b/src/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs index a046521cb69..cafbd25f883 100644 --- a/src/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs +++ b/src/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs @@ -13,9 +13,9 @@ public class CustomTResultAsyncSpecs [Fact] public void Should_be_able_to_construct_active_policy() { - var construct = () => + Action construct = () => { - var policy = AsyncPreExecutePolicy.CreateAsync(async () => + AsyncPreExecutePolicy policy = AsyncPreExecutePolicy.CreateAsync(async () => { // Placeholder for more substantive async work. Console.WriteLine("Do something"); @@ -27,14 +27,14 @@ public void Should_be_able_to_construct_active_policy() } [Fact] - public void Active_policy_should_execute() + public async Task Active_policy_should_execute() { - var preExecuted = false; - var policy = AsyncPreExecutePolicy.CreateAsync(() => { preExecuted = true; return Task.CompletedTask; }); + bool preExecuted = false; + AsyncPreExecutePolicy policy = AsyncPreExecutePolicy.CreateAsync(() => { preExecuted = true; return Task.CompletedTask; }); - var executed = false; - policy.Awaiting(x => x.ExecuteAsync(async () => { executed = true; await Task.CompletedTask; return ResultPrimitive.Undefined; })) - .Should().NotThrow(); + bool executed = false; + await policy.Awaiting(x => x.ExecuteAsync(async () => { executed = true; await Task.CompletedTask; return ResultPrimitive.Undefined; })) + .Should().NotThrowAsync(); executed.Should().BeTrue(); preExecuted.Should().BeTrue(); @@ -43,9 +43,9 @@ public void Active_policy_should_execute() [Fact] public void Should_be_able_to_construct_reactive_policy() { - var construct = () => + Action construct = () => { - var policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviourAsync(async outcome => + AsyncAddBehaviourIfHandlePolicy policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviourAsync(async outcome => { // Placeholder for more substantive async work. Console.WriteLine("Handling " + outcome.Result); @@ -59,13 +59,13 @@ public void Should_be_able_to_construct_reactive_policy() [Fact] public async Task Reactive_policy_should_handle_result() { - var handled = ResultPrimitive.Undefined; - var policy = Policy + ResultPrimitive handled = ResultPrimitive.Undefined; + AsyncAddBehaviourIfHandlePolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .WithBehaviourAsync(async outcome => { handled = outcome.Result; await Task.CompletedTask; }); - var toReturn = ResultPrimitive.Fault; - var executed = false; + ResultPrimitive toReturn = ResultPrimitive.Fault; + bool executed = false; (await policy.ExecuteAsync(async () => { @@ -83,12 +83,12 @@ public async Task Reactive_policy_should_handle_result() public async Task Reactive_policy_should_be_able_to_ignore_unhandled_result() { ResultPrimitive? handled = null; - var policy = Policy + AsyncAddBehaviourIfHandlePolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .WithBehaviourAsync(async outcome => { handled = outcome.Result; await Task.CompletedTask; }); - var toReturn = ResultPrimitive.FaultYetAgain; - var executed = false; + ResultPrimitive toReturn = ResultPrimitive.FaultYetAgain; + bool executed = false; (await policy.ExecuteAsync(async () => { @@ -102,4 +102,4 @@ public async Task Reactive_policy_should_be_able_to_ignore_unhandled_result() handled.Should().Be(null); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Custom/CustomTResultSpecs.cs b/src/Polly.Specs/Custom/CustomTResultSpecs.cs index b6ce5282b50..521e636f0c2 100644 --- a/src/Polly.Specs/Custom/CustomTResultSpecs.cs +++ b/src/Polly.Specs/Custom/CustomTResultSpecs.cs @@ -12,9 +12,9 @@ public class CustomTResultSpecs [Fact] public void Should_be_able_to_construct_active_policy() { - var construct = () => + Action construct = () => { - var policy = PreExecutePolicy.Create(() => Console.WriteLine("Do something")); + PreExecutePolicy policy = PreExecutePolicy.Create(() => Console.WriteLine("Do something")); }; construct.Should().NotThrow(); @@ -23,10 +23,10 @@ public void Should_be_able_to_construct_active_policy() [Fact] public void Active_policy_should_execute() { - var preExecuted = false; - var policy = PreExecutePolicy.Create(() => preExecuted = true); + bool preExecuted = false; + PreExecutePolicy policy = PreExecutePolicy.Create(() => preExecuted = true); - var executed = false; + bool executed = false; policy.Invoking(x => x.Execute(() => { executed = true; @@ -41,9 +41,9 @@ public void Active_policy_should_execute() [Fact] public void Should_be_able_to_construct_reactive_policy() { - var construct = () => + Action construct = () => { - var policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviour(outcome => Console.WriteLine("Handling " + outcome.Result)); + AddBehaviourIfHandlePolicy policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviour(outcome => Console.WriteLine("Handling " + outcome.Result)); }; construct.Should().NotThrow(); @@ -52,11 +52,11 @@ public void Should_be_able_to_construct_reactive_policy() [Fact] public void Reactive_policy_should_handle_result() { - var handled = ResultPrimitive.Undefined; - var policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviour(outcome => handled = outcome.Result); + ResultPrimitive handled = ResultPrimitive.Undefined; + AddBehaviourIfHandlePolicy policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviour(outcome => handled = outcome.Result); - var toReturn = ResultPrimitive.Fault; - var executed = false; + ResultPrimitive toReturn = ResultPrimitive.Fault; + bool executed = false; policy.Execute(() => { @@ -73,10 +73,10 @@ public void Reactive_policy_should_handle_result() public void Reactive_policy_should_be_able_to_ignore_unhandled_result() { ResultPrimitive? handled = null; - var policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviour(outcome => handled = outcome.Result); + AddBehaviourIfHandlePolicy policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviour(outcome => handled = outcome.Result); - var toReturn = ResultPrimitive.FaultYetAgain; - var executed = false; + ResultPrimitive toReturn = ResultPrimitive.FaultYetAgain; + bool executed = false; policy.Execute(() => { @@ -89,4 +89,4 @@ public void Reactive_policy_should_be_able_to_ignore_unhandled_result() handled.Should().Be(null); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Fallback/FallbackAsyncSpecs.cs b/src/Polly.Specs/Fallback/FallbackAsyncSpecs.cs index d791d73defc..27a4c5dbfd4 100644 --- a/src/Polly.Specs/Fallback/FallbackAsyncSpecs.cs +++ b/src/Polly.Specs/Fallback/FallbackAsyncSpecs.cs @@ -49,8 +49,8 @@ public void Should_throw_when_fallback_func_is_null_with_onFallback_with_context Func onFallbackAsync = (_, _) => TaskHelper.EmptyTask; Action policy = () => Policy - .Handle() - .FallbackAsync(fallbackActionAsync, onFallbackAsync); + .Handle() + .FallbackAsync(fallbackActionAsync, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -63,8 +63,8 @@ public void Should_throw_when_onFallback_delegate_is_null() Func onFallbackAsync = null; Action policy = () => Policy - .Handle() - .FallbackAsync(fallbackActionAsync, onFallbackAsync); + .Handle() + .FallbackAsync(fallbackActionAsync, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("onFallbackAsync"); @@ -77,8 +77,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() Func onFallbackAsync = null; Action policy = () => Policy - .Handle() - .FallbackAsync(fallbackActionAsync, onFallbackAsync); + .Handle() + .FallbackAsync(fallbackActionAsync, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("onFallbackAsync"); @@ -91,12 +91,12 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() [Fact] public async Task Should_not_execute_fallback_when_executed_delegate_does_not_throw() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); await fallbackPolicy.ExecuteAsync(() => TaskHelper.EmptyTask); @@ -104,136 +104,136 @@ public async Task Should_not_execute_fallback_when_executed_delegate_does_not_th } [Fact] - public void Should_not_execute_fallback_when_executed_delegate_throws_exception_not_handled_by_policy() + public async Task Should_not_execute_fallback_when_executed_delegate_throws_exception_not_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().Throw(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_execute_fallback_when_executed_delegate_throws_exception_handled_by_policy() + public async Task Should_execute_fallback_when_executed_delegate_throws_exception_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrow(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); fallbackActionExecuted.Should().BeTrue(); } [Fact] - public void Should_execute_fallback_when_executed_delegate_throws_one_of_exceptions_handled_by_policy() + public async Task Should_execute_fallback_when_executed_delegate_throws_one_of_exceptions_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle() - .Or() - .FallbackAsync(fallbackActionAsync); + .Handle() + .Or() + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrow(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); fallbackActionExecuted.Should().BeTrue(); } [Fact] - public void Should_not_execute_fallback_when_executed_delegate_throws_exception_not_one_of_exceptions_handled_by_policy() + public async Task Should_not_execute_fallback_when_executed_delegate_throws_exception_not_one_of_exceptions_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle() - .Or() - .FallbackAsync(fallbackActionAsync); + .Handle() + .Or() + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().Throw(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_not_execute_fallback_when_exception_thrown_does_not_match_handling_predicates() + public async Task Should_not_execute_fallback_when_exception_thrown_does_not_match_handling_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle(_ => false) - .FallbackAsync(fallbackActionAsync); + .Handle(_ => false) + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().Throw(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_not_execute_fallback_when_exception_thrown_does_not_match_any_of_handling_predicates() + public async Task Should_not_execute_fallback_when_exception_thrown_does_not_match_any_of_handling_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle(_ => false) - .Or(_ => false) - .FallbackAsync(fallbackActionAsync); + .Handle(_ => false) + .Or(_ => false) + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().Throw(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_execute_fallback_when_exception_thrown_matches_handling_predicates() + public async Task Should_execute_fallback_when_exception_thrown_matches_handling_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle(_ => true) - .FallbackAsync(fallbackActionAsync); + .Handle(_ => true) + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrow(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); fallbackActionExecuted.Should().BeTrue(); } [Fact] - public void Should_execute_fallback_when_exception_thrown_matches_one_of_handling_predicates() + public async Task Should_execute_fallback_when_exception_thrown_matches_one_of_handling_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy - .Handle(_ => true) - .Or() - .FallbackAsync(fallbackActionAsync); + .Handle(_ => true) + .Or() + .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrow(); + await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); fallbackActionExecuted.Should().BeTrue(); } [Fact] - public void Should_not_handle_exception_thrown_by_fallback_delegate_even_if_is_exception_handled_by_policy() + public async Task Should_not_handle_exception_thrown_by_fallback_delegate_even_if_is_exception_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; @@ -244,20 +244,21 @@ public void Should_not_handle_exception_thrown_by_fallback_delegate_even_if_is_e .Handle() .FallbackAsync(fallbackActionAsync); - fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync((e, _) => e.HelpLink = "FromExecuteDelegate")) - .Should().Throw().And.HelpLink.Should().Be("FromFallbackAction"); + var ex = await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync((e, _) => e.HelpLink = "FromExecuteDelegate")) + .Should().ThrowAsync(); + ex.And.HelpLink.Should().Be("FromFallbackAction"); fallbackActionExecuted.Should().BeTrue(); } [Fact] - public void Should_throw_for_generic_method_execution_on_non_generic_policy() + public async Task Should_throw_for_generic_method_execution_on_non_generic_policy() { var fallbackPolicy = Policy .Handle() .FallbackAsync(_ => TaskHelper.EmptyTask); - fallbackPolicy.Awaiting(p => p.ExecuteAsync(() => Task.FromResult(0))).Should().Throw(); + await fallbackPolicy.Awaiting(p => p.ExecuteAsync(() => Task.FromResult(0))).Should().ThrowAsync(); } #endregion @@ -267,7 +268,7 @@ public void Should_throw_for_generic_method_execution_on_non_generic_policy() [Fact] public async Task Should_call_onFallback_passing_exception_triggering_fallback() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; Exception exceptionPassedToOnFallback = null; @@ -290,7 +291,7 @@ public async Task Should_not_call_onFallback_when_executed_delegate_does_not_thr { Func fallbackActionAsync = _ => TaskHelper.EmptyTask; - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Func onFallbackAsync = _ => { onFallbackExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy @@ -307,7 +308,7 @@ public async Task Should_not_call_onFallback_when_executed_delegate_does_not_thr #region Context passing tests [Fact] - public void Should_call_onFallback_with_the_passed_context() + public async Task Should_call_onFallback_with_the_passed_context() { Func fallbackActionAsync = (_, _) => TaskHelper.EmptyTask; @@ -319,9 +320,9 @@ public void Should_call_onFallback_with_the_passed_context() .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), - new { key1 = "value1", key2 = "value2" }.AsDictionary())) - .Should().NotThrow(); + await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), + new { key1 = "value1", key2 = "value2" }.AsDictionary())) + .Should().NotThrowAsync(); contextData.Should() .ContainKeys("key1", "key2").And @@ -329,7 +330,7 @@ public void Should_call_onFallback_with_the_passed_context() } [Fact] - public void Should_call_onFallback_with_the_passed_context_when_execute_and_capture() + public async Task Should_call_onFallback_with_the_passed_context_when_execute_and_capture() { Func fallbackActionAsync = (_, _) => TaskHelper.EmptyTask; @@ -341,9 +342,9 @@ public void Should_call_onFallback_with_the_passed_context_when_execute_and_capt .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new ArgumentNullException(), - new { key1 = "value1", key2 = "value2" }.AsDictionary())) - .Should().NotThrow(); + await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new ArgumentNullException(), + new { key1 = "value1", key2 = "value2" }.AsDictionary())) + .Should().NotThrowAsync(); contextData.Should() .ContainKeys("key1", "key2").And @@ -351,7 +352,7 @@ public void Should_call_onFallback_with_the_passed_context_when_execute_and_capt } [Fact] - public void Should_call_onFallback_with_independent_context_for_independent_calls() + public async Task Should_call_onFallback_with_independent_context_for_independent_calls() { Func fallbackActionAsync = (_, _) => TaskHelper.EmptyTask; @@ -364,11 +365,11 @@ public void Should_call_onFallback_with_independent_context_for_independent_call .Or() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), new { key = "value1" }.AsDictionary())) - .Should().NotThrow(); + await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), new { key = "value1" }.AsDictionary())) + .Should().NotThrowAsync(); - fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new DivideByZeroException(), new { key = "value2" }.AsDictionary())) - .Should().NotThrow(); + await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new DivideByZeroException(), new { key = "value2" }.AsDictionary())) + .Should().NotThrowAsync(); contextData.Count.Should().Be(2); contextData.Keys.Should().Contain(typeof(ArgumentNullException)); @@ -382,7 +383,7 @@ public void Should_call_onFallback_with_independent_context_for_independent_call public async Task Context_should_be_empty_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Func fallbackActionAsync = (_, _) => TaskHelper.EmptyTask; Func onFallbackAsync = (_, ctx) => { onFallbackExecuted = true; capturedContext = ctx; return TaskHelper.EmptyTask; }; @@ -399,7 +400,7 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context } [Fact] - public void Should_call_fallbackAction_with_the_passed_context() + public async Task Should_call_fallbackAction_with_the_passed_context() { IDictionary contextData = null; @@ -411,9 +412,9 @@ public void Should_call_fallbackAction_with_the_passed_context() .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), + await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), new { key1 = "value1", key2 = "value2" }.AsDictionary())) - .Should().NotThrow(); + .Should().NotThrowAsync(); contextData.Should() .ContainKeys("key1", "key2").And @@ -421,7 +422,7 @@ public void Should_call_fallbackAction_with_the_passed_context() } [Fact] - public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_capture() + public async Task Should_call_fallbackAction_with_the_passed_context_when_execute_and_capture() { IDictionary contextData = null; @@ -433,9 +434,9 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new ArgumentNullException(), + await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new ArgumentNullException(), new { key1 = "value1", key2 = "value2" }.AsDictionary())) - .Should().NotThrow(); + .Should().NotThrowAsync(); contextData.Should() .ContainKeys("key1", "key2").And @@ -446,7 +447,7 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ public async Task Context_should_be_empty_at_fallbackAction_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var fallbackExecuted = false; + bool fallbackExecuted = false; Func fallbackActionAsync = (ctx, _) => { fallbackExecuted = true; capturedContext = ctx; return TaskHelper.EmptyTask; }; @@ -468,7 +469,7 @@ public async Task Context_should_be_empty_at_fallbackAction_if_execute_not_calle #region Exception passing tests [Fact] - public void Should_call_fallbackAction_with_the_exception() + public async Task Should_call_fallbackAction_with_the_exception() { Exception fallbackException = null; @@ -481,14 +482,14 @@ public void Should_call_fallbackAction_with_the_exception() .FallbackAsync(fallbackFunc, onFallback); Exception instanceToThrow = new ArgumentNullException("myParam"); - fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) - .Should().NotThrow(); + await fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) + .Should().NotThrowAsync(); fallbackException.Should().Be(instanceToThrow); } [Fact] - public void Should_call_fallbackAction_with_the_exception_when_execute_and_capture() + public async Task Should_call_fallbackAction_with_the_exception_when_execute_and_capture() { Exception fallbackException = null; @@ -500,15 +501,15 @@ public void Should_call_fallbackAction_with_the_exception_when_execute_and_captu .Handle() .FallbackAsync(fallbackFunc, onFallback); - fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(() => throw new ArgumentNullException())) - .Should().NotThrow(); + await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(() => throw new ArgumentNullException())) + .Should().NotThrowAsync(); fallbackException.Should().NotBeNull() .And.BeOfType(typeof(ArgumentNullException)); } [Fact] - public void Should_call_fallbackAction_with_the_matched_inner_exception_unwrapped() + public async Task Should_call_fallbackAction_with_the_matched_inner_exception_unwrapped() { Exception fallbackException = null; @@ -521,15 +522,15 @@ public void Should_call_fallbackAction_with_the_matched_inner_exception_unwrappe .FallbackAsync(fallbackFunc, onFallback); Exception instanceToCapture = new ArgumentNullException("myParam"); - var instanceToThrow = new Exception(String.Empty, instanceToCapture); - fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) - .Should().NotThrow(); + Exception instanceToThrow = new Exception(String.Empty, instanceToCapture); + await fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) + .Should().NotThrowAsync(); fallbackException.Should().Be(instanceToCapture); } [Fact] - public void Should_call_fallbackAction_with_the_matched_inner_of_aggregate_exception_unwrapped() + public async Task Should_call_fallbackAction_with_the_matched_inner_of_aggregate_exception_unwrapped() { Exception fallbackException = null; @@ -543,14 +544,14 @@ public void Should_call_fallbackAction_with_the_matched_inner_of_aggregate_excep Exception instanceToCapture = new ArgumentNullException("myParam"); Exception instanceToThrow = new AggregateException(instanceToCapture); - fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) - .Should().NotThrow(); + await fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) + .Should().NotThrowAsync(); fallbackException.Should().Be(instanceToCapture); } [Fact] - public void Should_not_call_fallbackAction_with_the_exception_if_exception_unhandled() + public async Task Should_not_call_fallbackAction_with_the_exception_if_exception_unhandled() { Exception fallbackException = null; @@ -562,8 +563,8 @@ public void Should_not_call_fallbackAction_with_the_exception_if_exception_unhan .Handle() .FallbackAsync(fallbackFunc, onFallback); - fallbackPolicy.Awaiting(p => p.ExecuteAsync(() => throw new ArgumentNullException())) - .Should().Throw(); + await fallbackPolicy.Awaiting(p => p.ExecuteAsync(() => throw new ArgumentNullException())) + .Should().ThrowAsync(); fallbackException.Should().BeNull(); } @@ -573,80 +574,80 @@ public void Should_not_call_fallbackAction_with_the_exception_if_exception_unhan #region Cancellation tests [Fact] - public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_execute_fallback_when_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_fallback_when_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeTrue(); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -654,9 +655,9 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); fallbackActionExecuted.Should().BeFalse(); @@ -664,157 +665,157 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex } [Fact] - public void Should_report_cancellation_and_not_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_does_not_handle_cancellations() + public async Task Should_report_cancellation_and_not_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_does_not_handle_cancellations() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_handles_cancellations() + public async Task Should_handle_cancellation_and_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_handles_cancellations() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var policy = Policy - .Handle() - .Or() - .FallbackAsync(fallbackActionAsync); + .Handle() + .Or() + .FallbackAsync(fallbackActionAsync); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeTrue(); } [Fact] - public void Should_not_report_cancellation_and_not_execute_fallback_if_non_faulting_action_execution_completes_and_user_delegate_does_not_observe_the_set_cancellationToken() + public async Task Should_not_report_cancellation_and_not_execute_fallback_if_non_faulting_action_execution_completes_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_execution_raises_unhandled_fault_and_user_delegate_does_not_observe_the_set_cancellationToken() + public async Task Should_report_unhandled_fault_and_not_execute_fallback_if_action_execution_raises_unhandled_fault_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeFalse(); } [Fact] - public void Should_handle_handled_fault_and_execute_fallback_following_faulting_action_execution_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_handle_handled_fault_and_execute_fallback_following_faulting_action_execution_when_user_delegate_does_not_observe_cancellationToken() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + .Handle() + .FallbackAsync(fallbackActionAsync); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeTrue(); @@ -823,4 +824,4 @@ public void Should_handle_handled_fault_and_execute_fallback_following_faulting_ #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Fallback/FallbackSpecs.cs b/src/Polly.Specs/Fallback/FallbackSpecs.cs index e160d7de427..6feb3e1e8a3 100644 --- a/src/Polly.Specs/Fallback/FallbackSpecs.cs +++ b/src/Polly.Specs/Fallback/FallbackSpecs.cs @@ -20,8 +20,8 @@ public void Should_throw_when_fallback_action_is_null() Action fallbackAction = null; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -47,8 +47,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback() Action onFallback = _ => { }; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -75,8 +75,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback_with_conte Action onFallback = (_, _) => { }; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -89,8 +89,8 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF Action onFallback = (_, _) => { }; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -99,12 +99,12 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF [Fact] public void Should_throw_when_onFallback_delegate_is_null() { - var fallbackAction = () => { }; + Action fallbackAction = () => { }; Action onFallback = null; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("onFallback"); @@ -131,8 +131,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() Action onFallback = null; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("onFallback"); @@ -145,8 +145,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti Action onFallback = null; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("onFallback"); @@ -159,12 +159,12 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti [Fact] public void Should_not_execute_fallback_when_executed_delegate_does_not_throw() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .Handle() + .Fallback(fallbackAction); fallbackPolicy.Execute(() => { }); @@ -174,12 +174,12 @@ public void Should_not_execute_fallback_when_executed_delegate_does_not_throw() [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_exception_not_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .Handle() + .Fallback(fallbackAction); fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); @@ -190,10 +190,10 @@ public void Should_not_execute_fallback_when_executed_delegate_throws_exception_ [Fact] public void Should_execute_fallback_when_executed_delegate_throws_exception_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction); @@ -205,10 +205,10 @@ public void Should_execute_fallback_when_executed_delegate_throws_exception_hand [Fact] public void Should_execute_fallback_when_executed_delegate_throws_one_of_exceptions_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Or() .Fallback(fallbackAction); @@ -221,13 +221,13 @@ public void Should_execute_fallback_when_executed_delegate_throws_one_of_excepti [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_exception_not_one_of_exceptions_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .Handle() - .Or() - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .Handle() + .Or() + .Fallback(fallbackAction); fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); @@ -237,12 +237,12 @@ public void Should_not_execute_fallback_when_executed_delegate_throws_exception_ [Fact] public void Should_not_execute_fallback_when_exception_thrown_does_not_match_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .Handle(_ => false) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .Handle(_ => false) + .Fallback(fallbackAction); fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); @@ -252,13 +252,13 @@ public void Should_not_execute_fallback_when_exception_thrown_does_not_match_han [Fact] public void Should_not_execute_fallback_when_exception_thrown_does_not_match_any_of_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .Handle(_ => false) - .Or(_ => false) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .Handle(_ => false) + .Or(_ => false) + .Fallback(fallbackAction); fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); @@ -268,10 +268,10 @@ public void Should_not_execute_fallback_when_exception_thrown_does_not_match_any [Fact] public void Should_execute_fallback_when_exception_thrown_matches_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle(_ => true) .Fallback(fallbackAction); @@ -283,10 +283,10 @@ public void Should_execute_fallback_when_exception_thrown_matches_handling_predi [Fact] public void Should_execute_fallback_when_exception_thrown_matches_one_of_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle(_ => true) .Or() .Fallback(fallbackAction); @@ -299,14 +299,14 @@ public void Should_execute_fallback_when_exception_thrown_matches_one_of_handlin [Fact] public void Should_not_handle_exception_thrown_by_fallback_delegate_even_if_is_exception_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; throw new DivideByZeroException {HelpLink = "FromFallbackAction"}; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction); @@ -319,7 +319,7 @@ public void Should_not_handle_exception_thrown_by_fallback_delegate_even_if_is_e [Fact] public void Should_throw_for_generic_method_execution_on_non_generic_policy() { - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(() => {}); @@ -333,14 +333,14 @@ public void Should_throw_for_generic_method_execution_on_non_generic_policy() [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_inner_exception_where_policy_doesnt_handle_inner() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new DivideByZeroException()); + Exception withInner = new Exception(String.Empty, new DivideByZeroException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); @@ -350,10 +350,10 @@ public void Should_not_execute_fallback_when_executed_delegate_throws_inner_exce [Fact] public void Should_execute_fallback_when_policy_handles_inner_and_executed_delegate_throws_as_non_inner() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction); @@ -367,14 +367,14 @@ public void Should_execute_fallback_when_policy_handles_inner_and_executed_deleg [Fact] public void Should_execute_fallback_when_executed_delegate_throws_inner_exception_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new DivideByZeroException()); + Exception withInner = new Exception(String.Empty, new DivideByZeroException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); @@ -384,15 +384,15 @@ public void Should_execute_fallback_when_executed_delegate_throws_inner_exceptio [Fact] public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_exceptions_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .OrInner() .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new ArgumentException()); + Exception withInner = new Exception(String.Empty, new ArgumentException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); @@ -402,14 +402,14 @@ public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_e [Fact] public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_exception_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new Exception(String.Empty, new Exception(String.Empty, new DivideByZeroException()))); + Exception withInner = new Exception(String.Empty, new Exception(String.Empty, new Exception(String.Empty, new DivideByZeroException()))); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); @@ -420,14 +420,14 @@ public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_e [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_inner_exception_not_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .HandleInner() - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleInner() + .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new ArgumentException()); + Exception withInner = new Exception(String.Empty, new ArgumentException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); @@ -437,14 +437,14 @@ public void Should_not_execute_fallback_when_executed_delegate_throws_inner_exce [Fact] public void Should_execute_fallback_when_inner_exception_thrown_matches_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new DivideByZeroException()); + Exception withInner = new Exception(String.Empty, new DivideByZeroException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); @@ -454,14 +454,14 @@ public void Should_execute_fallback_when_inner_exception_thrown_matches_handling [Fact] public void Should_execute_fallback_when_inner_nested_exception_thrown_matches_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new Exception(String.Empty, new Exception(String.Empty, new DivideByZeroException()))); + Exception withInner = new Exception(String.Empty, new Exception(String.Empty, new Exception(String.Empty, new DivideByZeroException()))); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); @@ -472,15 +472,15 @@ public void Should_execute_fallback_when_inner_nested_exception_thrown_matches_h [Fact] public void Should_execute_fallback_when_inner_exception_thrown_matches_one_of_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) .OrInner(_ => true) .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new ArgumentNullException()); + Exception withInner = new Exception(String.Empty, new ArgumentNullException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); @@ -490,14 +490,14 @@ public void Should_execute_fallback_when_inner_exception_thrown_matches_one_of_h [Fact] public void Should_not_execute_fallback_when_inner_exception_thrown_does_not_match_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .HandleInner(_ => false) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleInner(_ => false) + .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new DivideByZeroException()); + Exception withInner = new Exception(String.Empty, new DivideByZeroException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); @@ -507,15 +507,15 @@ public void Should_not_execute_fallback_when_inner_exception_thrown_does_not_mat [Fact] public void Should_not_execute_fallback_when_inner_exception_thrown_does_not_match_any_of_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .HandleInner(_ => false) - .OrInner(_ => false) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleInner(_ => false) + .OrInner(_ => false) + .Fallback(fallbackAction); - var withInner = new Exception(String.Empty, new ArgumentNullException()); + Exception withInner = new Exception(String.Empty, new ArgumentNullException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); @@ -530,10 +530,10 @@ public void Should_not_execute_fallback_when_inner_exception_thrown_does_not_mat [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_inner_of_aggregate_exception_where_policy_doesnt_handle_inner() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction); @@ -547,10 +547,10 @@ public void Should_not_execute_fallback_when_executed_delegate_throws_inner_of_a [Fact] public void Should_execute_fallback_when_executed_delegate_throws_inner_of_aggregate_exception_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction); @@ -564,10 +564,10 @@ public void Should_execute_fallback_when_executed_delegate_throws_inner_of_aggre [Fact] public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_of_aggregate_exceptions_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .OrInner() .Fallback(fallbackAction); @@ -582,10 +582,10 @@ public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_o [Fact] public void Should_execute_fallback_when_executed_delegate_throws_aggregate_exception_with_inner_handled_by_policy_amongst_other_inners() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction); @@ -599,10 +599,10 @@ public void Should_execute_fallback_when_executed_delegate_throws_aggregate_exce [Fact] public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_of_aggregate_exception_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction); @@ -616,27 +616,27 @@ public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_o [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_inner_of_aggregate_exception_not_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .HandleInner() - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleInner() + .Fallback(fallbackAction); Exception withInner = new AggregateException(new ArgumentException()); fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerExceptions.Should().ContainSingle(e => e is ArgumentException); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.Should().BeFalse(); } [Fact] public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_matches_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) .Fallback(fallbackAction); @@ -650,10 +650,10 @@ public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_mat [Fact] public void Should_execute_fallback_when_inner_of_aggregate_nested_exception_thrown_matches_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) .Fallback(fallbackAction); @@ -668,10 +668,10 @@ public void Should_execute_fallback_when_inner_of_aggregate_nested_exception_thr [Fact] public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_matches_one_of_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) .OrInner(_ => true) .Fallback(fallbackAction); @@ -686,12 +686,12 @@ public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_mat [Fact] public void Should_not_execute_fallback_when_inner_of_aggregate_exception_thrown_does_not_match_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .HandleInner(_ => false) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleInner(_ => false) + .Fallback(fallbackAction); Exception withInner = new AggregateException(new DivideByZeroException()); @@ -703,13 +703,13 @@ public void Should_not_execute_fallback_when_inner_of_aggregate_exception_thrown [Fact] public void Should_not_execute_fallback_when_inner_of_aggregate_exception_thrown_does_not_match_any_of_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var fallbackPolicy = Policy - .HandleInner(_ => false) - .OrInner(_ => false) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleInner(_ => false) + .OrInner(_ => false) + .Fallback(fallbackAction); Exception withInner = new AggregateException(new ArgumentNullException()); @@ -725,13 +725,13 @@ public void Should_not_execute_fallback_when_inner_of_aggregate_exception_thrown [Fact] public void Should_call_onFallback_passing_exception_triggering_fallback() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; Exception exceptionPassedToOnFallback = null; Action onFallback = ex => { exceptionPassedToOnFallback = ex; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); @@ -746,12 +746,12 @@ public void Should_call_onFallback_passing_exception_triggering_fallback() [Fact] public void Should_not_call_onFallback_when_executed_delegate_does_not_throw() { - var fallbackAction = () => { }; + Action fallbackAction = () => { }; - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Action onFallback = _ => { onFallbackExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); @@ -773,12 +773,12 @@ public void Should_call_onFallback_with_the_passed_context() Action onFallback = (_, ctx) => { contextData = ctx; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); fallbackPolicy.Invoking(p => p.Execute(_ => throw new ArgumentNullException(), - new {key1 = "value1", key2 = "value2"}.AsDictionary())) + new {key1 = "value1", key2 = "value2"}.AsDictionary())) .Should().NotThrow(); contextData.Should() @@ -795,12 +795,12 @@ public void Should_call_onFallback_with_the_passed_context_when_execute_and_capt Action onFallback = (_, ctx) => { contextData = ctx; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); fallbackPolicy.Invoking(p => p.ExecuteAndCapture(_ => throw new ArgumentNullException(), - new {key1 = "value1", key2 = "value2"}.AsDictionary())) + new {key1 = "value1", key2 = "value2"}.AsDictionary())) .Should().NotThrow(); contextData.Should() @@ -817,17 +817,17 @@ public void Should_call_onFallback_with_independent_context_for_independent_call Action onFallback = (ex, ctx) => { contextData[ex.GetType()] = ctx["key"]; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Or() .Fallback(fallbackAction, onFallback); fallbackPolicy.Invoking( - p => p.Execute(_ => throw new ArgumentNullException(), new {key = "value1"}.AsDictionary())) + p => p.Execute(_ => throw new ArgumentNullException(), new {key = "value1"}.AsDictionary())) .Should().NotThrow(); fallbackPolicy.Invoking( - p => p.Execute(_ => throw new DivideByZeroException(), new {key = "value2"}.AsDictionary())) + p => p.Execute(_ => throw new DivideByZeroException(), new {key = "value2"}.AsDictionary())) .Should().NotThrow(); contextData.Count.Should().Be(2); @@ -842,12 +842,12 @@ public void Should_call_onFallback_with_independent_context_for_independent_call public void Context_should_be_empty_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Action fallbackAction = _ => { }; Action onFallback = (_, ctx) => { onFallbackExecuted = true; capturedContext = ctx; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Or() .Fallback(fallbackAction, onFallback); @@ -867,7 +867,7 @@ public void Should_call_fallbackAction_with_the_passed_context() Action onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); @@ -889,7 +889,7 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ Action onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); @@ -906,12 +906,12 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ public void Context_should_be_empty_at_fallbackAction_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var fallbackExecuted = false; + bool fallbackExecuted = false; Action fallbackAction = (ctx, _) => { fallbackExecuted = true; capturedContext = ctx; }; Action onFallback = (_, _) => {}; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Or() .Fallback(fallbackAction, onFallback); @@ -935,7 +935,7 @@ public void Should_call_fallbackAction_with_the_exception() Action onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); @@ -955,7 +955,7 @@ public void Should_call_fallbackAction_with_the_exception_when_execute_and_captu Action onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); fallbackPolicy.Invoking(p => p.ExecuteAndCapture(() => throw new ArgumentNullException())) @@ -974,12 +974,12 @@ public void Should_call_fallbackAction_with_the_matched_inner_exception_unwrappe Action onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction, onFallback); Exception instanceToCapture = new ArgumentNullException("myParam"); - var instanceToThrow = new Exception(String.Empty, instanceToCapture); + Exception instanceToThrow = new Exception(String.Empty, instanceToCapture); fallbackPolicy.Invoking(p => p.RaiseException(instanceToThrow)) .Should().NotThrow(); @@ -995,7 +995,7 @@ public void Should_call_fallbackAction_with_the_matched_inner_of_aggregate_excep Action onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleInner() .Fallback(fallbackAction, onFallback); @@ -1017,7 +1017,7 @@ public void Should_not_call_fallbackAction_with_the_exception_if_exception_unhan Action onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); @@ -1034,19 +1034,19 @@ public void Should_not_call_fallbackAction_with_the_exception_if_exception_unhan [Fact] public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var policy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, @@ -1062,19 +1062,19 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca [Fact] public void Should_execute_fallback_when_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var policy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, @@ -1090,20 +1090,20 @@ public void Should_execute_fallback_when_faulting_and_cancellationToken_not_canc [Fact] public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var policy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -1123,20 +1123,20 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex [Fact] public void Should_report_cancellation_and_not_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_does_not_handle_cancellations() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var policy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1154,20 +1154,20 @@ public void Should_report_cancellation_and_not_execute_fallback_during_otherwise [Fact] public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_handles_cancellations() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var policy = Policy - .Handle() - .Or() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Or() + .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1184,19 +1184,19 @@ public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non [Fact] public void Should_not_report_cancellation_and_not_execute_fallback_if_non_faulting_action_execution_completes_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var policy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1213,19 +1213,19 @@ public void Should_not_report_cancellation_and_not_execute_fallback_if_non_fault [Fact] public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_execution_raises_unhandled_fault_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var policy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, @@ -1242,19 +1242,19 @@ public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_exe [Fact] public void Should_handle_handled_fault_and_execute_fallback_following_faulting_action_execution_when_user_delegate_does_not_observe_cancellationToken() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; }; + bool fallbackActionExecuted = false; + Action fallbackAction = () => { fallbackActionExecuted = true; }; - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var policy = Policy - .Handle() - .Fallback(fallbackAction); + FallbackPolicy policy = Policy + .Handle() + .Fallback(fallbackAction); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1, AttemptDuringWhichToCancel = 1, @@ -1272,4 +1272,4 @@ public void Should_handle_handled_fault_and_execute_fallback_following_faulting_ -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs b/src/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs index ac6ad23f998..cf62109483b 100644 --- a/src/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs +++ b/src/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs @@ -21,8 +21,8 @@ public void Should_throw_when_fallback_action_is_null() Func> fallbackAction = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -35,8 +35,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback() Func, Task> onFallbackAsync = _ => TaskHelper.EmptyTask; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -49,8 +49,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback_with_conte Func, Context, Task> onFallbackAsync = (_, _) => TaskHelper.EmptyTask; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -63,8 +63,8 @@ public void Should_throw_when_onFallback_delegate_is_null() Func, Task> onFallbackAsync = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("onFallbackAsync"); @@ -91,8 +91,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() Func, Context, Task> onFallbackAsync = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("onFallbackAsync"); @@ -105,8 +105,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti Func, Context, Task> onFallbackAsync = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); policy.Should().Throw() .And.ParamName.Should().Be("onFallbackAsync"); @@ -119,12 +119,12 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti [Fact] public async Task Should_not_execute_fallback_when_executed_delegate_does_not_raise_fault() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); await fallbackPolicy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); @@ -134,12 +134,12 @@ public async Task Should_not_execute_fallback_when_executed_delegate_does_not_ra [Fact] public async Task Should_not_execute_fallback_when_executed_delegate_raises_fault_not_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) .Should().Be(ResultPrimitive.FaultAgain); @@ -151,8 +151,8 @@ public async Task Should_not_execute_fallback_when_executed_delegate_raises_faul public async Task Should_return_fallback_value_when_executed_delegate_raises_fault_handled_by_policy() { var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(ResultPrimitive.Substitute); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(ResultPrimitive.Substitute); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) .Should().Be(ResultPrimitive.Substitute); @@ -161,12 +161,12 @@ public async Task Should_return_fallback_value_when_executed_delegate_raises_fau [Fact] public async Task Should_execute_fallback_when_executed_delegate_raises_fault_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) .Should().Be(ResultPrimitive.Substitute); @@ -177,13 +177,13 @@ public async Task Should_execute_fallback_when_executed_delegate_raises_fault_ha [Fact] public async Task Should_execute_fallback_when_executed_delegate_raises_one_of_results_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) .Should().Be(ResultPrimitive.Substitute); @@ -194,13 +194,13 @@ public async Task Should_execute_fallback_when_executed_delegate_raises_one_of_r [Fact] public async Task Should_not_execute_fallback_when_executed_delegate_raises_fault_not_one_of_faults_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultYetAgain)) .Should().Be(ResultPrimitive.FaultYetAgain); @@ -211,12 +211,12 @@ public async Task Should_not_execute_fallback_when_executed_delegate_raises_faul [Fact] public async Task Should_not_execute_fallback_when_result_raised_does_not_match_handling_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(_ => false) - .FallbackAsync(fallbackAction); + .HandleResult(_ => false) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) .Should().Be(ResultPrimitive.Fault); @@ -227,13 +227,13 @@ public async Task Should_not_execute_fallback_when_result_raised_does_not_match_ [Fact] public async Task Should_not_execute_fallback_when_executed_delegate_raises_fault_not_handled_by_any_of_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(r => r == ResultPrimitive.Fault) - .OrResult(r => r == ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(r => r == ResultPrimitive.Fault) + .OrResult(r => r == ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultYetAgain)) .Should().Be(ResultPrimitive.FaultYetAgain); @@ -244,12 +244,12 @@ public async Task Should_not_execute_fallback_when_executed_delegate_raises_faul [Fact] public async Task Should_execute_fallback_when_result_raised_matches_handling_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(_ => true) - .FallbackAsync(fallbackAction); + .HandleResult(_ => true) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Undefined)) .Should().Be(ResultPrimitive.Substitute); @@ -261,13 +261,13 @@ public async Task Should_execute_fallback_when_result_raised_matches_handling_pr [Fact] public async Task Should_execute_fallback_when_result_raised_matches_one_of_handling_predicates() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(_ => true) - .OrResult(ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(_ => true) + .OrResult(ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Undefined)) .Should().Be(ResultPrimitive.Substitute); @@ -278,7 +278,7 @@ public async Task Should_execute_fallback_when_result_raised_matches_one_of_hand [Fact] public async Task Should_not_handle_result_raised_by_fallback_delegate_even_if_is_result_handled_by_policy() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; @@ -302,7 +302,7 @@ public async Task Should_not_handle_result_raised_by_fallback_delegate_even_if_i [Fact] public async Task Should_call_onFallback_passing_result_triggering_fallback() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(new ResultClass(ResultPrimitive.Substitute)); }; ResultClass resultPassedToOnFallback = null; @@ -312,7 +312,7 @@ public async Task Should_call_onFallback_passing_result_triggering_fallback() .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .FallbackAsync(fallbackAction, onFallbackAsync); - var resultFromDelegate = new ResultClass(ResultPrimitive.Fault); + ResultClass resultFromDelegate = new ResultClass(ResultPrimitive.Fault); await fallbackPolicy.ExecuteAsync(() => Task.FromResult(resultFromDelegate)); fallbackActionExecuted.Should().BeTrue(); @@ -323,9 +323,9 @@ public async Task Should_call_onFallback_passing_result_triggering_fallback() [Fact] public async Task Should_not_call_onFallback_when_executed_delegate_does_not_raise_fault() { - Func> fallbackAction = _ => Task.FromResult(ResultPrimitive.Substitute); + Func> fallbackAction = _ => Task.FromResult(ResultPrimitive.Substitute); - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Func, Task> onFallbackAsync = _ => { onFallbackExecuted = true; return TaskHelper.EmptyTask; }; var fallbackPolicy = Policy @@ -355,7 +355,7 @@ public void Should_call_onFallback_with_the_passed_context() .FallbackAsync(fallbackAction, onFallbackAsync); fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Fault), - new { key1 = "value1", key2 = "value2" }.AsDictionary()) + new { key1 = "value1", key2 = "value2" }.AsDictionary()) .Result .Should().Be(ResultPrimitive.Substitute); @@ -378,7 +378,7 @@ public async Task Should_call_onFallback_with_the_passed_context_when_execute_an .FallbackAsync(fallbackAction, onFallbackAsync); (await fallbackPolicy.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Fault), - new { key1 = "value1", key2 = "value2" }.AsDictionary())) + new { key1 = "value1", key2 = "value2" }.AsDictionary())) .Result.Should().Be(ResultPrimitive.Substitute); contextData.Should() @@ -419,7 +419,7 @@ public void Should_call_onFallback_with_independent_context_for_independent_call public async Task Context_should_be_empty_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Func> fallbackAction = (_, _) => Task.FromResult(ResultPrimitive.Substitute); Func, Context, Task> onFallbackAsync = (_, ctx) => { onFallbackExecuted = true; capturedContext = ctx; return TaskHelper.EmptyTask; }; @@ -460,7 +460,7 @@ public void Should_call_fallbackAction_with_the_passed_context() } [Fact] - public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_capture() + public async Task Should_call_fallbackAction_with_the_passed_context_when_execute_and_capture() { IDictionary contextData = null; @@ -472,9 +472,9 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ .HandleResult(ResultPrimitive.Fault) .FallbackAsync(fallbackActionAsync, onFallbackAsync); - fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Fault), + await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Fault), new { key1 = "value1", key2 = "value2" }.AsDictionary())) - .Should().NotThrow(); + .Should().NotThrowAsync(); contextData.Should() .ContainKeys("key1", "key2").And @@ -485,7 +485,7 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ public async Task Context_should_be_empty_at_fallbackAction_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var fallbackExecuted = false; + bool fallbackExecuted = false; Func> fallbackActionAsync = (ctx, _) => { fallbackExecuted = true; capturedContext = ctx; return Task.FromResult(ResultPrimitive.Substitute); }; @@ -580,7 +580,7 @@ public async Task Should_not_call_fallbackAction_with_the_fault_if_fault_unhandl [Fact] public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var policy = Policy @@ -588,13 +588,13 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; @@ -609,7 +609,7 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ [Fact] public async Task Should_execute_fallback_when_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var policy = Policy @@ -617,13 +617,13 @@ public async Task Should_execute_fallback_when_faulting_and_cancellationToken_no .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; @@ -636,9 +636,9 @@ public async Task Should_execute_fallback_when_faulting_and_cancellationToken_no } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var policy = Policy @@ -646,22 +646,22 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. }; cancellationTokenSource.Cancel(); - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); fallbackActionExecuted.Should().BeFalse(); @@ -669,9 +669,9 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex } [Fact] - public void Should_report_cancellation_and_not_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_does_not_handle_cancellations() + public async Task Should_report_cancellation_and_not_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_does_not_handle_cancellations() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var policy = Policy @@ -679,21 +679,21 @@ public void Should_report_cancellation_and_not_execute_fallback_during_otherwise .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); fallbackActionExecuted.Should().BeFalse(); @@ -702,7 +702,7 @@ public void Should_report_cancellation_and_not_execute_fallback_during_otherwise [Fact] public async Task Should_handle_cancellation_and_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_handles_cancellations() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var policy = Policy @@ -711,13 +711,13 @@ public async Task Should_handle_cancellation_and_execute_fallback_during_otherwi .Or() .FallbackAsync(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true @@ -733,7 +733,7 @@ public async Task Should_handle_cancellation_and_execute_fallback_during_otherwi [Fact] public async Task Should_not_report_cancellation_and_not_execute_fallback_if_non_faulting_action_execution_completes_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var policy = Policy @@ -741,13 +741,13 @@ public async Task Should_not_report_cancellation_and_not_execute_fallback_if_non .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false @@ -763,7 +763,7 @@ public async Task Should_not_report_cancellation_and_not_execute_fallback_if_non [Fact] public async Task Should_report_unhandled_fault_and_not_execute_fallback_if_action_execution_raises_unhandled_fault_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var policy = Policy @@ -771,13 +771,13 @@ public async Task Should_report_unhandled_fault_and_not_execute_fallback_if_acti .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false @@ -793,21 +793,21 @@ public async Task Should_report_unhandled_fault_and_not_execute_fallback_if_acti [Fact] public async Task Should_handle_handled_fault_and_execute_fallback_following_faulting_action_execution_when_user_delegate_does_not_observe_cancellationToken() { - var fallbackActionExecuted = false; + bool fallbackActionExecuted = false; Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false @@ -823,4 +823,4 @@ public async Task Should_handle_handled_fault_and_execute_fallback_following_fau #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Fallback/FallbackTResultSpecs.cs b/src/Polly.Specs/Fallback/FallbackTResultSpecs.cs index 5d932c4bd96..1d028e36851 100644 --- a/src/Polly.Specs/Fallback/FallbackTResultSpecs.cs +++ b/src/Polly.Specs/Fallback/FallbackTResultSpecs.cs @@ -20,8 +20,8 @@ public void Should_throw_when_fallback_action_is_null() Func fallbackAction = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -47,8 +47,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback() Action> onFallback = _ => { }; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction, onFallback); + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -75,8 +75,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback_with_conte Action, Context> onFallback = (_, _) => { }; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction, onFallback); + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -89,8 +89,8 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF Action, Context> onFallback = (_, _) => { }; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction, onFallback); + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("fallbackAction"); @@ -99,12 +99,12 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF [Fact] public void Should_throw_when_onFallback_delegate_is_null() { - var fallbackAction = () => ResultPrimitive.Substitute; + Func fallbackAction = () => ResultPrimitive.Substitute; Action> onFallback = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction, onFallback); + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("onFallback"); @@ -131,8 +131,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() Action, Context> onFallback = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction, onFallback); + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("onFallback"); @@ -145,8 +145,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti Action, Context> onFallback = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction, onFallback); + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction, onFallback); policy.Should().Throw() .And.ParamName.Should().Be("onFallback"); @@ -159,12 +159,12 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti [Fact] public void Should_not_execute_fallback_when_executed_delegate_does_not_raise_fault() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction); fallbackPolicy.Execute(() => ResultPrimitive.Good); @@ -174,12 +174,12 @@ public void Should_not_execute_fallback_when_executed_delegate_does_not_raise_fa [Fact] public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultAgain).Should().Be(ResultPrimitive.FaultAgain); @@ -189,9 +189,9 @@ public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_ [Fact] public void Should_return_fallback_value_when_executed_delegate_raises_fault_handled_by_policy() { - var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(ResultPrimitive.Substitute); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(ResultPrimitive.Fault) + .Fallback(ResultPrimitive.Substitute); fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).Should().Be(ResultPrimitive.Substitute); } @@ -199,12 +199,12 @@ public void Should_return_fallback_value_when_executed_delegate_raises_fault_han [Fact] public void Should_execute_fallback_when_executed_delegate_raises_fault_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(ResultPrimitive.Fault) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).Should().Be(ResultPrimitive.Substitute); @@ -214,13 +214,13 @@ public void Should_execute_fallback_when_executed_delegate_raises_fault_handled_ [Fact] public void Should_execute_fallback_when_executed_delegate_raises_one_of_results_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultAgain).Should().Be(ResultPrimitive.Substitute); @@ -230,13 +230,13 @@ public void Should_execute_fallback_when_executed_delegate_raises_one_of_results [Fact] public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_one_of_faults_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultYetAgain).Should().Be(ResultPrimitive.FaultYetAgain); @@ -246,12 +246,12 @@ public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_ [Fact] public void Should_not_execute_fallback_when_result_raised_does_not_match_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(_ => false) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(_ => false) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).Should().Be(ResultPrimitive.Fault); @@ -261,13 +261,13 @@ public void Should_not_execute_fallback_when_result_raised_does_not_match_handli [Fact] public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_handled_by_any_of_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(r => r == ResultPrimitive.Fault) - .OrResult(r => r == ResultPrimitive.FaultAgain) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(r => r == ResultPrimitive.Fault) + .OrResult(r => r == ResultPrimitive.FaultAgain) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultYetAgain).Should().Be(ResultPrimitive.FaultYetAgain); @@ -277,12 +277,12 @@ public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_ [Fact] public void Should_execute_fallback_when_result_raised_matches_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(_ => true) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(_ => true) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.Undefined).Should().Be(ResultPrimitive.Substitute); @@ -293,13 +293,13 @@ public void Should_execute_fallback_when_result_raised_matches_handling_predicat [Fact] public void Should_execute_fallback_when_result_raised_matches_one_of_handling_predicates() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var fallbackPolicy = Policy - .HandleResult(_ => true) - .OrResult(ResultPrimitive.FaultAgain) - .Fallback(fallbackAction); + FallbackPolicy fallbackPolicy = Policy + .HandleResult(_ => true) + .OrResult(ResultPrimitive.FaultAgain) + .Fallback(fallbackAction); fallbackPolicy.RaiseResultSequence(ResultPrimitive.Undefined).Should().Be(ResultPrimitive.Substitute); @@ -309,14 +309,14 @@ public void Should_execute_fallback_when_result_raised_matches_one_of_handling_p [Fact] public void Should_not_handle_result_raised_by_fallback_delegate_even_if_is_result_handled_by_policy() { - var fallbackActionExecuted = false; - var fallbackAction = () => + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return new ResultClass(ResultPrimitive.Fault, "FromFallbackAction"); }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .Fallback(fallbackAction); @@ -333,17 +333,17 @@ public void Should_not_handle_result_raised_by_fallback_delegate_even_if_is_resu [Fact] public void Should_call_onFallback_passing_result_triggering_fallback() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return new ResultClass(ResultPrimitive.Substitute); }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return new ResultClass(ResultPrimitive.Substitute); }; ResultClass resultPassedToOnFallback = null; Action> onFallback = r => { resultPassedToOnFallback = r.Result; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - var resultFromDelegate = new ResultClass(ResultPrimitive.Fault); + ResultClass resultFromDelegate = new ResultClass(ResultPrimitive.Fault); fallbackPolicy.Execute(() => resultFromDelegate); fallbackActionExecuted.Should().BeTrue(); @@ -354,12 +354,12 @@ public void Should_call_onFallback_passing_result_triggering_fallback() [Fact] public void Should_not_call_onFallback_when_executed_delegate_does_not_raise_fault() { - var fallbackAction = () => ResultPrimitive.Substitute; + Func fallbackAction = () => ResultPrimitive.Substitute; - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Action> onFallback = _ => { onFallbackExecuted = true; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); @@ -381,12 +381,12 @@ public void Should_call_onFallback_with_the_passed_context() Action, Context> onFallback = (_, ctx) => { contextData = ctx; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); fallbackPolicy.Execute(_ => ResultPrimitive.Fault, - new { key1 = "value1", key2 = "value2" }.AsDictionary()) + new { key1 = "value1", key2 = "value2" }.AsDictionary()) .Should().Be(ResultPrimitive.Substitute); contextData.Should() @@ -403,12 +403,12 @@ public void Should_call_onFallback_with_the_passed_context_when_execute_and_capt Action, Context> onFallback = (_, ctx) => { contextData = ctx; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); fallbackPolicy.ExecuteAndCapture(_ => ResultPrimitive.Fault, - new { key1 = "value1", key2 = "value2" }.AsDictionary()) + new { key1 = "value1", key2 = "value2" }.AsDictionary()) .Result.Should().Be(ResultPrimitive.Substitute); contextData.Should() @@ -425,7 +425,7 @@ public void Should_call_onFallback_with_independent_context_for_independent_call Action, Context> onFallback = (dr, ctx) => { contextData[dr.Result] = ctx["key"]; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction, onFallback); @@ -447,12 +447,12 @@ public void Should_call_onFallback_with_independent_context_for_independent_call public void Context_should_be_empty_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var onFallbackExecuted = false; + bool onFallbackExecuted = false; Func fallbackAction = _ => ResultPrimitive.Substitute; Action, Context> onFallback = (_, ctx) => { onFallbackExecuted = true; capturedContext = ctx; }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction, onFallback); @@ -472,7 +472,7 @@ public void Should_call_fallbackAction_with_the_passed_context() Action, Context> onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); @@ -494,7 +494,7 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ Action, Context> onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); @@ -511,13 +511,13 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ public void Context_should_be_empty_at_fallbackAction_if_execute_not_called_with_any_context_data() { Context capturedContext = null; - var fallbackExecuted = false; + bool fallbackExecuted = false; Func fallbackAction = (ctx, _) => { fallbackExecuted = true; capturedContext = ctx; return ResultPrimitive.Substitute; }; Action, Context> onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction, onFallback); @@ -541,7 +541,7 @@ public void Should_call_fallbackAction_with_the_fault() Action, Context> onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); @@ -563,7 +563,7 @@ public void Should_call_fallbackAction_with_the_fault_when_execute_and_capture() Action, Context> onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); @@ -586,7 +586,7 @@ public void Should_not_call_fallbackAction_with_the_fault_if_fault_unhandled() Action, Context> onFallback = (_, _) => { }; - var fallbackPolicy = Policy + FallbackPolicy fallbackPolicy = Policy .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); @@ -603,20 +603,20 @@ public void Should_not_call_fallbackAction_with_the_fault_if_fault_unhandled() [Fact] public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; @@ -631,20 +631,20 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca [Fact] public void Should_execute_fallback_when_faulting_and_cancellationToken_not_cancelled() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; @@ -659,21 +659,21 @@ public void Should_execute_fallback_when_faulting_and_cancellationToken_not_canc [Fact] public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. }; @@ -692,21 +692,21 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex [Fact] public void Should_report_cancellation_and_not_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_does_not_handle_cancellations() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true @@ -723,21 +723,21 @@ public void Should_report_cancellation_and_not_execute_fallback_during_otherwise [Fact] public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_handles_cancellations() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Or() .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true @@ -753,20 +753,20 @@ public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non [Fact] public void Should_not_report_cancellation_and_not_execute_fallback_if_non_faulting_action_execution_completes_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false @@ -782,20 +782,20 @@ public void Should_not_report_cancellation_and_not_execute_fallback_if_non_fault [Fact] public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_execution_raises_unhandled_fault_and_user_delegate_does_not_observe_the_set_cancellationToken() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false @@ -811,21 +811,21 @@ public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_exe [Fact] public void Should_handle_handled_fault_and_execute_fallback_following_faulting_action_execution_when_user_delegate_does_not_observe_cancellationToken() { - var fallbackActionExecuted = false; - var fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; + bool fallbackActionExecuted = false; + Func fallbackAction = () => { fallbackActionExecuted = true; return ResultPrimitive.Substitute; }; - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var policy = Policy + FallbackPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false @@ -841,4 +841,4 @@ public void Should_handle_handled_fault_and_execute_fallback_following_faulting_ #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs b/src/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs index 8995afb4846..e71f35972c9 100644 --- a/src/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs +++ b/src/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs @@ -59,4 +59,4 @@ public void WriteLine(string format, params object[] args) { items.TryAdd(Guid.NewGuid(), new Item(format ?? string.Empty, args == null || args.Length == 0 ? noArgs : args)); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Bulkhead/AssertionFailure.cs b/src/Polly.Specs/Helpers/Bulkhead/AssertionFailure.cs index 080e7f6758c..be90eee9198 100644 --- a/src/Polly.Specs/Helpers/Bulkhead/AssertionFailure.cs +++ b/src/Polly.Specs/Helpers/Bulkhead/AssertionFailure.cs @@ -16,4 +16,4 @@ public AssertionFailure(int expected, int actual, string measure) public int Expected { get; } public int Actual { get; } public string Measure { get; } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Bulkhead/SilentOutputHelper.cs b/src/Polly.Specs/Helpers/Bulkhead/SilentOutputHelper.cs index 2634981f010..5417f0d1f72 100644 --- a/src/Polly.Specs/Helpers/Bulkhead/SilentOutputHelper.cs +++ b/src/Polly.Specs/Helpers/Bulkhead/SilentOutputHelper.cs @@ -13,4 +13,4 @@ public void WriteLine(string format, params object[] args) { // Do nothing: intentionally silent. } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs b/src/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs index 6207303c25f..42a6eebf9cb 100644 --- a/src/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs +++ b/src/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs @@ -23,7 +23,7 @@ public class TraceableAction : IDisposable public TraceableActionStatus Status { - get => _status; + get { return _status; } set { _status = value; @@ -49,14 +49,14 @@ public Task ExecuteOnBulkhead(BulkheadPolicy bulkhead) { return ExecuteThroughSyncBulkheadOuter( () => bulkhead.Execute(_ => ExecuteThroughSyncBulkheadInner(), CancellationSource.Token) - ); + ); } public Task ExecuteOnBulkhead(BulkheadPolicy bulkhead) { return ExecuteThroughSyncBulkheadOuter( () => bulkhead.Execute(_ => { ExecuteThroughSyncBulkheadInner(); return default; }, CancellationSource.Token) - ); + ); } // Note re TaskCreationOptions.LongRunning: Testing the parallelization of the bulkhead policy efficiently requires the ability to start large numbers of parallel tasks in a short space of time. The ThreadPool's algorithm of only injecting extra threads (when necessary) at a rate of two-per-second however makes high-volume tests using the ThreadPool both slow and flaky. For PCL tests further, ThreadPool.SetMinThreads(...) is not available, to mitigate this. Using TaskCreationOptions.LongRunning allows us to force tasks to be started near-instantly on non-ThreadPool threads. @@ -69,51 +69,51 @@ private Task ExecuteThroughSyncBulkheadOuter(Action executeThroughBulkheadInner) Status = TraceableActionStatus.StartRequested; return Task.Factory.StartNew(() => + { + try { - try - { - Status = TraceableActionStatus.QueueingForSemaphore; + Status = TraceableActionStatus.QueueingForSemaphore; - executeThroughBulkheadInner(); - } - catch (BulkheadRejectedException) + executeThroughBulkheadInner(); + } + catch (BulkheadRejectedException) + { + Status = TraceableActionStatus.Rejected; + } + catch (OperationCanceledException) + { + if (Status != TraceableActionStatus.Canceled) { - Status = TraceableActionStatus.Rejected; - } - catch (OperationCanceledException) + _testOutputHelper.WriteLine(_id + "Caught queue cancellation."); + Status = TraceableActionStatus.Canceled; + } // else: was execution cancellation rethrown: ignore + } + catch (AggregateException ae) + { + if (ae.InnerExceptions.Count == 1 && ae.InnerException is OperationCanceledException) { if (Status != TraceableActionStatus.Canceled) { _testOutputHelper.WriteLine(_id + "Caught queue cancellation."); Status = TraceableActionStatus.Canceled; - } // else: was execution cancellation rethrown: ignore - } - catch (AggregateException ae) - { - if (ae.InnerExceptions.Count == 1 && ae.InnerException is OperationCanceledException) - { - if (Status != TraceableActionStatus.Canceled) - { - _testOutputHelper.WriteLine(_id + "Caught queue cancellation."); - Status = TraceableActionStatus.Canceled; - } // else: was execution cancellation rethrown: ignore - } - else throw; + } // else: was execution cancellation rethrown: ignore } - catch (Exception e) - { - _testOutputHelper.WriteLine(_id + "Caught unexpected exception during execution: " + e); + else throw; + } + catch (Exception e) + { + _testOutputHelper.WriteLine(_id + "Caught unexpected exception during execution: " + e); - Status = TraceableActionStatus.Faulted; - } - finally - { - // Exiting the execution successfully is also a change of state (on which assertions may be occurring) in that it releases a semaphore slot sucessfully. - // There can also be races between assertions and executions-responding-to-previous-state-changes, so a second signal presents another opportunity for assertions to be run. - SignalStateChange(); - } - }, - TaskCreationOptions.LongRunning); + Status = TraceableActionStatus.Faulted; + } + finally + { + // Exiting the execution successfully is also a change of state (on which assertions may be occurring) in that it releases a semaphore slot sucessfully. + // There can also be races between assertions and executions-responding-to-previous-state-changes, so a second signal presents another opportunity for assertions to be run. + SignalStateChange(); + } + }, + TaskCreationOptions.LongRunning); } private void ExecuteThroughSyncBulkheadInner() @@ -234,4 +234,4 @@ public void Dispose() { CancellationSource.Dispose(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Bulkhead/TraceableActionStatus.cs b/src/Polly.Specs/Helpers/Bulkhead/TraceableActionStatus.cs index 636af89073a..71cf17b4a89 100644 --- a/src/Polly.Specs/Helpers/Bulkhead/TraceableActionStatus.cs +++ b/src/Polly.Specs/Helpers/Bulkhead/TraceableActionStatus.cs @@ -13,4 +13,4 @@ public enum TraceableActionStatus Canceled, Faulted, Completed, -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs b/src/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs index 03e90163df8..4203a3c46c6 100644 --- a/src/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs +++ b/src/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs @@ -10,9 +10,13 @@ internal class StubCacheKeyStrategy : ICacheKeyStrategy { private readonly Func strategy; - public StubCacheKeyStrategy(Func strategy) => + public StubCacheKeyStrategy(Func strategy) + { this.strategy = strategy; + } - public string GetCacheKey(Context context) => - strategy(context); -} \ No newline at end of file + public string GetCacheKey(Context context) + { + return strategy(context); + } +} diff --git a/src/Polly.Specs/Helpers/Caching/StubCacheProvider.cs b/src/Polly.Specs/Helpers/Caching/StubCacheProvider.cs index 38c7bf5732f..406cd95f8e8 100644 --- a/src/Polly.Specs/Helpers/Caching/StubCacheProvider.cs +++ b/src/Polly.Specs/Helpers/Caching/StubCacheProvider.cs @@ -42,14 +42,18 @@ public CacheItem(object value, Ttl ttl) return (false, null); } - public void Put(string key, object value, Ttl ttl) => - cachedValues[key] = new(value, ttl); + public void Put(string key, object value, Ttl ttl) + { + cachedValues[key] = new CacheItem(value, ttl); + } #region Naive async-over-sync implementation // Intentionally naive async-over-sync implementation. Its purpose is to be the simplest thing to support tests of the CachePolicyAsync and CacheEngineAsync, not to be a usable implementation of IAsyncCacheProvider. - public Task<(bool, object)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) => - Task.FromResult(TryGet(key)); + public Task<(bool, object)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) + { + return Task.FromResult(TryGet(key)); + } public Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext) { @@ -59,4 +63,4 @@ public Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancel #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs b/src/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs index 1a9da563a54..a2f563e185f 100644 --- a/src/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs +++ b/src/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs @@ -34,8 +34,10 @@ public void Put(string key, object value, Ttl ttl) #region Naive async-over-sync implementation // Intentionally naive async-over-sync implementation. Its purpose is to be the simplest thing to support tests of the CachePolicyAsync and CacheEngineAsync, not to be a usable implementation of IAsyncCacheProvider. - public Task<(bool, object)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) => - Task.FromResult(TryGet(key)); + public Task<(bool, object)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) + { + return Task.FromResult(TryGet(key)); + } public Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext) { @@ -45,4 +47,4 @@ public Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancel #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Caching/StubSerialized.cs b/src/Polly.Specs/Helpers/Caching/StubSerialized.cs index 84a08d034c8..dac764a54c4 100644 --- a/src/Polly.Specs/Helpers/Caching/StubSerialized.cs +++ b/src/Polly.Specs/Helpers/Caching/StubSerialized.cs @@ -20,4 +20,4 @@ public StubSerialized(TOriginal original) internal class StubSerialized : StubSerialized { public StubSerialized(object obj) : base(obj) { } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Caching/StubSerializer.cs b/src/Polly.Specs/Helpers/Caching/StubSerializer.cs index 55d4fc18d3c..ad81ebab152 100644 --- a/src/Polly.Specs/Helpers/Caching/StubSerializer.cs +++ b/src/Polly.Specs/Helpers/Caching/StubSerializer.cs @@ -21,4 +21,4 @@ public StubSerializer(Func serialize, Func _serialize(objectToSerialize); public TResult Deserialize(TSerialized objectToDeserialize) => _deserialize(objectToDeserialize); -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Constants.cs b/src/Polly.Specs/Helpers/Constants.cs index cdc64c2ea26..27779b1fcba 100644 --- a/src/Polly.Specs/Helpers/Constants.cs +++ b/src/Polly.Specs/Helpers/Constants.cs @@ -14,4 +14,4 @@ public class Constants /// Denotes a test collection making heavy use of parallel threads. These tests are not run in parallel with each other, to reduce heavy use of threads in the build/CI environment. /// public const string ParallelThreadDependentTestCollection = "ParallelThreadDependentTestCollection"; -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/ContextualPolicyExtensions.cs b/src/Polly.Specs/Helpers/ContextualPolicyExtensions.cs index 0f1e48613c0..8288594e11d 100644 --- a/src/Polly.Specs/Helpers/ContextualPolicyExtensions.cs +++ b/src/Polly.Specs/Helpers/ContextualPolicyExtensions.cs @@ -10,7 +10,7 @@ public static void RaiseException(this Policy policy, IDictionary contextData, Action configureException = null) where TException : Exception, new() { - var counter = 0; + int counter = 0; policy.Execute(_ => { @@ -35,4 +35,4 @@ public static void RaiseException( policy.RaiseException(1, contextData, configureException); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/ContextualPolicyExtensionsAsync.cs b/src/Polly.Specs/Helpers/ContextualPolicyExtensionsAsync.cs index 506f0281a4d..91fa7302034 100644 --- a/src/Polly.Specs/Helpers/ContextualPolicyExtensionsAsync.cs +++ b/src/Polly.Specs/Helpers/ContextualPolicyExtensionsAsync.cs @@ -11,7 +11,7 @@ public static class ContextualPolicyExtensionsAsync public static Task RaiseExceptionAsync(this AsyncPolicy policy, int numberOfTimesToRaiseException, IDictionary contextData, Action configureException = null, CancellationToken cancellationToken = default) where TException : Exception, new() { - var counter = 0; + int counter = 0; return policy.ExecuteAsync((_, _) => { @@ -29,6 +29,9 @@ public static class ContextualPolicyExtensionsAsync }, contextData, cancellationToken); } - public static Task RaiseExceptionAsync(this AsyncPolicy policy, IDictionary contextData, Action configureException = null, CancellationToken cancellationToken = default) where TException : Exception, new() => - policy.RaiseExceptionAsync(1, contextData, configureException, cancellationToken); -} \ No newline at end of file + public static Task RaiseExceptionAsync(this AsyncPolicy policy, IDictionary contextData, Action configureException = null, CancellationToken cancellationToken = default) where TException : Exception, new() + { + return policy.RaiseExceptionAsync(1, contextData, configureException, cancellationToken); + } + +} diff --git a/src/Polly.Specs/Helpers/ContextualPolicyTResultExtensions.cs b/src/Polly.Specs/Helpers/ContextualPolicyTResultExtensions.cs index 9b45ef35177..73c8eaa2dec 100644 --- a/src/Polly.Specs/Helpers/ContextualPolicyTResultExtensions.cs +++ b/src/Polly.Specs/Helpers/ContextualPolicyTResultExtensions.cs @@ -8,8 +8,10 @@ public static class ContextualPolicyTResultExtensions { public static TResult RaiseResultSequence(this Policy policy, IDictionary contextData, - params TResult[] resultsToRaise) => - policy.RaiseResultSequence(contextData, resultsToRaise.ToList()); + params TResult[] resultsToRaise) + { + return policy.RaiseResultSequence(contextData, resultsToRaise.ToList()); + } public static TResult RaiseResultSequence(this Policy policy, IDictionary contextData, @@ -29,9 +31,11 @@ public static TResult RaiseResultSequence(this Policy policy, } public static PolicyResult RaiseResultSequenceOnExecuteAndCapture(this Policy policy, - IDictionary contextData, - params TResult[] resultsToRaise) => - policy.RaiseResultSequenceOnExecuteAndCapture(contextData, resultsToRaise.ToList()); + IDictionary contextData, + params TResult[] resultsToRaise) + { + return policy.RaiseResultSequenceOnExecuteAndCapture(contextData, resultsToRaise.ToList()); + } public static PolicyResult RaiseResultSequenceOnExecuteAndCapture(this Policy policy, IDictionary contextData, @@ -50,4 +54,4 @@ public static PolicyResult RaiseResultSequenceOnExecuteAndCapture RaiseResultSequenceAsync(this AsyncPolicy policy, - IDictionary contextData, - params TResult[] resultsToRaise) => - policy.RaiseResultSequenceAsync(contextData, CancellationToken.None, resultsToRaise.ToList()); +IDictionary contextData, +params TResult[] resultsToRaise) + { + return policy.RaiseResultSequenceAsync(contextData, CancellationToken.None, resultsToRaise.ToList()); + } public static Task RaiseResultSequenceAsync(this AsyncPolicy policy, IDictionary contextData, CancellationToken cancellationToken, IEnumerable resultsToRaise) { @@ -29,8 +31,10 @@ public static Task RaiseResultSequenceAsync(this AsyncPolicy> RaiseResultSequenceOnExecuteAndCaptureAsync(this AsyncPolicy policy, IDictionary contextData, params TResult[] resultsToRaise) => - policy.RaiseResultSequenceOnExecuteAndCaptureAsync(contextData, resultsToRaise.ToList()); + public static Task> RaiseResultSequenceOnExecuteAndCaptureAsync(this AsyncPolicy policy, IDictionary contextData, params TResult[] resultsToRaise) + { + return policy.RaiseResultSequenceOnExecuteAndCaptureAsync(contextData, resultsToRaise.ToList()); + } public static Task> RaiseResultSequenceOnExecuteAndCaptureAsync(this AsyncPolicy policy, IDictionary contextData, IEnumerable resultsToRaise) { @@ -46,4 +50,4 @@ public static Task> RaiseResultSequenceOnExecuteAndCapture return Task.FromResult(enumerator.Current); }, contextData); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandleEngine.cs b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandleEngine.cs index df527aa2132..14888c80354 100644 --- a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandleEngine.cs +++ b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandleEngine.cs @@ -16,7 +16,7 @@ internal static TResult Implementation( { try { - var result = action(context, cancellationToken); + TResult result = action(context, cancellationToken); if (shouldHandleResultPredicates.AnyMatch(result)) { @@ -27,7 +27,7 @@ internal static TResult Implementation( } catch (Exception ex) { - var handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; @@ -39,4 +39,4 @@ internal static TResult Implementation( throw; } } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandlePolicy.cs b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandlePolicy.cs index 609fb1bc0ae..f996124ccc1 100644 --- a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandlePolicy.cs +++ b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandlePolicy.cs @@ -41,8 +41,9 @@ internal AddBehaviourIfHandlePolicy( _behaviourIfHandle = behaviourIfHandle ?? throw new ArgumentNullException(nameof(behaviourIfHandle)); } - protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => - AddBehaviourIfHandleEngine.Implementation( + protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) + { + return AddBehaviourIfHandleEngine.Implementation( ExceptionPredicates, ResultPredicates, _behaviourIfHandle, @@ -50,4 +51,5 @@ protected override TResult Implementation(Func WithBehaviour(this return new AddBehaviourIfHandlePolicy(behaviourIfHandle, policyBuilder); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandleEngine.cs b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandleEngine.cs index 736b9ab5e54..ac3ce6365a7 100644 --- a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandleEngine.cs +++ b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandleEngine.cs @@ -18,7 +18,7 @@ internal static async Task ImplementationAsync( { try { - var result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); + TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); if (shouldHandleResultPredicates.AnyMatch(result)) { @@ -29,7 +29,7 @@ internal static async Task ImplementationAsync( } catch (Exception ex) { - var handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; @@ -41,4 +41,4 @@ internal static async Task ImplementationAsync( throw; } } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandlePolicy.cs b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandlePolicy.cs index 686e295509a..9493cb0c8de 100644 --- a/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandlePolicy.cs +++ b/src/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AsyncAddBehaviourIfHandlePolicy.cs @@ -37,12 +37,16 @@ internal class AsyncAddBehaviourIfHandlePolicy : AsyncPolicy internal AsyncAddBehaviourIfHandlePolicy( Func, Task> behaviourIfHandle, PolicyBuilder policyBuilder) - : base(policyBuilder) => + : base(policyBuilder) + { _behaviourIfHandle = behaviourIfHandle ?? throw new ArgumentNullException(nameof(behaviourIfHandle)); + } + protected override Task ImplementationAsync(Func> action, Context context, System.Threading.CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncAddBehaviourIfHandleEngine.ImplementationAsync( + bool continueOnCapturedContext) + { + return AsyncAddBehaviourIfHandleEngine.ImplementationAsync( ExceptionPredicates, ResultPredicates, _behaviourIfHandle, @@ -51,4 +55,5 @@ protected override Task ImplementationAsync(Func WithBehaviourAsync(behaviourIfHandle, policyBuilder); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecuteEngine.cs b/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecuteEngine.cs index 7842194937e..9a585f9f9c9 100644 --- a/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecuteEngine.cs +++ b/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecuteEngine.cs @@ -29,4 +29,4 @@ internal static async Task ImplementationAsync( return await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecutePolicy.cs b/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecutePolicy.cs index 1099b1a9366..81b599c1a0a 100644 --- a/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecutePolicy.cs +++ b/src/Polly.Specs/Helpers/Custom/PreExecute/AsyncPreExecutePolicy.cs @@ -8,28 +8,40 @@ internal class AsyncPreExecutePolicy : AsyncPolicy { private Func _preExecute; - public static AsyncPreExecutePolicy CreateAsync(Func preExecute) => - new(preExecute); + public static AsyncPreExecutePolicy CreateAsync(Func preExecute) + { + return new AsyncPreExecutePolicy(preExecute); + } - internal AsyncPreExecutePolicy(Func preExecute) => + internal AsyncPreExecutePolicy(Func preExecute) + { _preExecute = preExecute ?? throw new ArgumentNullException(nameof(preExecute)); + } protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncPreExecuteEngine.ImplementationAsync(_preExecute, action, context, cancellationToken, continueOnCapturedContext); + bool continueOnCapturedContext) + { + return AsyncPreExecuteEngine.ImplementationAsync(_preExecute, action, context, cancellationToken, continueOnCapturedContext); + } } internal class AsyncPreExecutePolicy : AsyncPolicy { private Func _preExecute; - public static AsyncPreExecutePolicy CreateAsync(Func preExecute) => - new AsyncPreExecutePolicy(preExecute); + public static AsyncPreExecutePolicy CreateAsync(Func preExecute) + { + return new AsyncPreExecutePolicy(preExecute); + } - internal AsyncPreExecutePolicy(Func preExecute) => + internal AsyncPreExecutePolicy(Func preExecute) + { _preExecute = preExecute ?? throw new ArgumentNullException(nameof(preExecute)); + } protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncPreExecuteEngine.ImplementationAsync(_preExecute, action, context, cancellationToken, continueOnCapturedContext); -} \ No newline at end of file + bool continueOnCapturedContext) + { + return AsyncPreExecuteEngine.ImplementationAsync(_preExecute, action, context, cancellationToken, continueOnCapturedContext); + } +} diff --git a/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecuteEngine.cs b/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecuteEngine.cs index 49120e08efb..30313751e62 100644 --- a/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecuteEngine.cs +++ b/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecuteEngine.cs @@ -26,4 +26,4 @@ internal static TResult Implementation( return action(context, cancellationToken); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecutePolicy.cs b/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecutePolicy.cs index abccf2aaa48..e27504eb96e 100644 --- a/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecutePolicy.cs +++ b/src/Polly.Specs/Helpers/Custom/PreExecute/PreExecutePolicy.cs @@ -7,26 +7,38 @@ internal class PreExecutePolicy : Policy { private Action _preExecute; - public static PreExecutePolicy Create(Action preExecute) => - new(preExecute); + public static PreExecutePolicy Create(Action preExecute) + { + return new PreExecutePolicy(preExecute); + } - internal PreExecutePolicy(Action preExecute) => + internal PreExecutePolicy(Action preExecute) + { _preExecute = preExecute ?? throw new ArgumentNullException(nameof(preExecute)); + } - protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => - PreExecuteEngine.Implementation(_preExecute, action, context, cancellationToken); + protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) + { + return PreExecuteEngine.Implementation(_preExecute, action, context, cancellationToken); + } } internal class PreExecutePolicy : Policy { private Action _preExecute; - public static PreExecutePolicy Create(Action preExecute) => - new PreExecutePolicy(preExecute); + public static PreExecutePolicy Create(Action preExecute) + { + return new PreExecutePolicy(preExecute); + } - internal PreExecutePolicy(Action preExecute) => + internal PreExecutePolicy(Action preExecute) + { _preExecute = preExecute ?? throw new ArgumentNullException(nameof(preExecute)); + } - protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => - PreExecuteEngine.Implementation(_preExecute, action, context, cancellationToken); -} \ No newline at end of file + protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) + { + return PreExecuteEngine.Implementation(_preExecute, action, context, cancellationToken); + } +} diff --git a/src/Polly.Specs/Helpers/ObjectExtensions.cs b/src/Polly.Specs/Helpers/ObjectExtensions.cs index 7172601fa18..c01ad7b6eab 100644 --- a/src/Polly.Specs/Helpers/ObjectExtensions.cs +++ b/src/Polly.Specs/Helpers/ObjectExtensions.cs @@ -14,4 +14,4 @@ public static IDictionary AsDictionary(this object source) propInfo => propInfo.GetValue(source, null) ); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/PolicyExtensions.cs b/src/Polly.Specs/Helpers/PolicyExtensions.cs index 3c117a712fe..05a44ea2bef 100644 --- a/src/Polly.Specs/Helpers/PolicyExtensions.cs +++ b/src/Polly.Specs/Helpers/PolicyExtensions.cs @@ -14,7 +14,7 @@ public class ExceptionAndOrCancellationScenario public static void RaiseException(this Policy policy, TException instance) where TException : Exception { - var scenario = new ExceptionAndOrCancellationScenario + ExceptionAndOrCancellationScenario scenario = new ExceptionAndOrCancellationScenario { ActionObservesCancellation = false, AttemptDuringWhichToCancel = null, @@ -31,7 +31,7 @@ public static void RaiseException(this Policy policy, TException ins public static void RaiseException(this Policy policy, int numberOfTimesToRaiseException, Action configureException = null) where TException : Exception, new() { - var scenario = new ExceptionAndOrCancellationScenario + ExceptionAndOrCancellationScenario scenario = new ExceptionAndOrCancellationScenario { ActionObservesCancellation = false, AttemptDuringWhichToCancel = null, @@ -61,9 +61,9 @@ public static void RaiseException(this Policy policy, TException ins public static void RaiseExceptionAndOrCancellation(this Policy policy, ExceptionAndOrCancellationScenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, Func exceptionFactory) where TException : Exception { - var counter = 0; + int counter = 0; - var cancellationToken = cancellationTokenSource.Token; + CancellationToken cancellationToken = cancellationTokenSource.Token; policy.Execute(ct => { @@ -91,9 +91,9 @@ public static void RaiseExceptionAndOrCancellation(this Policy polic public static TResult RaiseExceptionAndOrCancellation(this Policy policy, ExceptionAndOrCancellationScenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, Func exceptionFactory, TResult successResult) where TException : Exception { - var counter = 0; + int counter = 0; - var cancellationToken = cancellationTokenSource.Token; + CancellationToken cancellationToken = cancellationTokenSource.Token; return policy.Execute(ct => { @@ -119,4 +119,4 @@ public static TResult RaiseExceptionAndOrCancellation(this return successResult; }, cancellationToken); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Helpers/PolicyExtensionsAsync.cs b/src/Polly.Specs/Helpers/PolicyExtensionsAsync.cs index e851a963724..6b65faca507 100644 --- a/src/Polly.Specs/Helpers/PolicyExtensionsAsync.cs +++ b/src/Polly.Specs/Helpers/PolicyExtensionsAsync.cs @@ -18,7 +18,7 @@ public class ExceptionAndOrCancellationScenario public static Task RaiseExceptionAsync(this AsyncPolicy policy, TException instance) where TException : Exception { - var scenario = new ExceptionAndOrCancellationScenario + ExceptionAndOrCancellationScenario scenario = new ExceptionAndOrCancellationScenario { ActionObservesCancellation = false, AttemptDuringWhichToCancel = null, @@ -28,12 +28,14 @@ public static Task RaiseExceptionAsync(this AsyncPolicy policy, TExc return policy.RaiseExceptionAndOrCancellationAsync(scenario, new CancellationTokenSource(), () => { }, _ => instance); } - public static Task RaiseExceptionAsync(this AsyncPolicy policy, Action configureException = null) where TException : Exception, new() => - policy.RaiseExceptionAsync(1, configureException); + public static Task RaiseExceptionAsync(this AsyncPolicy policy, Action configureException = null) where TException : Exception, new() + { + return policy.RaiseExceptionAsync(1, configureException); + } public static Task RaiseExceptionAsync(this AsyncPolicy policy, int numberOfTimesToRaiseException, Action configureException = null, CancellationToken cancellationToken = default) where TException : Exception, new() { - var scenario = new ExceptionAndOrCancellationScenario + ExceptionAndOrCancellationScenario scenario = new ExceptionAndOrCancellationScenario { ActionObservesCancellation = false, AttemptDuringWhichToCancel = null, @@ -63,9 +65,9 @@ public static Task RaiseExceptionAsync(this AsyncPolicy policy, TExc public static Task RaiseExceptionAndOrCancellationAsync(this AsyncPolicy policy, ExceptionAndOrCancellationScenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, Func exceptionFactory) where TException : Exception { - var counter = 0; + int counter = 0; - var cancellationToken = cancellationTokenSource.Token; + CancellationToken cancellationToken = cancellationTokenSource.Token; return policy.ExecuteAsync(ct => { @@ -94,9 +96,9 @@ public static Task RaiseExceptionAndOrCancellationAsync(this AsyncPo public static Task RaiseExceptionAndOrCancellationAsync(this AsyncPolicy policy, ExceptionAndOrCancellationScenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, Func exceptionFactory, TResult successResult) where TException : Exception { - var counter = 0; + int counter = 0; - var cancellationToken = cancellationTokenSource.Token; + CancellationToken cancellationToken = cancellationTokenSource.Token; return policy.ExecuteAsync(ct => { @@ -122,4 +124,4 @@ public static Task RaiseExceptionAndOrCancellationAsync(this Policy policy, params TResult[] resultsToRaise) => - policy.RaiseResultSequence(resultsToRaise.ToList()); + public static TResult RaiseResultSequence(this Policy policy, params TResult[] resultsToRaise) + { + return policy.RaiseResultSequence(resultsToRaise.ToList()); + } public static TResult RaiseResultSequence(this Policy policy, IEnumerable resultsToRaise) { @@ -27,8 +29,10 @@ public static TResult RaiseResultSequence(this Policy policy, } } - public static TResult RaiseResultAndOrExceptionSequence(this Policy policy, params object[] resultsOrExceptionsToRaise) => - policy.RaiseResultAndOrExceptionSequence(resultsOrExceptionsToRaise.ToList()); + public static TResult RaiseResultAndOrExceptionSequence(this Policy policy, params object[] resultsOrExceptionsToRaise) + { + return policy.RaiseResultAndOrExceptionSequence(resultsOrExceptionsToRaise.ToList()); + } public static TResult RaiseResultAndOrExceptionSequence(this Policy policy, IEnumerable resultsOrExceptionsToRaise) @@ -43,7 +47,7 @@ public static TResult RaiseResultAndOrExceptionSequence(this Policy(this Policy policy, Scenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, - params TResult[] resultsToRaise) => - policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, + params TResult[] resultsToRaise) + { + return policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, resultsToRaise.ToList()); + } public static TResult RaiseResultSequenceAndOrCancellation(this Policy policy, Scenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, IEnumerable resultsToRaise) { - var counter = 0; + int counter = 0; - var cancellationToken = cancellationTokenSource.Token; + CancellationToken cancellationToken = cancellationTokenSource.Token; using (var enumerator = resultsToRaise.GetEnumerator()) { @@ -106,4 +112,5 @@ public static TResult RaiseResultSequenceAndOrCancellation(this Policy< }, cancellationToken); } } -} \ No newline at end of file +} + diff --git a/src/Polly.Specs/Helpers/PolicyTResultExtensionsAsync.cs b/src/Polly.Specs/Helpers/PolicyTResultExtensionsAsync.cs index fe96ee5132a..614c502db99 100644 --- a/src/Polly.Specs/Helpers/PolicyTResultExtensionsAsync.cs +++ b/src/Polly.Specs/Helpers/PolicyTResultExtensionsAsync.cs @@ -10,11 +10,15 @@ namespace Polly.Specs.Helpers; public static class PolicyTResultExtensionsAsync { - public static Task RaiseResultSequenceAsync(this AsyncPolicy policy, params TResult[] resultsToRaise) => - policy.RaiseResultSequenceAsync(resultsToRaise.ToList()); + public static Task RaiseResultSequenceAsync(this AsyncPolicy policy, params TResult[] resultsToRaise) + { + return policy.RaiseResultSequenceAsync(resultsToRaise.ToList()); + } - public static Task RaiseResultSequenceAsync(this AsyncPolicy policy, IEnumerable resultsToRaise) => - policy.RaiseResultSequenceAsync(default, resultsToRaise); + public static Task RaiseResultSequenceAsync(this AsyncPolicy policy, IEnumerable resultsToRaise) + { + return policy.RaiseResultSequenceAsync(default, resultsToRaise); + } public static async Task RaiseResultSequenceAsync(this AsyncPolicy policy, CancellationToken cancellationToken, IEnumerable resultsToRaise) @@ -33,12 +37,16 @@ public static async Task RaiseResultSequenceAsync(this AsyncPo } } - public static Task RaiseResultAndOrExceptionSequenceAsync(this AsyncPolicy policy, params object[] resultsOrExceptionsToRaise) => - policy.RaiseResultAndOrExceptionSequenceAsync(resultsOrExceptionsToRaise.ToList()); + public static Task RaiseResultAndOrExceptionSequenceAsync(this AsyncPolicy policy, params object[] resultsOrExceptionsToRaise) + { + return policy.RaiseResultAndOrExceptionSequenceAsync(resultsOrExceptionsToRaise.ToList()); + } public static Task RaiseResultAndOrExceptionSequenceAsync(this AsyncPolicy policy, - IEnumerable resultsOrExceptionsToRaise) => - policy.RaiseResultAndOrExceptionSequenceAsync(CancellationToken.None, resultsOrExceptionsToRaise); + IEnumerable resultsOrExceptionsToRaise) + { + return policy.RaiseResultAndOrExceptionSequenceAsync(CancellationToken.None, resultsOrExceptionsToRaise); + } public static async Task RaiseResultAndOrExceptionSequenceAsync(this AsyncPolicy policy, CancellationToken cancellationToken, IEnumerable resultsOrExceptionsToRaise) @@ -52,7 +60,7 @@ public static async Task RaiseResultAndOrExceptionSequenceAsync RaiseResultSequenceAndOrCancellationAsync(this AsyncPolicy policy, Scenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, - params TResult[] resultsToRaise) => - policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + params TResult[] resultsToRaise) + { + return policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, resultsToRaise.ToList()); + } public static async Task RaiseResultSequenceAndOrCancellationAsync( this AsyncPolicy policy, Scenario scenario, CancellationTokenSource cancellationTokenSource, Action onExecute, IEnumerable resultsToRaise) { - var counter = 0; + int counter = 0; - var cancellationToken = cancellationTokenSource.Token; + CancellationToken cancellationToken = cancellationTokenSource.Token; using (var enumerator = resultsToRaise.GetEnumerator()) { @@ -118,4 +128,4 @@ public static async Task RaiseResultSequenceAndOrCancellationAsync().CircuitBreakerAsync(1, TimeSpan.Zero); IAsyncPolicy nonGenericPolicy = breaker; var genericPolicy = nonGenericPolicy.AsAsyncPolicy(); - var deleg = () => Task.FromResult(ResultPrimitive.Good); + Func> deleg = () => Task.FromResult(ResultPrimitive.Good); (await genericPolicy.ExecuteAsync(deleg)).Should().Be(ResultPrimitive.Good); breaker.Isolate(); - genericPolicy.Awaiting(p => p.ExecuteAsync(deleg)).Should().Throw(); + await genericPolicy.Awaiting(p => p.ExecuteAsync(deleg)).Should().ThrowAsync(); } -} \ No newline at end of file +} + diff --git a/src/Polly.Specs/ISyncPolicyExtensionsSpecs.cs b/src/Polly.Specs/ISyncPolicyExtensionsSpecs.cs index 5b946f62659..5103728b4d4 100644 --- a/src/Polly.Specs/ISyncPolicyExtensionsSpecs.cs +++ b/src/Polly.Specs/ISyncPolicyExtensionsSpecs.cs @@ -22,13 +22,14 @@ public void Converting_a_nongeneric_ISyncPolicy_to_generic_should_return_an_ISyn { // Use a CircuitBreaker as a policy which we can easily manipulate to demonstrate that the executions are passing through the underlying non-generic policy. - var breaker = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy breaker = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); ISyncPolicy nonGenericPolicy = breaker; var genericPolicy = nonGenericPolicy.AsPolicy(); - var deleg = () => ResultPrimitive.Good; + Func deleg = () => ResultPrimitive.Good; genericPolicy.Execute(deleg).Should().Be(ResultPrimitive.Good); breaker.Isolate(); genericPolicy.Invoking(p => p.Execute(deleg)).Should().Throw(); } -} \ No newline at end of file +} + diff --git a/src/Polly.Specs/NoOp/NoOpAsyncSpecs.cs b/src/Polly.Specs/NoOp/NoOpAsyncSpecs.cs index 247b3a9626f..71b1dfef5c0 100644 --- a/src/Polly.Specs/NoOp/NoOpAsyncSpecs.cs +++ b/src/Polly.Specs/NoOp/NoOpAsyncSpecs.cs @@ -1,4 +1,5 @@ using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using Polly.Utilities; using Xunit; @@ -8,33 +9,33 @@ namespace Polly.Specs.NoOp; public class NoOpAsyncSpecs { [Fact] - public void Should_execute_user_delegate() + public async Task Should_execute_user_delegate() { var policy = Policy.NoOpAsync(); - var executed = false; + bool executed = false; - policy.Awaiting(p => p.ExecuteAsync(() => { executed = true; return TaskHelper.EmptyTask; })) - .Should().NotThrow(); + await policy.Awaiting(p => p.ExecuteAsync(() => { executed = true; return TaskHelper.EmptyTask; })) + .Should().NotThrowAsync(); executed.Should().BeTrue(); } [Fact] - public void Should_execute_user_delegate_without_adding_extra_cancellation_behaviour() + public async Task Should_execute_user_delegate_without_adding_extra_cancellation_behaviour() { var policy = Policy.NoOpAsync(); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); - policy.Awaiting(p => p.ExecuteAsync( - _ => { executed = true; return TaskHelper.EmptyTask; }, cts.Token)) - .Should().NotThrow(); + await policy.Awaiting(p => p.ExecuteAsync( + _ => { executed = true; return TaskHelper.EmptyTask; }, cts.Token)) + .Should().NotThrowAsync(); } executed.Should().BeTrue(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/NoOp/NoOpSpecs.cs b/src/Polly.Specs/NoOp/NoOpSpecs.cs index 28fae7d4ab1..7c16ee57b93 100644 --- a/src/Polly.Specs/NoOp/NoOpSpecs.cs +++ b/src/Polly.Specs/NoOp/NoOpSpecs.cs @@ -10,8 +10,8 @@ public class NoOpSpecs [Fact] public void Should_execute_user_delegate() { - var policy = Policy.NoOp(); - var executed = false; + NoOpPolicy policy = Policy.NoOp(); + bool executed = false; policy.Invoking(x => x.Execute(() => { executed = true; })) .Should().NotThrow(); @@ -22,10 +22,10 @@ public void Should_execute_user_delegate() [Fact] public void Should_execute_user_delegate_without_adding_extra_cancellation_behaviour() { - var policy = Policy.NoOp(); - var executed = false; + NoOpPolicy policy = Policy.NoOp(); + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); @@ -35,4 +35,4 @@ public void Should_execute_user_delegate_without_adding_extra_cancellation_behav executed.Should().BeTrue(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs b/src/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs index f6f28fd882e..0cfb27d1896 100644 --- a/src/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs +++ b/src/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs @@ -10,35 +10,35 @@ namespace Polly.Specs.NoOp; public class NoOpTResultAsyncSpecs { [Fact] - public void Should_execute_user_delegate() + public async Task Should_execute_user_delegate() { var policy = Policy.NoOpAsync(); int? result = null; Func, Task> action = async p => result = await p.ExecuteAsync(() => Task.FromResult((int?)10)); - policy.Awaiting(action) - .Should().NotThrow(); + await policy.Awaiting(action) + .Should().NotThrowAsync(); result.HasValue.Should().BeTrue(); result.Should().Be(10); } [Fact] - public void Should_execute_user_delegate_without_adding_extra_cancellation_behaviour() + public async Task Should_execute_user_delegate_without_adding_extra_cancellation_behaviour() { var policy = Policy.NoOpAsync(); int? result = null; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); Func, Task> action = async p => result = await p.ExecuteAsync(_ => Task.FromResult((int?)10), cts.Token); - policy.Awaiting(action) - .Should().NotThrow(); + await policy.Awaiting(action) + .Should().NotThrowAsync(); } result.HasValue.Should().BeTrue(); result.Should().Be(10); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/NoOp/NoOpTResultSpecs.cs b/src/Polly.Specs/NoOp/NoOpTResultSpecs.cs index 5e8aacbd533..9c940f9552b 100644 --- a/src/Polly.Specs/NoOp/NoOpTResultSpecs.cs +++ b/src/Polly.Specs/NoOp/NoOpTResultSpecs.cs @@ -10,7 +10,7 @@ public class NoOpTResultSpecs [Fact] public void Should_execute_user_delegate() { - var policy = Policy.NoOp(); + NoOpPolicy policy = Policy.NoOp(); int? result = null; policy.Invoking(x => result = x.Execute(() => 10)) @@ -23,18 +23,18 @@ public void Should_execute_user_delegate() [Fact] public void Should_execute_user_delegate_without_adding_extra_cancellation_behaviour() { - var policy = Policy.NoOp(); + NoOpPolicy policy = Policy.NoOp(); int? result = null; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); policy.Invoking(p => result = p.Execute(_ => 10, cts.Token)) - .Should().NotThrow(); + .Should().NotThrow(); } result.HasValue.Should().BeTrue(); result.Should().Be(10); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/PolicyAsyncSpecs.cs b/src/Polly.Specs/PolicyAsyncSpecs.cs index 7d5d2f1c2de..987c027fa25 100644 --- a/src/Polly.Specs/PolicyAsyncSpecs.cs +++ b/src/Polly.Specs/PolicyAsyncSpecs.cs @@ -14,7 +14,7 @@ public class PolicyAsyncSpecs [Fact] public async Task Executing_the_policy_action_should_execute_the_specified_async_action() { - var executed = false; + bool executed = false; var policy = Policy .Handle() @@ -37,7 +37,7 @@ public async Task Executing_the_policy_function_should_execute_the_specified_asy .Handle() .RetryAsync((_, _) => { }); - var result = await policy.ExecuteAsync(() => Task.FromResult(2)); + int result = await policy.ExecuteAsync(() => Task.FromResult(2)); result.Should() .Be(2); @@ -165,56 +165,56 @@ public async Task Executing_the_policy_function_and_failing_with_an_unhandled_ex #region Context tests [Fact] - public void Executing_the_policy_action_should_throw_when_context_data_is_null() + public async Task Executing_the_policy_action_should_throw_when_context_data_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAsync(_ => TaskHelper.EmptyTask, (IDictionary)null)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(_ => TaskHelper.EmptyTask, (IDictionary)null)) + .Should().ThrowAsync(); } [Fact] - public void Executing_the_policy_action_should_throw_when_context_is_null() + public async Task Executing_the_policy_action_should_throw_when_context_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAsync(_ => TaskHelper.EmptyTask, (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + var ex = await policy.Awaiting(p => p.ExecuteAsync(_ => TaskHelper.EmptyTask, (Context)null)) + .Should().ThrowAsync(); + ex.And.ParamName.Should().Be("context"); } [Fact] - public void Executing_the_policy_function_should_throw_when_context_data_is_null() + public async Task Executing_the_policy_function_should_throw_when_context_data_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(2), (IDictionary)null)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(2), (IDictionary)null)) + .Should().ThrowAsync(); } [Fact] - public void Executing_the_policy_function_should_throw_when_context_is_null() + public async Task Executing_the_policy_function_should_throw_when_context_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(2), (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + var ex = await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(2), (Context)null)) + .Should().ThrowAsync(); + ex.And.ParamName.Should().Be("context"); } [Fact] public async Task Executing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; var policy = Policy.NoOpAsync(); @@ -225,56 +225,56 @@ public async Task Executing_the_policy_function_should_pass_context_to_executed_ } [Fact] - public void Execute_and_capturing_the_policy_action_should_throw_when_context_data_is_null() + public async Task Execute_and_capturing_the_policy_action_should_throw_when_context_data_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, (IDictionary)null)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, (IDictionary)null)) + .Should().ThrowAsync(); } [Fact] - public void Execute_and_capturing_the_policy_action_should_throw_when_context_is_null() + public async Task Execute_and_capturing_the_policy_action_should_throw_when_context_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + var ex = await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, (Context)null)) + .Should().ThrowAsync(); + ex.And.ParamName.Should().Be("context"); } [Fact] - public void Execute_and_capturing_the_policy_function_should_throw_when_context_data_is_null() + public async Task Execute_and_capturing_the_policy_function_should_throw_when_context_data_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(2), (IDictionary)null)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(2), (IDictionary)null)) + .Should().ThrowAsync(); } [Fact] - public void Execute_and_capturing_the_policy_function_should_throw_when_context_is_null() + public async Task Execute_and_capturing_the_policy_function_should_throw_when_context_is_null() { var policy = Policy .Handle() .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(2), (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + var ex = await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(2), (Context)null)) + .Should().ThrowAsync(); + ex.And.ParamName.Should().Be("context"); } [Fact] public async Task Execute_and_capturing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; var policy = Policy.NoOpAsync(); @@ -287,8 +287,8 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ [Fact] public async Task Execute_and_capturing_the_policy_function_should_pass_context_to_PolicyResult() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); var policy = Policy.NoOpAsync(); @@ -297,4 +297,4 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs b/src/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs index 3a64bb76041..c6ada99be00 100644 --- a/src/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs +++ b/src/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs @@ -62,7 +62,7 @@ public void PolicyKey_property_should_be_non_null_or_empty_if_not_explicitly_con public void PolicyKey_property_should_start_with_policy_type_if_not_explicitly_configured() { var policy = Policy.Handle().RetryAsync(); - + policy.PolicyKey.Should().StartWith("AsyncRetry"); } @@ -91,7 +91,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr { var policy = Policy.Handle().RetryAsync(); - var retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; + string retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); @@ -105,7 +105,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr [Fact] public async Task Should_pass_PolicyKey_to_execution_context() { - var policyKey = Guid.NewGuid().ToString(); + string policyKey = Guid.NewGuid().ToString(); string policyKeySetOnExecutionContext = null; Action onRetry = (_, _, context) => { policyKeySetOnExecutionContext = context.PolicyKey; }; @@ -119,13 +119,13 @@ public async Task Should_pass_PolicyKey_to_execution_context() [Fact] public async Task Should_pass_OperationKey_to_execution_context() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; string operationKeySetOnContext = null; Action onRetry = (_, _, context) => { operationKeySetOnContext = context.OperationKey; }; var retry = Policy.Handle().RetryAsync(1, onRetry); - var firstExecution = true; + bool firstExecution = true; await retry.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; @@ -142,13 +142,13 @@ await retry.ExecuteAsync(async _ => [Fact] public async Task Should_pass_PolicyKey_to_execution_context_in_generic_execution_on_non_generic_policy() { - var policyKey = Guid.NewGuid().ToString(); + string policyKey = Guid.NewGuid().ToString(); string policyKeySetOnExecutionContext = null; Action onRetry = (_, _, context) => { policyKeySetOnExecutionContext = context.PolicyKey; }; var retry = Policy.Handle().RetryAsync(1, onRetry).WithPolicyKey(policyKey); - var firstExecution = true; + bool firstExecution = true; await retry.ExecuteAsync(async () => { await TaskHelper.EmptyTask; @@ -166,13 +166,13 @@ await retry.ExecuteAsync(async () => [Fact] public async Task Should_pass_OperationKey_to_execution_context_in_generic_execution_on_non_generic_policy() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; string operationKeySetOnContext = null; Action onRetry = (_, _, context) => { operationKeySetOnContext = context.OperationKey; }; var retry = Policy.Handle().RetryAsync(1, onRetry); - var firstExecution = true; + bool firstExecution = true; await retry.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; @@ -274,7 +274,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr { var policy = Policy.HandleResult(0).RetryAsync(); - var retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; + string retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); @@ -288,7 +288,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr [Fact] public async Task Should_pass_PolicyKey_to_execution_context() { - var policyKey = Guid.NewGuid().ToString(); + string policyKey = Guid.NewGuid().ToString(); string policyKeySetOnExecutionContext = null; Action, int, Context> onRetry = (_, _, context) => { policyKeySetOnExecutionContext = context.PolicyKey; }; @@ -302,13 +302,13 @@ public async Task Should_pass_PolicyKey_to_execution_context() [Fact] public async Task Should_pass_OperationKey_to_execution_context() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; string operationKeySetOnContext = null; Action, int, Context> onRetry = (_, _, context) => { operationKeySetOnContext = context.OperationKey; }; var retry = Policy.HandleResult(ResultPrimitive.Fault).RetryAsync(1, onRetry); - var firstExecution = true; + bool firstExecution = true; await retry.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; @@ -325,4 +325,4 @@ await retry.ExecuteAsync(async _ => #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/PolicyContextAndKeySpecs.cs b/src/Polly.Specs/PolicyContextAndKeySpecs.cs index a414311d399..2f6ce29057f 100644 --- a/src/Polly.Specs/PolicyContextAndKeySpecs.cs +++ b/src/Polly.Specs/PolicyContextAndKeySpecs.cs @@ -90,7 +90,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr { var policy = Policy.Handle().Retry(); - var retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; + string retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); @@ -104,7 +104,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr [Fact] public void Should_pass_PolicyKey_to_execution_context() { - var policyKey = Guid.NewGuid().ToString(); + string policyKey = Guid.NewGuid().ToString(); string policyKeySetOnExecutionContext = null; Action onRetry = (_, _, context) => { policyKeySetOnExecutionContext = context.PolicyKey; }; @@ -118,13 +118,13 @@ public void Should_pass_PolicyKey_to_execution_context() [Fact] public void Should_pass_OperationKey_to_execution_context() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; string operationKeySetOnContext = null; Action onRetry = (_, _, context) => { operationKeySetOnContext = context.OperationKey; }; var retry = Policy.Handle().Retry(1, onRetry); - var firstExecution = true; + bool firstExecution = true; retry.Execute(_ => { if (firstExecution) @@ -140,13 +140,13 @@ public void Should_pass_OperationKey_to_execution_context() [Fact] public void Should_pass_PolicyKey_to_execution_context_in_generic_execution_on_non_generic_policy() { - var policyKey = Guid.NewGuid().ToString(); + string policyKey = Guid.NewGuid().ToString(); string policyKeySetOnExecutionContext = null; Action onRetry = (_, _, context) => { policyKeySetOnExecutionContext = context.PolicyKey; }; var retry = Policy.Handle().Retry(1, onRetry).WithPolicyKey(policyKey); - var firstExecution = true; + bool firstExecution = true; retry.Execute(() => { if (firstExecution) @@ -163,13 +163,13 @@ public void Should_pass_PolicyKey_to_execution_context_in_generic_execution_on_n [Fact] public void Should_pass_OperationKey_to_execution_context_in_generic_execution_on_non_generic_policy() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; string operationKeySetOnContext = null; Action onRetry = (_, _, context) => { operationKeySetOnContext = context.OperationKey; }; var retry = Policy.Handle().Retry(1, onRetry); - var firstExecution = true; + bool firstExecution = true; retry.Execute(_ => { if (firstExecution) @@ -271,7 +271,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr { var policy = Policy.HandleResult(0).Retry(); - var retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; + string retrieveKeyWhenNotExplicitlyConfigured = policy.PolicyKey; Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); @@ -285,7 +285,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr [Fact] public void Should_pass_PolicyKey_to_execution_context() { - var policyKey = Guid.NewGuid().ToString(); + string policyKey = Guid.NewGuid().ToString(); string policyKeySetOnExecutionContext = null; Action, int, Context> onRetry = (_, _, context) => { policyKeySetOnExecutionContext = context.PolicyKey; }; @@ -299,13 +299,13 @@ public void Should_pass_PolicyKey_to_execution_context() [Fact] public void Should_pass_OperationKey_to_execution_context() { - var operationKey = "SomeKey"; + string operationKey = "SomeKey"; string operationKeySetOnContext = null; Action, int, Context> onRetry = (_, _, context) => { operationKeySetOnContext = context.OperationKey; }; var retry = Policy.HandleResult(ResultPrimitive.Fault).Retry(1, onRetry); - var firstExecution = true; + bool firstExecution = true; retry.Execute(_ => { if (firstExecution) @@ -320,4 +320,4 @@ public void Should_pass_OperationKey_to_execution_context() } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/PolicySpecs.cs b/src/Polly.Specs/PolicySpecs.cs index 517108c8f42..0d335066ea7 100644 --- a/src/Polly.Specs/PolicySpecs.cs +++ b/src/Polly.Specs/PolicySpecs.cs @@ -166,7 +166,7 @@ public void Executing_the_policy_action_should_throw_when_context_data_is_null() .Retry((_, _, _) => { }); policy.Invoking(p => p.Execute(_ => { }, (IDictionary)null)) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -207,8 +207,8 @@ public void Executing_the_policy_function_should_throw_when_context_is_null() [Fact] public void Executing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; Policy policy = Policy.NoOp(); @@ -226,7 +226,7 @@ public void Execute_and_capturing_the_policy_action_should_throw_when_context_da .Retry((_, _, _) => { }); policy.Invoking(p => p.ExecuteAndCapture(_ => { }, (IDictionary)null)) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -249,7 +249,7 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .Retry((_, _, _) => { }); policy.Invoking(p => p.ExecuteAndCapture(_ => 2, (IDictionary)null)) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -260,15 +260,15 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .Retry((_, _, _) => { }); policy.Invoking(p => p.ExecuteAndCapture(_ => 2, (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + .Should().Throw().And + .ParamName.Should().Be("context"); } [Fact] public void Execute_and_capturing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; Policy policy = Policy.NoOp(); @@ -281,8 +281,8 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_exe [Fact] public void Execute_and_capturing_the_policy_function_should_pass_context_to_PolicyResult() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Policy policy = Policy.NoOp(); @@ -291,4 +291,4 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_Pol } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/PolicyTResultAsyncSpecs.cs b/src/Polly.Specs/PolicyTResultAsyncSpecs.cs index 1ab76fb217c..f767dbb5e6e 100644 --- a/src/Polly.Specs/PolicyTResultAsyncSpecs.cs +++ b/src/Polly.Specs/PolicyTResultAsyncSpecs.cs @@ -96,45 +96,45 @@ public async Task Executing_the_policy_function_and_returning_an_unhandled_resul [Fact] - public void Executing_the_policy_function_should_throw_when_context_data_is_null() + public async Task Executing_the_policy_function_should_throw_when_context_data_is_null() { var policy = Policy .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), (IDictionary)null)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), (IDictionary)null)) + .Should().ThrowAsync(); } [Fact] - public void Executing_the_policy_function_should_throw_when_context_is_null() + public async Task Executing_the_policy_function_should_throw_when_context_is_null() { var policy = Policy .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + var ex = await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), (Context)null)) + .Should().ThrowAsync(); + ex.And.ParamName.Should().Be("context"); } [Fact] - public void Execute_and_capturing_the_policy_function_should_throw_when_context_data_is_null() + public async Task Execute_and_capturing_the_policy_function_should_throw_when_context_data_is_null() { var policy = Policy .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Good), (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + var ex = await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Good), (Context)null)) + .Should().ThrowAsync(); + ex.And.ParamName.Should().Be("context"); } [Fact] public async Task Executing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; var policy = Policy.NoOpAsync(); @@ -145,22 +145,22 @@ public async Task Executing_the_policy_function_should_pass_context_to_executed_ } [Fact] - public void Execute_and_capturing_the_policy_function_should_throw_when_context_is_null() + public async Task Execute_and_capturing_the_policy_function_should_throw_when_context_is_null() { var policy = Policy .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, _) => { }); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Good), (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + var ex = await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Good), (Context)null)) + .Should().ThrowAsync(); + ex.And.ParamName.Should().Be("context"); } [Fact] public async Task Execute_and_capturing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; var policy = Policy.NoOpAsync(); @@ -173,8 +173,8 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ [Fact] public async Task Execute_and_capturing_the_policy_function_should_pass_context_to_PolicyResult() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); var policy = Policy.NoOpAsync(); @@ -183,4 +183,4 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/PolicyTResultSpecs.cs b/src/Polly.Specs/PolicyTResultSpecs.cs index b78a1f65023..9720c752c7e 100644 --- a/src/Polly.Specs/PolicyTResultSpecs.cs +++ b/src/Polly.Specs/PolicyTResultSpecs.cs @@ -119,8 +119,8 @@ public void Executing_the_policy_function_should_throw_when_context_is_null() [Fact] public void Executing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; Policy policy = Policy.NoOp(); @@ -138,7 +138,7 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .Retry((_, _, _) => { }); policy.Invoking(p => p.ExecuteAndCapture(_ => ResultPrimitive.Good, (IDictionary)null)) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -149,15 +149,15 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .Retry((_, _, _) => { }); policy.Invoking(p => p.ExecuteAndCapture(_ => ResultPrimitive.Good, (Context)null)) - .Should().Throw().And - .ParamName.Should().Be("context"); + .Should().Throw().And + .ParamName.Should().Be("context"); } [Fact] public void Execute_and_capturing_the_policy_function_should_pass_context_to_executed_delegate() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Context capturedContext = null; Policy policy = Policy.NoOp(); @@ -170,8 +170,8 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_exe [Fact] public void Execute_and_capturing_the_policy_function_should_pass_context_to_PolicyResult() { - var operationKey = "SomeKey"; - var executionContext = new Context(operationKey); + string operationKey = "SomeKey"; + Context executionContext = new Context(operationKey); Policy policy = Policy.NoOp(); @@ -180,4 +180,4 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_Pol } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Polly.Specs.csproj b/src/Polly.Specs/Polly.Specs.csproj index 6ad7be03aec..04a83c8fecc 100644 --- a/src/Polly.Specs/Polly.Specs.csproj +++ b/src/Polly.Specs/Polly.Specs.csproj @@ -1,9 +1,8 @@  - netcoreapp2.1;netcoreapp3.1;net6.0;net461;net472 - - false + netcoreapp3.1;net6.0 + $(TargetFrameworks);net461;net472 true @@ -12,7 +11,8 @@ - + + @@ -23,4 +23,11 @@ + + true + [xunit.*]* + System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute + 75,60,70 + + diff --git a/src/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs b/src/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs index 2a0a7200af9..addb68a7eff 100644 --- a/src/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs +++ b/src/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs @@ -16,12 +16,16 @@ public void Dispose() SystemClock.Reset(); } - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) => - Policy.RateLimitAsync(numberOfExecutions, perTimeSpan); - - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) => - Policy.RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst); + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) + { + return Policy.RateLimitAsync(numberOfExecutions, perTimeSpan); + } + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) + { + return Policy.RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst); + } + protected override (bool, TimeSpan) TryExecuteThroughPolicy(IRateLimitPolicy policy) { if (policy is AsyncRateLimitPolicy typedPolicy) @@ -41,4 +45,4 @@ protected override (bool, TimeSpan) TryExecuteThroughPolicy(IRateLimitPolicy pol throw new InvalidOperationException("Unexpected policy type in test construction."); } } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs b/src/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs index acd8794f747..fc12dab463b 100644 --- a/src/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs +++ b/src/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs @@ -11,18 +11,26 @@ namespace Polly.Specs.RateLimit; [Collection(Polly.Specs.Helpers.Constants.SystemClockDependentTestCollection)] public class AsyncRateLimitPolicyTResultSpecs : RateLimitPolicyTResultSpecsBase, IDisposable { - public void Dispose() => + public void Dispose() + { SystemClock.Reset(); + } - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) => - Policy.RateLimitAsync(numberOfExecutions, perTimeSpan); + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) + { + return Policy.RateLimitAsync(numberOfExecutions, perTimeSpan); + } - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) => - Policy.RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst); + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) + { + return Policy.RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst); + } protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst, - Func retryAfterFactory) => - Policy.RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst, retryAfterFactory); + Func retryAfterFactory) + { + return Policy.RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst, retryAfterFactory); + } protected override (bool, TimeSpan) TryExecuteThroughPolicy(IRateLimitPolicy policy) { @@ -55,4 +63,4 @@ protected override TResult TryExecuteThroughPolicy(IRateLimitPolicy new LockFreeTokenBucketRateLimiter(onePer, bucketCapacity); -} \ No newline at end of file +} diff --git a/src/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs b/src/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs index c6ea7262503..7994baaec7f 100644 --- a/src/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs +++ b/src/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs @@ -15,11 +15,15 @@ public void Dispose() SystemClock.Reset(); } - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) => - Policy.RateLimit(numberOfExecutions, perTimeSpan); + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) + { + return Policy.RateLimit(numberOfExecutions, perTimeSpan); + } - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) => - Policy.RateLimit(numberOfExecutions, perTimeSpan, maxBurst); + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) + { + return Policy.RateLimit(numberOfExecutions, perTimeSpan, maxBurst); + } protected override (bool, TimeSpan) TryExecuteThroughPolicy(IRateLimitPolicy policy) { @@ -40,4 +44,4 @@ protected override (bool, TimeSpan) TryExecuteThroughPolicy(IRateLimitPolicy pol throw new InvalidOperationException("Unexpected policy type in test construction."); } } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs b/src/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs index dbeec16b47a..6bc1dbd14a1 100644 --- a/src/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs +++ b/src/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs @@ -23,7 +23,7 @@ protected abstract IRateLimitPolicy GetPolicyViaSyntax( protected void ShouldPermitAnExecution(IRateLimitPolicy policy) { - (var permitExecution, var retryAfter) = TryExecuteThroughPolicy(policy); + (bool permitExecution, TimeSpan retryAfter) = TryExecuteThroughPolicy(policy); permitExecution.Should().BeTrue(); retryAfter.Should().Be(TimeSpan.Zero); @@ -31,7 +31,7 @@ protected void ShouldPermitAnExecution(IRateLimitPolicy policy) protected void ShouldPermitNExecutions(IRateLimitPolicy policy, long numberOfExecutions) { - for (var execution = 0; execution < numberOfExecutions; execution++) + for (int execution = 0; execution < numberOfExecutions; execution++) { ShouldPermitAnExecution(policy); } @@ -126,7 +126,7 @@ public void Given_bucket_capacity_one_and_time_not_advanced_ratelimiter_specifie FixClock(); // Arrange - var onePer = TimeSpan.FromSeconds(onePerSeconds); + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetPolicyViaSyntax(1, onePer); // Assert - first execution after initialising should always be permitted. @@ -148,7 +148,7 @@ public void Given_bucket_capacity_N_and_time_not_advanced_ratelimiter_permits_ex FixClock(); // Arrange. - var onePer = TimeSpan.FromSeconds(1); + TimeSpan onePer = TimeSpan.FromSeconds(1); var rateLimiter = GetPolicyViaSyntax(1, onePer, bucketCapacity); // Act - should be able to successfully take bucketCapacity items. @@ -170,7 +170,7 @@ public void Given_any_bucket_capacity_ratelimiter_permits_another_execution_per_ FixClock(); // Arrange - var onePer = TimeSpan.FromSeconds(onePerSeconds); + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetPolicyViaSyntax(1, onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -178,10 +178,10 @@ public void Given_any_bucket_capacity_ratelimiter_permits_another_execution_per_ ShouldNotPermitAnExecution(rateLimiter); // Act-Assert - repeatedly advance the clock towards the interval but not quite - then to the interval - var experimentRepeats = bucketCapacity * 3; - var shortfallFromInterval = TimeSpan.FromTicks(1); - var notQuiteInterval = onePer - shortfallFromInterval; - for (var i = 0; i < experimentRepeats; i++) + int experimentRepeats = bucketCapacity * 3; + TimeSpan shortfallFromInterval = TimeSpan.FromTicks(1); + TimeSpan notQuiteInterval = onePer - shortfallFromInterval; + for (int i = 0; i < experimentRepeats; i++) { // Arrange - Advance clock not quite to the interval AdvanceClock(notQuiteInterval.Ticks); @@ -208,8 +208,8 @@ public void Given_any_bucket_capacity_rate_limiter_permits_full_bucket_burst_aft FixClock(); // Arrange - var onePerSeconds = 1; - var onePer = TimeSpan.FromSeconds(onePerSeconds); + int onePerSeconds = 1; + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetPolicyViaSyntax(1, onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -234,8 +234,8 @@ public void Given_any_bucket_capacity_rate_limiter_permits_half_full_bucket_burs FixClock(); // Arrange - var onePerSeconds = 1; - var onePer = TimeSpan.FromSeconds(onePerSeconds); + int onePerSeconds = 1; + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetPolicyViaSyntax(1, onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -260,8 +260,8 @@ public void Given_any_bucket_capacity_rate_limiter_permits_only_full_bucket_burs FixClock(); // Arrange - var onePerSeconds = 1; - var onePer = TimeSpan.FromSeconds(onePerSeconds); + int onePerSeconds = 1; + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetPolicyViaSyntax(1, onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -285,13 +285,13 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o FixClock(); // Arrange - var onePer = TimeSpan.FromSeconds(1); + TimeSpan onePer = TimeSpan.FromSeconds(1); var rateLimiter = GetPolicyViaSyntax(1, onePer); // Arrange - parallel tasks all waiting on a manual reset event. ManualResetEventSlim gate = new(); Task<(bool permitExecution, TimeSpan retryAfter)>[] tasks = new Task<(bool, TimeSpan)>[parallelContention]; - for (var i = 0; i < parallelContention; i++) + for (int i = 0; i < parallelContention; i++) { tasks[i] = Task.Run(() => { @@ -309,4 +309,4 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o results.Count(r => r.permitExecution).Should().Be(1); results.Count(r => !r.permitExecution).Should().Be(parallelContention - 1); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs b/src/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs index 9e9fa4b7f77..320e13e65f6 100644 --- a/src/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs +++ b/src/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs @@ -15,15 +15,21 @@ public void Dispose() SystemClock.Reset(); } - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) => - Policy.RateLimit(numberOfExecutions, perTimeSpan); + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan) + { + return Policy.RateLimit(numberOfExecutions, perTimeSpan); + } - protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) => - Policy.RateLimit(numberOfExecutions, perTimeSpan, maxBurst); + protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst) + { + return Policy.RateLimit(numberOfExecutions, perTimeSpan, maxBurst); + } protected override IRateLimitPolicy GetPolicyViaSyntax(int numberOfExecutions, TimeSpan perTimeSpan, int maxBurst, - Func retryAfterFactory) => - Policy.RateLimit(numberOfExecutions, perTimeSpan, maxBurst, retryAfterFactory); + Func retryAfterFactory) + { + return Policy.RateLimit(numberOfExecutions, perTimeSpan, maxBurst, retryAfterFactory); + } protected override (bool, TimeSpan) TryExecuteThroughPolicy(IRateLimitPolicy policy) { @@ -56,4 +62,4 @@ protected override TResult TryExecuteThroughPolicy(IRateLimitPolicy retryAfterFactory = (t, ctx) => { @@ -42,7 +42,7 @@ public void Ratelimiter_specifies_correct_wait_until_next_execution_by_custom_fa // (do nothing - time not advanced) // Act - try another execution. - var contextToPassIn = new Context(); + Context contextToPassIn = new Context(); var resultExpectedBlocked = TryExecuteThroughPolicy(rateLimiter, contextToPassIn, new ResultClassWithRetryAfter(ResultPrimitive.Good)); // Assert - should be blocked - time not advanced. @@ -53,4 +53,4 @@ public void Ratelimiter_specifies_correct_wait_until_next_execution_by_custom_fa contextPassedToRetryAfter.Should().NotBeNull(); contextPassedToRetryAfter.Should().BeSameAs(contextToPassIn); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/RateLimit/RateLimitSpecsBase.cs b/src/Polly.Specs/RateLimit/RateLimitSpecsBase.cs index 1a447d98a13..32753153f45 100644 --- a/src/Polly.Specs/RateLimit/RateLimitSpecsBase.cs +++ b/src/Polly.Specs/RateLimit/RateLimitSpecsBase.cs @@ -16,9 +16,9 @@ public abstract class RateLimitSpecsBase /// The action containing fluent assertions, which must succeed within the timespan. protected void Within(TimeSpan timeSpan, Action actionContainingAssertions) { - var retryInterval = TimeSpan.FromSeconds(0.2); + TimeSpan retryInterval = TimeSpan.FromSeconds(0.2); - var watch = Stopwatch.StartNew(); + Stopwatch watch = Stopwatch.StartNew(); while (true) { try @@ -39,15 +39,15 @@ protected void Within(TimeSpan timeSpan, Action actionContainingAssertions) protected static void FixClock() { - var now = DateTimeOffset.UtcNow; + DateTimeOffset now = DateTimeOffset.UtcNow; SystemClock.DateTimeOffsetUtcNow = () => now; } protected static void AdvanceClock(TimeSpan advance) { - var now = SystemClock.DateTimeOffsetUtcNow(); + DateTimeOffset now = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => now + advance; } protected static void AdvanceClock(long advanceTicks) => AdvanceClock(TimeSpan.FromTicks(advanceTicks)); -} \ No newline at end of file +} diff --git a/src/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs b/src/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs index 58b017ebb5d..1e30031e516 100644 --- a/src/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs +++ b/src/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs @@ -29,7 +29,7 @@ public void Given_bucket_capacity_one_and_time_not_advanced_ratelimiter_specifie FixClock(); // Arrange - var onePer = TimeSpan.FromSeconds(onePerSeconds); + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetRateLimiter(onePer, 1); // Assert - first execution after initialising should always be permitted. @@ -51,7 +51,7 @@ public void Given_bucket_capacity_N_and_time_not_advanced_ratelimiter_permits_ex FixClock(); // Arrange. - var onePer = TimeSpan.FromSeconds(1); + TimeSpan onePer = TimeSpan.FromSeconds(1); var rateLimiter = GetRateLimiter(onePer, bucketCapacity); // Act - should be able to successfully take bucketCapacity items. @@ -73,7 +73,7 @@ public void Given_any_bucket_capacity_ratelimiter_permits_another_execution_per_ FixClock(); // Arrange - var onePer = TimeSpan.FromSeconds(onePerSeconds); + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetRateLimiter(onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -81,10 +81,10 @@ public void Given_any_bucket_capacity_ratelimiter_permits_another_execution_per_ rateLimiter.ShouldNotPermitAnExecution(); // Act-Assert - repeatedly advance the clock towards the interval but not quite - then to the interval - var experimentRepeats = bucketCapacity * 3; - var shortfallFromInterval = TimeSpan.FromTicks(1); - var notQuiteInterval = onePer - shortfallFromInterval; - for (var i = 0; i < experimentRepeats; i++) + int experimentRepeats = bucketCapacity * 3; + TimeSpan shortfallFromInterval = TimeSpan.FromTicks(1); + TimeSpan notQuiteInterval = onePer - shortfallFromInterval; + for (int i = 0; i < experimentRepeats; i++) { // Arrange - Advance clock not quite to the interval AdvanceClock(notQuiteInterval.Ticks); @@ -111,8 +111,8 @@ public void Given_any_bucket_capacity_rate_limiter_permits_full_bucket_burst_aft FixClock(); // Arrange - var onePerSeconds = 1; - var onePer = TimeSpan.FromSeconds(onePerSeconds); + int onePerSeconds = 1; + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetRateLimiter(onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -137,8 +137,8 @@ public void Given_any_bucket_capacity_rate_limiter_permits_half_full_bucket_burs FixClock(); // Arrange - var onePerSeconds = 1; - var onePer = TimeSpan.FromSeconds(onePerSeconds); + int onePerSeconds = 1; + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetRateLimiter(onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -163,8 +163,8 @@ public void Given_any_bucket_capacity_rate_limiter_permits_only_full_bucket_burs FixClock(); // Arrange - var onePerSeconds = 1; - var onePer = TimeSpan.FromSeconds(onePerSeconds); + int onePerSeconds = 1; + TimeSpan onePer = TimeSpan.FromSeconds(onePerSeconds); var rateLimiter = GetRateLimiter(onePer, bucketCapacity); // Arrange - spend the initial bucket capacity. @@ -188,13 +188,13 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o FixClock(); // Arrange - var onePer = TimeSpan.FromSeconds(1); + TimeSpan onePer = TimeSpan.FromSeconds(1); var rateLimiter = GetRateLimiter(onePer, 1); // Arrange - parallel tasks all waiting on a manual reset event. - var gate = new ManualResetEventSlim(); + ManualResetEventSlim gate = new ManualResetEventSlim(); Task<(bool permitExecution, TimeSpan retryAfter)>[] tasks = new Task<(bool, TimeSpan)>[parallelContention]; - for (var i = 0; i < parallelContention; i++) + for (int i = 0; i < parallelContention; i++) { tasks[i] = Task.Run(() => { @@ -212,4 +212,4 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o results.Count(r => r.permitExecution).Should().Be(1); results.Count(r => !r.permitExecution).Should().Be(parallelContention - 1); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs b/src/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs index 159ade9af88..7738cc71d6f 100644 --- a/src/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs +++ b/src/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs @@ -20,14 +20,14 @@ public ConcurrentPolicyRegistrySpecs() public void Should_be_able_to_add_Policy_using_TryAdd() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var insert = _registry.TryAdd(key, policy); _registry.Count.Should().Be(1); insert.Should().Be(true); Policy policy2 = Policy.NoOp(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); var insert2 = _registry.TryAdd(key2, policy2); _registry.Count.Should().Be(2); @@ -38,14 +38,14 @@ public void Should_be_able_to_add_Policy_using_TryAdd() public void Should_be_able_to_add_PolicyTResult_using_TryAdd() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var insert = _registry.TryAdd(key, policy); _registry.Count.Should().Be(1); insert.Should().Be(true); Policy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); var insert2 = _registry.TryAdd(key2, policy2); _registry.Count.Should().Be(2); @@ -56,14 +56,14 @@ public void Should_be_able_to_add_PolicyTResult_using_TryAdd() public void Should_be_able_to_add_Policy_by_interface_using_TryAdd() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var insert = _registry.TryAdd(key, policy); _registry.Count.Should().Be(1); insert.Should().Be(true); ISyncPolicy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); var insert2 = _registry.TryAdd(key2, policy2); _registry.Count.Should().Be(2); @@ -74,12 +74,12 @@ public void Should_be_able_to_add_Policy_by_interface_using_TryAdd() public void Should_be_able_to_remove_policy_with_TryRemove() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Count.Should().Be(1); - var removed = _registry.TryRemove(key, out IsPolicy removedPolicy); + bool removed = _registry.TryRemove(key, out IsPolicy removedPolicy); _registry.Count.Should().Be(0); removedPolicy.Should().BeSameAs(policy); removed.Should().BeTrue(); @@ -88,9 +88,9 @@ public void Should_be_able_to_remove_policy_with_TryRemove() [Fact] public void Should_report_false_from_TryRemove_if_no_Policy() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); - var removed = _registry.TryRemove(key, out IsPolicy removedPolicy); + bool removed = _registry.TryRemove(key, out IsPolicy removedPolicy); removed.Should().BeFalse(); } @@ -98,12 +98,12 @@ public void Should_report_false_from_TryRemove_if_no_Policy() public void Should_be_able_to_update_policy_with_TryUpdate() { Policy existingPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); Policy newPolicy = Policy.NoOp(); - var updated = _registry.TryUpdate(key, newPolicy, existingPolicy); + bool updated = _registry.TryUpdate(key, newPolicy, existingPolicy); updated.Should().BeTrue(); _registry[key].Should().BeSameAs(newPolicy); @@ -113,13 +113,13 @@ public void Should_be_able_to_update_policy_with_TryUpdate() public void Should_not_update_policy_with_TryUpdate_when_existingPolicy_mismatch() { Policy existingPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); - var someOtherPolicy = Policy.NoOp(); + NoOpPolicy someOtherPolicy = Policy.NoOp(); Policy newPolicy = Policy.NoOp(); - var updated = _registry.TryUpdate(key, newPolicy, someOtherPolicy); + bool updated = _registry.TryUpdate(key, newPolicy, someOtherPolicy); updated.Should().BeFalse(); _registry[key].Should().BeSameAs(existingPolicy); @@ -128,12 +128,12 @@ public void Should_not_update_policy_with_TryUpdate_when_existingPolicy_mismatch [Fact] public void Should_not_update_policy_with_TryUpdate_when_no_existing_value() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); - var someOtherPolicy = Policy.NoOp(); + NoOpPolicy someOtherPolicy = Policy.NoOp(); Policy newPolicy = Policy.NoOp(); - var updated = _registry.TryUpdate(key, newPolicy, someOtherPolicy); + bool updated = _registry.TryUpdate(key, newPolicy, someOtherPolicy); updated.Should().BeFalse(); _registry.ContainsKey(key).Should().BeFalse(); @@ -143,7 +143,7 @@ public void Should_not_update_policy_with_TryUpdate_when_no_existing_value() public void Should_add_with_GetOrAdd_with_value_when_no_existing_policy() { Policy newPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var returnedPolicy = _registry.GetOrAdd(key, newPolicy); @@ -154,7 +154,7 @@ public void Should_add_with_GetOrAdd_with_value_when_no_existing_policy() public void Should_add_with_GetOrAdd_with_factory_when_no_existing_policy() { Policy newPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var returnedPolicy = _registry.GetOrAdd(key, _ => newPolicy); @@ -165,7 +165,7 @@ public void Should_add_with_GetOrAdd_with_factory_when_no_existing_policy() public void Should_return_existing_with_GetOrAdd_with_value_when_existing_policy() { Policy existingPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); Policy newPolicy = Policy.NoOp(); @@ -179,7 +179,7 @@ public void Should_return_existing_with_GetOrAdd_with_value_when_existing_policy public void Should_return_existing_with_GetOrAdd_with_factory_when_existing_policy() { Policy existingPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); Policy newPolicy = Policy.NoOp(); @@ -193,7 +193,7 @@ public void Should_return_existing_with_GetOrAdd_with_factory_when_existing_poli public void Should_add_with_AddOrUpdate_with_value_when_no_existing_policy() { Policy newPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var returnedPolicy = _registry.AddOrUpdate( key, @@ -207,7 +207,7 @@ public void Should_add_with_AddOrUpdate_with_value_when_no_existing_policy() public void Should_add_with_AddOrUpdate_with_addfactory_when_no_existing_policy() { Policy newPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var returnedPolicy = _registry.AddOrUpdate( @@ -222,7 +222,7 @@ public void Should_add_with_AddOrUpdate_with_addfactory_when_no_existing_policy( public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addvalue_when_existing_policy() { Policy existingPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); const string policyKeyToDecorate = "SomePolicyKey"; @@ -243,7 +243,7 @@ public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addvalue_ public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addfactory_when_existing_policy() { Policy existingPolicy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); const string policyKeyToDecorate = "SomePolicyKey"; @@ -260,4 +260,4 @@ public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addfactor returnedPolicy.PolicyKey.Should().Be(policyKeyToDecorate); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Registry/PolicyRegistrySpecs.cs b/src/Polly.Specs/Registry/PolicyRegistrySpecs.cs index e32594dec32..bfa28e6f9c7 100644 --- a/src/Polly.Specs/Registry/PolicyRegistrySpecs.cs +++ b/src/Polly.Specs/Registry/PolicyRegistrySpecs.cs @@ -25,13 +25,13 @@ public PolicyRegistrySpecs() public void Should_be_able_to_add_Policy_using_Add() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Count.Should().Be(1); Policy policy2 = Policy.NoOp(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); _registry.Add(key2, policy2); _registry.Count.Should().Be(2); @@ -41,13 +41,13 @@ public void Should_be_able_to_add_Policy_using_Add() public void Should_be_able_to_add_PolicyTResult_using_Add() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Count.Should().Be(1); Policy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); _registry.Add(key2, policy2); _registry.Count.Should().Be(2); @@ -57,29 +57,29 @@ public void Should_be_able_to_add_PolicyTResult_using_Add() public void Should_be_able_to_add_Policy_by_interface_using_Add() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Count.Should().Be(1); ISyncPolicy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); _registry.Add>(key2, policy2); _registry.Count.Should().Be(2); } - + [Fact] public void Should_be_able_to_add_Policy_using_Indexer() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry[key] = policy; _registry.Count.Should().Be(1); Policy policy2 = Policy.NoOp(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); _registry[key2] = policy2; _registry.Count.Should().Be(2); @@ -89,23 +89,23 @@ public void Should_be_able_to_add_Policy_using_Indexer() public void Should_be_able_to_add_PolicyTResult_using_Indexer() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry[key] = policy; _registry.Count.Should().Be(1); Policy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); _registry[key2] = policy2; _registry.Count.Should().Be(2); } - + [Fact] public void Should_not_be_able_to_add_Policy_with_duplicate_key_using_Add() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Invoking(r => r.Add(key, policy)) .Should().NotThrow(); @@ -120,7 +120,7 @@ public void Should_not_be_able_to_add_Policy_with_duplicate_key_using_Add() public void Should_be_able_to_overwrite_existing_Policy_if_key_exists_when_inserting_using_Indexer() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); Policy policy_new = Policy.NoOp(); @@ -135,7 +135,7 @@ public void Should_be_able_to_overwrite_existing_Policy_if_key_exists_when_inser public void Should_be_able_to_overwrite_existing_PolicyTResult_if_key_exists_when_inserting_using_Indexer() { Policy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add>(key, policy); Policy policy_new = Policy.HandleResult(ResultPrimitive.Fault).Retry(); @@ -145,7 +145,7 @@ public void Should_be_able_to_overwrite_existing_PolicyTResult_if_key_exists_whe _registry.Get>(key).Should().BeSameAs(policy_new); } - + [Fact] public void Should_throw_when_adding_Policy_using_Add_when_key_is_null() { @@ -172,7 +172,7 @@ public void Should_throw_when_adding_Policy_using_Indexer_when_key_is_null() public void Should_be_able_to_retrieve_stored_Policy_using_TryGet() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; _registry.Add(key, policy); @@ -184,7 +184,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_TryGet() public void Should_be_able_to_retrieve_stored_PolicyTResult_using_TryGet() { Policy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; _registry.Add(key, policy); @@ -196,7 +196,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_TryGet() public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_TryGet() { ISyncPolicy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); ISyncPolicy outPolicy = null; _registry.Add(key, policy); @@ -208,7 +208,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_TryGet() public void Should_be_able_to_retrieve_stored_Policy_using_Get() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Get(key).Should().BeSameAs(policy); @@ -218,7 +218,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Get() public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Get() { Policy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Get>(key).Should().BeSameAs(policy); @@ -228,7 +228,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Get() public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Get() { ISyncPolicy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Get>(key).Should().BeSameAs(policy); @@ -238,7 +238,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Get() public void Should_be_able_to_retrieve_stored_Policy_using_Indexer() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry[key].Should().BeSameAs(policy); @@ -248,7 +248,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Indexer() public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Indexer() { Policy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry[key].Should().BeSameAs(policy); @@ -258,7 +258,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Indexer() public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Indexer() { ISyncPolicy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry[key].Should().BeSameAs(policy); @@ -267,9 +267,9 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Indexer( [Fact] public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryGet() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; - var result = false; + bool result = false; _registry.Invoking(r => result = r.TryGet(key, out outPolicy)) .Should().NotThrow(); @@ -280,9 +280,9 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG [Fact] public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryGetPolicyTResult() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; - var result = false; + bool result = false; _registry.Invoking(r => result = r.TryGet(key, out outPolicy)) .Should().NotThrow(); @@ -293,9 +293,9 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG [Fact] public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryGetPolicy_by_interface() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); ISyncPolicy outPolicy = null; - var result = false; + bool result = false; _registry.Invoking(r => result = r.TryGet>(key, out outPolicy)) .Should().NotThrow(); @@ -306,7 +306,7 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG [Fact] public void Should_throw_while_retrieving_using_Get_when_key_does_not_exist() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy policy = null; _registry.Invoking(r => policy = r.Get(key)) .Should().Throw(); @@ -315,7 +315,7 @@ public void Should_throw_while_retrieving_using_Get_when_key_does_not_exist() [Fact] public void Should_throw_while_retrieving_using_GetTResult_when_key_does_not_exist() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy policy = null; _registry.Invoking(r => policy = r.Get>(key)) .Should().Throw(); @@ -324,7 +324,7 @@ public void Should_throw_while_retrieving_using_GetTResult_when_key_does_not_exi [Fact] public void Should_throw_while_retrieving_using_Get_by_interface_when_key_does_not_exist() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); ISyncPolicy policy = null; _registry.Invoking(r => policy = r.Get>(key)) .Should().Throw(); @@ -333,7 +333,7 @@ public void Should_throw_while_retrieving_using_Get_by_interface_when_key_does_n [Fact] public void Should_throw_while_retrieving_when_key_does_not_exist_using_Indexer() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); IsPolicy outPolicy = null; _registry.Invoking(r => outPolicy = r[key]) .Should().Throw(); @@ -382,13 +382,13 @@ public void Should_throw_when_retrieving_using_Indexer_when_key_is_null() public void Should_be_able_to_clear_registry() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Count.Should().Be(1); Policy policy2 = Policy.NoOp(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); _registry.Add(key2, policy2); _registry.Count.Should().Be(2); @@ -401,7 +401,7 @@ public void Should_be_able_to_clear_registry() public void Should_be_able_to_remove_policy() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.Count.Should().Be(1); @@ -425,12 +425,12 @@ public void Should_throw_when_removing_Policy_when_key_is_null() public void Should_be_able_to_check_if_key_exists() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); _registry.ContainsKey(key).Should().BeTrue(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); _registry.ContainsKey(key2).Should().BeFalse(); } @@ -469,4 +469,4 @@ public void Constructor_Called_With_Default_Parameters_Assigns_A_ConcurrentDicti } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs b/src/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs index b6f3b99b9d8..eb6a233ae7a 100644 --- a/src/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs +++ b/src/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs @@ -12,10 +12,12 @@ public class ReadOnlyPolicyRegistrySpecs { IPolicyRegistry _registry; - IReadOnlyPolicyRegistry ReadOnlyRegistry => _registry; + IReadOnlyPolicyRegistry ReadOnlyRegistry { get{ return _registry; } } - public ReadOnlyPolicyRegistrySpecs() => + public ReadOnlyPolicyRegistrySpecs() + { _registry = new PolicyRegistry(); + } #region Tests for retrieving policy @@ -23,7 +25,7 @@ public ReadOnlyPolicyRegistrySpecs() => public void Should_be_able_to_retrieve_stored_Policy_using_TryGet() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; _registry.Add(key, policy); @@ -35,7 +37,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_TryGet() public void Should_be_able_to_retrieve_stored_PolicyTResult_using_TryGet() { Policy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; _registry.Add(key, policy); @@ -47,7 +49,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_TryGet() public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_TryGet() { ISyncPolicy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); ISyncPolicy outPolicy = null; _registry.Add(key, policy); @@ -59,7 +61,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_TryGet() public void Should_be_able_to_retrieve_stored_Policy_using_Get() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); ReadOnlyRegistry.Get(key).Should().BeSameAs(policy); @@ -69,7 +71,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Get() public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Get() { Policy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); ReadOnlyRegistry.Get>(key).Should().BeSameAs(policy); @@ -79,7 +81,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Get() public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Get() { ISyncPolicy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); ReadOnlyRegistry.Get>(key).Should().BeSameAs(policy); @@ -89,7 +91,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Get() public void Should_be_able_to_retrieve_stored_Policy_using_Indexer() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); ReadOnlyRegistry[key].Should().BeSameAs(policy); @@ -99,7 +101,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Indexer() public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Indexer() { Policy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); ReadOnlyRegistry[key].Should().BeSameAs(policy); @@ -109,7 +111,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Indexer() public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Indexer() { ISyncPolicy policy = Policy.HandleResult(ResultPrimitive.Fault).Retry(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); ReadOnlyRegistry[key].Should().BeSameAs(policy); @@ -118,9 +120,9 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Indexer( [Fact] public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryGet() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; - var result = false; + bool result = false; ReadOnlyRegistry.Invoking(r => result = r.TryGet(key, out outPolicy)) .Should().NotThrow(); @@ -131,9 +133,9 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG [Fact] public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryGetPolicyTResult() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy outPolicy = null; - var result = false; + bool result = false; ReadOnlyRegistry.Invoking(r => result = r.TryGet(key, out outPolicy)) .Should().NotThrow(); @@ -144,9 +146,9 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG [Fact] public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryGetPolicy_by_interface() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); ISyncPolicy outPolicy = null; - var result = false; + bool result = false; ReadOnlyRegistry.Invoking(r => result = r.TryGet>(key, out outPolicy)) .Should().NotThrow(); @@ -157,7 +159,7 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG [Fact] public void Should_throw_while_retrieving_using_Get_when_key_does_not_exist() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy policy = null; ReadOnlyRegistry.Invoking(r => policy = r.Get(key)) .Should().Throw(); @@ -166,7 +168,7 @@ public void Should_throw_while_retrieving_using_Get_when_key_does_not_exist() [Fact] public void Should_throw_while_retrieving_using_GetTResult_when_key_does_not_exist() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); Policy policy = null; ReadOnlyRegistry.Invoking(r => policy = r.Get>(key)) .Should().Throw(); @@ -175,7 +177,7 @@ public void Should_throw_while_retrieving_using_GetTResult_when_key_does_not_exi [Fact] public void Should_throw_while_retrieving_using_Get_by_interface_when_key_does_not_exist() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); ISyncPolicy policy = null; ReadOnlyRegistry.Invoking(r => policy = r.Get>(key)) .Should().Throw(); @@ -184,7 +186,7 @@ public void Should_throw_while_retrieving_using_Get_by_interface_when_key_does_n [Fact] public void Should_throw_while_retrieving_when_key_does_not_exist_using_Indexer() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); IsPolicy outPolicy = null; ReadOnlyRegistry.Invoking(r => outPolicy = r[key]) .Should().Throw(); @@ -234,12 +236,12 @@ public void Should_throw_when_retrieving_using_Indexer_when_key_is_null() public void Should_be_able_to_check_if_key_exists() { Policy policy = Policy.NoOp(); - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); ReadOnlyRegistry.ContainsKey(key).Should().BeTrue(); - var key2 = Guid.NewGuid().ToString(); + string key2 = Guid.NewGuid().ToString(); ReadOnlyRegistry.ContainsKey(key2).Should().BeFalse(); } @@ -251,7 +253,7 @@ public void Should_throw_when_checking_if_key_exists_when_key_is_null() .Should().Throw(); } #endregion - + #region Tests for the GetEnumerator method [Fact] @@ -272,7 +274,7 @@ public void Calling_The_GetEnumerator_Method_Returning_A_IEnumerator_Of_KeyValue [Fact] public void Policies_Should_Be_Added_To_The_Registry_When_Using_Collection_Initializer_Syntax() { - var key = Guid.NewGuid().ToString(); + string key = Guid.NewGuid().ToString(); var policy = Policy.NoOp(); var testRegistry = new PolicyRegistry @@ -280,7 +282,10 @@ public void Policies_Should_Be_Added_To_The_Registry_When_Using_Collection_Initi {key, policy} }; - testRegistry.Should().Equal(new KeyValuePair(key, policy)); + testRegistry.Should().Equal(new Dictionary + { + {key, policy} + }); } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/RetryAsyncSpecs.cs b/src/Polly.Specs/Retry/RetryAsyncSpecs.cs index da82c2364a8..0176d48661d 100644 --- a/src/Polly.Specs/Retry/RetryAsyncSpecs.cs +++ b/src/Polly.Specs/Retry/RetryAsyncSpecs.cs @@ -21,149 +21,149 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .RetryAsync(-1, onRetry); + .Handle() + .RetryAsync(-1, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] - public void Should_not_throw_when_specified_exception_thrown_same_number_of_times_as_retry_count() + public async Task Should_not_throw_when_specified_exception_thrown_same_number_of_times_as_retry_count() { var policy = Policy .Handle() .RetryAsync(3); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_number_of_times_as_retry_count() + public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_number_of_times_as_retry_count() { var policy = Policy .Handle() .Or() .RetryAsync(3); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_specified_exception_thrown_less_number_of_times_than_retry_count() + public async Task Should_not_throw_when_specified_exception_thrown_less_number_of_times_than_retry_count() { var policy = Policy .Handle() .RetryAsync(3); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_number_of_times_than_retry_count() + public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_number_of_times_than_retry_count() { var policy = Policy .Handle() .Or() .RetryAsync(3); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] - public void Should_throw_when_specified_exception_thrown_more_times_then_retry_count() + public async Task Should_throw_when_specified_exception_thrown_more_times_then_retry_count() { var policy = Policy .Handle() .RetryAsync(3); - policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_times_then_retry_count() + public async Task Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_times_then_retry_count() { var policy = Policy .Handle() .Or() .RetryAsync(3); - policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type() + public async Task Should_throw_when_exception_thrown_is_not_the_specified_exception_type() { var policy = Policy .Handle() .RetryAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() + public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() { var policy = Policy .Handle() .Or() .RetryAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_specified_exception_predicate_is_not_satisfied() + public async Task Should_throw_when_specified_exception_predicate_is_not_satisfied() { var policy = Policy .Handle(_ => false) .RetryAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle(_ => false) .Or(_ => false) .RetryAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_not_throw_when_specified_exception_predicate_is_satisfied() + public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied() { var policy = Policy .Handle(_ => true) .RetryAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle(_ => true) .Or(_ => true) .RetryAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] @@ -179,13 +179,13 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_retry_count await policy.RaiseExceptionAsync(3); retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + .ContainInOrder(expectedRetryCounts); } [Fact] public async Task Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] { "Exception #1", "Exception #2", "Exception #3" }; + var expectedExceptions = new string[] { "Exception #1", "Exception #2", "Exception #3" }; var retryExceptions = new List(); var policy = Policy @@ -218,7 +218,7 @@ public async Task Should_call_onretry_with_a_handled_innerexception() } [Fact] - public void Should_not_call_onretry_when_no_retries_are_performed() + public async Task Should_not_call_onretry_when_no_retries_are_performed() { var retryCounts = new List(); @@ -226,25 +226,25 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .Handle() .RetryAsync((_, retryCount) => retryCounts.Add(retryCount)); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); retryCounts.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] - public void Should_create_new_state_for_each_call_to_policy() + public async Task Should_create_new_state_for_each_call_to_policy() { var policy = Policy .Handle() .RetryAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] @@ -258,7 +258,7 @@ public void Should_call_onretry_with_the_passed_context() policy.RaiseExceptionAsync( new { key1 = "value1", key2 = "value2" }.AsDictionary() - ); + ); contextData.Should() .ContainKeys("key1", "key2").And @@ -266,7 +266,7 @@ public void Should_call_onretry_with_the_passed_context() } [Fact] - public void Should_call_onretry_with_the_passed_context_when_execute_and_capture() + public async Task Should_call_onretry_with_the_passed_context_when_execute_and_capture() { IDictionary contextData = null; @@ -274,9 +274,9 @@ public void Should_call_onretry_with_the_passed_context_when_execute_and_capture .Handle() .RetryAsync((_, _, context) => contextData = context); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => { throw new DivideByZeroException(); }, - new { key1 = "value1", key2 = "value2" }.AsDictionary())) - .Should().NotThrow(); + await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => { throw new DivideByZeroException(); }, + new { key1 = "value1", key2 = "value2" }.AsDictionary())) + .Should().NotThrowAsync(); contextData.Should() .ContainKeys("key1", "key2").And @@ -284,7 +284,7 @@ public void Should_call_onretry_with_the_passed_context_when_execute_and_capture } [Fact] - public void Context_should_be_empty_if_execute_not_called_with_any_data() + public async Task Context_should_be_empty_if_execute_not_called_with_any_data() { Context capturedContext = null; @@ -292,10 +292,10 @@ public void Context_should_be_empty_if_execute_not_called_with_any_data() .Handle() .RetryAsync((_, _, context) => capturedContext = context); - policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); capturedContext.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -321,7 +321,7 @@ public void Should_create_new_context_for_each_call_to_execute() } [Fact] - public void Should_create_new_context_for_each_call_to_execute_and_capture() + public async Task Should_create_new_context_for_each_call_to_execute_and_capture() { string contextValue = null; @@ -329,23 +329,23 @@ public void Should_create_new_context_for_each_call_to_execute_and_capture() .Handle() .RetryAsync((_, _, context) => contextValue = context["key"].ToString()); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new DivideByZeroException(), - new { key = "original_value" }.AsDictionary())) - .Should().NotThrow(); + await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new DivideByZeroException(), + new { key = "original_value" }.AsDictionary())) + .Should().NotThrowAsync(); contextValue.Should().Be("original_value"); - policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new DivideByZeroException(), - new { key = "new_value" }.AsDictionary())) - .Should().NotThrow(); + await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new DivideByZeroException(), + new { key = "new_value" }.AsDictionary())) + .Should().NotThrowAsync(); contextValue.Should().Be("new_value"); } [Fact] - public void Should_not_call_onretry_when_retry_count_is_zero() + public async Task Should_not_call_onretry_when_retry_count_is_zero() { - var retryInvoked = false; + bool retryInvoked = false; Action onRetry = (_, _) => { retryInvoked = true; }; @@ -353,8 +353,8 @@ public void Should_not_call_onretry_when_retry_count_is_zero() .Handle() .RetryAsync(0, onRetry); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); retryInvoked.Should().BeFalse(); } @@ -362,17 +362,17 @@ public void Should_not_call_onretry_when_retry_count_is_zero() #region Async and cancellation tests [Fact] - public void Should_wait_asynchronously_for_async_onretry_delegate() + public async Task Should_wait_asynchronously_for_async_onretry_delegate() { // This test relates to https://github.com/App-vNext/Polly/issues/107. // An async (...) => { ... } anonymous delegate with no return type may compile to either an async void or an async Task method; which assign to an Action<...> or Func<..., Task> respectively. However, if it compiles to async void (assigning to Action<...>), then the delegate, when run, will return at the first await, and execution continues without waiting for the Action to complete, as described by Stephen Toub: http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' of the retry policy would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - var shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var executeDelegateInvocations = 0; - var executeDelegateInvocationsWhenOnRetryExits = 0; + int executeDelegateInvocations = 0; + int executeDelegateInvocationsWhenOnRetryExits = 0; var policy = Policy .Handle() @@ -382,12 +382,12 @@ public void Should_wait_asynchronously_for_async_onretry_delegate() executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; }); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; throw new DivideByZeroException(); - })).Should().Throw(); + })).Should().ThrowAsync(); while (executeDelegateInvocationsWhenOnRetryExits == 0) { } // Wait for the onRetry delegate to complete. @@ -396,69 +396,69 @@ public void Should_wait_asynchronously_for_async_onretry_delegate() } [Fact] - public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_not_cancelled() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -466,206 +466,206 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_report_faulting_from_faulting_last_retry_execution_when_user_delegate_does_not_observe_cancellation_raised_during_last_retry() + public async Task Should_report_faulting_from_faulting_last_retry_execution_when_user_delegate_does_not_observe_cancellation_raised_during_last_retry() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() + public async Task Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy .Handle() @@ -674,47 +674,47 @@ public void Should_report_cancellation_after_faulting_action_execution_and_cance cancellationTokenSource.Cancel(); }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() + public async Task Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action) - .Should().NotThrow(); + await policy.Awaiting(action) + .Should().NotThrowAsync(); result.Should().BeTrue(); @@ -722,21 +722,21 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance } [Fact] - public void Should_honour_and_report_cancellation_during_func_execution() + public async Task Should_honour_and_report_cancellation_during_func_execution() { var policy = Policy .Handle() .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -744,8 +744,8 @@ public void Should_honour_and_report_cancellation_during_func_execution() }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(action).Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); result.Should().Be(null); @@ -753,4 +753,4 @@ public void Should_honour_and_report_cancellation_during_func_execution() } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs b/src/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs index 36244e7dee1..13f067b8483 100644 --- a/src/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs +++ b/src/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs @@ -16,101 +16,101 @@ namespace Polly.Specs.Retry; public class RetryForeverAsyncSpecs { [Fact] - public void Should_not_throw_regardless_of_how_many_times_the_specified_exception_is_raised() + public async Task Should_not_throw_regardless_of_how_many_times_the_specified_exception_is_raised() { var policy = Policy .Handle() .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_regardless_of_how_many_times_one_of_the_specified_exception_is_raised() + public async Task Should_not_throw_regardless_of_how_many_times_one_of_the_specified_exception_is_raised() { var policy = Policy .Handle() .Or() .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type() + public async Task Should_throw_when_exception_thrown_is_not_the_specified_exception_type() { var policy = Policy .Handle() .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() + public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() { var policy = Policy .Handle() .Or() .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_specified_exception_predicate_is_not_satisfied() + public async Task Should_throw_when_specified_exception_predicate_is_not_satisfied() { var policy = Policy .Handle(_ => false) .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle(_ => false) .Or(_ => false) .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_not_throw_when_specified_exception_predicate_is_satisfied() + public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied() { var policy = Policy .Handle(_ => true) .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle(_ => true) .Or(_ => true) .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] public async Task Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] {"Exception #1", "Exception #2", "Exception #3"}; + var expectedExceptions = new string[] {"Exception #1", "Exception #2", "Exception #3"}; var retryExceptions = new List(); var policy = Policy @@ -139,8 +139,8 @@ public void Should_call_onretry_on_each_retry_with_the_passed_context() ); contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + .ContainKeys("key1", "key2").And + .ContainValues("value1", "value2"); } [Fact] @@ -160,7 +160,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() } [Fact] - public void Context_should_be_empty_if_execute_not_called_with_any_data() + public async Task Context_should_be_empty_if_execute_not_called_with_any_data() { Context capturedContext = null; @@ -168,10 +168,10 @@ public void Context_should_be_empty_if_execute_not_called_with_any_data() .Handle() .RetryForeverAsync((_, context) => capturedContext = context); - policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); capturedContext.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -197,7 +197,7 @@ public void Should_create_new_context_for_each_call_to_execute() } [Fact] - public void Should_not_call_onretry_when_no_retries_are_performed() + public async Task Should_not_call_onretry_when_no_retries_are_performed() { var retryExceptions = new List(); @@ -205,25 +205,25 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .Handle() .RetryForeverAsync(exception => retryExceptions.Add(exception)); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); retryExceptions.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] - public void Should_wait_asynchronously_for_async_onretry_delegate() + public async Task Should_wait_asynchronously_for_async_onretry_delegate() { // This test relates to https://github.com/App-vNext/Polly/issues/107. // An async (...) => { ... } anonymous delegate with no return type may compile to either an async void or an async Task method; which assign to an Action<...> or Func<..., Task> respectively. However, if it compiles to async void (assigning tp Action<...>), then the delegate, when run, will return at the first await, and execution continues without waiting for the Action to complete, as described by Stephen Toub: http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - var shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var executeDelegateInvocations = 0; - var executeDelegateInvocationsWhenOnRetryExits = 0; + int executeDelegateInvocations = 0; + int executeDelegateInvocationsWhenOnRetryExits = 0; var policy = Policy .Handle() @@ -233,12 +233,12 @@ public void Should_wait_asynchronously_for_async_onretry_delegate() executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; }); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; if (executeDelegateInvocations == 1) { throw new DivideByZeroException(); } - })).Should().NotThrow(); + })).Should().NotThrowAsync(); while (executeDelegateInvocationsWhenOnRetryExits == 0) { } // Wait for the onRetry delegate to complete. @@ -247,44 +247,44 @@ public void Should_wait_asynchronously_for_async_onretry_delegate() } [Fact] - public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -292,203 +292,203 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() + public async Task Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy .Handle() .RetryForeverAsync( - _ => - { - cancellationTokenSource.Cancel(); - }); + _ => + { + cancellationTokenSource.Cancel(); + }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() + public async Task Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action) - .Should().NotThrow(); + await policy.Awaiting(action) + .Should().NotThrowAsync(); result.Should().BeTrue(); @@ -496,21 +496,21 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance } [Fact] - public void Should_honour_and_report_cancellation_during_func_execution() + public async Task Should_honour_and_report_cancellation_during_func_execution() { var policy = Policy .Handle() .RetryForeverAsync(); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -518,12 +518,12 @@ public void Should_honour_and_report_cancellation_during_func_execution() }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(action).Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); result.Should().Be(null); attemptsInvoked.Should().Be(1); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/RetryForeverSpecs.cs b/src/Polly.Specs/Retry/RetryForeverSpecs.cs index 9dc83a3d7d0..cdbb7aede9a 100644 --- a/src/Polly.Specs/Retry/RetryForeverSpecs.cs +++ b/src/Polly.Specs/Retry/RetryForeverSpecs.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using FluentAssertions; using Polly.Specs.Helpers; using Xunit; @@ -15,11 +16,11 @@ public void Should_throw_when_onretry_action_without_context_is_null() Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .RetryForever(nullOnRetry); + .Handle() + .RetryForever(nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -28,11 +29,11 @@ public void Should_throw_when_onretry_action_with_context_is_null() Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .RetryForever(nullOnRetry); + .Handle() + .RetryForever(nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -43,7 +44,7 @@ public void Should_not_throw_regardless_of_how_many_times_the_specified_exceptio .RetryForever(); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -55,7 +56,7 @@ public void Should_not_throw_regardless_of_how_many_times_one_of_the_specified_e .RetryForever(); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -66,18 +67,18 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty .RetryForever(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type_async() + public async Task Should_throw_when_exception_thrown_is_not_the_specified_exception_type_async() { var policy = Policy .Handle() .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] @@ -89,7 +90,7 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .RetryForever(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -100,7 +101,7 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .RetryForever(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -112,7 +113,7 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .RetryForever(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -123,18 +124,18 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() .RetryForever(); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] - public void Should_not_throw_when_specified_exception_predicate_is_satisfied_async() + public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied_async() { var policy = Policy .Handle(_ => true) .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] @@ -146,25 +147,25 @@ public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_ .RetryForever(); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied_async() + public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied_async() { var policy = Policy .Handle(_ => true) .Or(_ => true) .RetryForeverAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] public void Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] {"Exception #1", "Exception #2", "Exception #3"}; + var expectedExceptions = new string[] {"Exception #1", "Exception #2", "Exception #3"}; var retryExceptions = new List(); var policy = Policy @@ -193,8 +194,8 @@ public void Should_call_onretry_on_each_retry_with_the_passed_context() ); contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + .ContainKeys("key1", "key2").And + .ContainValues("value1", "value2"); } [Fact] @@ -223,10 +224,10 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .RetryForever(exception => retryExceptions.Add(exception)); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryExceptions.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -250,4 +251,4 @@ public void Should_create_new_context_for_each_call_to_execute() contextValue.Should().Be("new_value"); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/RetrySpecs.cs b/src/Polly.Specs/Retry/RetrySpecs.cs index 243e4b8091c..e2ac616708d 100644 --- a/src/Polly.Specs/Retry/RetrySpecs.cs +++ b/src/Polly.Specs/Retry/RetrySpecs.cs @@ -16,11 +16,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .Retry(-1, onRetry); - + .Handle() + .Retry(-1, onRetry); + policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -29,11 +29,11 @@ public void Should_throw_when_onretry_action_without_context_is_null() Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .Retry(1, nullOnRetry); + .Handle() + .Retry(1, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -42,11 +42,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() Action onRetry = (_, _, _) => { }; Action policy = () => Policy - .Handle() - .Retry(-1, onRetry); + .Handle() + .Retry(-1, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -55,11 +55,11 @@ public void Should_throw_when_onretry_action_with_context_is_null() Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .Retry(1, nullOnRetry); + .Handle() + .Retry(1, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -70,7 +70,7 @@ public void Should_not_throw_when_specified_exception_thrown_same_number_of_time .Retry(3); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -82,7 +82,7 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_nu .Retry(3); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -93,9 +93,9 @@ public void Should_not_throw_when_specified_exception_thrown_less_number_of_time .Retry(3); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } - + [Fact] public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_number_of_times_than_retry_count() { @@ -105,9 +105,9 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_nu .Retry(3); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } - + [Fact] public void Should_throw_when_specified_exception_thrown_more_times_then_retry_count() { @@ -116,9 +116,9 @@ public void Should_throw_when_specified_exception_thrown_more_times_then_retry_c .Retry(3); policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + .Should().Throw(); } - + [Fact] public void Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_times_then_retry_count() { @@ -128,9 +128,9 @@ public void Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_ti .Retry(3); policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + .Should().Throw(); } - + [Fact] public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type() { @@ -139,7 +139,7 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty .Retry(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -151,7 +151,7 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .Retry(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -162,7 +162,7 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .Retry(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -174,7 +174,7 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .Retry(); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -185,7 +185,7 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() .Retry(); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -197,7 +197,7 @@ public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_ .Retry(); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -213,13 +213,13 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() policy.RaiseException(3); retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + .ContainInOrder(expectedRetryCounts); } [Fact] public void Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] { "Exception #1", "Exception #2", "Exception #3" }; + var expectedExceptions = new string[] { "Exception #1", "Exception #2", "Exception #3" }; var retryExceptions = new List(); var policy = Policy @@ -366,7 +366,7 @@ public void Should_call_onretry_with_the_passed_context() policy.RaiseException( new { key1 = "value1", key2 = "value2" }.AsDictionary() - ); + ); contextData.Should() .ContainKeys("key1", "key2").And @@ -383,7 +383,7 @@ public void Should_call_onretry_with_the_passed_context_when_execute_and_capture .Retry((_, _, context) => contextData = context); policy.Invoking(p => p.ExecuteAndCapture(_ => { throw new DivideByZeroException();}, - new { key1 = "value1", key2 = "value2" }.AsDictionary())) + new { key1 = "value1", key2 = "value2" }.AsDictionary())) .Should().NotThrow(); contextData.Should() @@ -403,7 +403,7 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( policy.RaiseException(); capturedContext.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -438,13 +438,13 @@ public void Should_create_new_context_for_each_call_to_execute_and_capture() .Retry((_, _, context) => contextValue = context["key"].ToString()); policy.Invoking(p => p.ExecuteAndCapture(_ => throw new DivideByZeroException(), - new { key = "original_value" }.AsDictionary())) + new { key = "original_value" }.AsDictionary())) .Should().NotThrow(); contextValue.Should().Be("original_value"); policy.Invoking(p => p.ExecuteAndCapture(_ => throw new DivideByZeroException(), - new { key = "new_value" }.AsDictionary())) + new { key = "new_value" }.AsDictionary())) .Should().NotThrow(); contextValue.Should().Be("new_value"); @@ -467,7 +467,7 @@ public void Should_create_new_state_for_each_call_to_policy() [Fact] public void Should_not_call_onretry_when_retry_count_is_zero_without_context() { - var retryInvoked = false; + bool retryInvoked = false; Action onRetry = (_, _) => { retryInvoked = true; }; @@ -476,7 +476,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() .Retry(0, onRetry); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryInvoked.Should().BeFalse(); } @@ -484,7 +484,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() [Fact] public void Should_not_call_onretry_when_retry_count_is_zero_with_context() { - var retryInvoked = false; + bool retryInvoked = false; Action onRetry = (_, _, _) => { retryInvoked = true; }; @@ -493,7 +493,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_context() .Retry(0, onRetry); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryInvoked.Should().BeFalse(); } @@ -508,13 +508,13 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, @@ -533,13 +533,13 @@ public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_can .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, @@ -558,13 +558,13 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -586,13 +586,13 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -613,13 +613,13 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, @@ -640,13 +640,13 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, @@ -667,13 +667,13 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, @@ -694,13 +694,13 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, @@ -721,13 +721,13 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, @@ -748,13 +748,13 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, @@ -770,8 +770,8 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ [Fact] public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy .Handle() @@ -780,10 +780,10 @@ public void Should_report_cancellation_after_faulting_action_execution_and_cance cancellationTokenSource.Cancel(); }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. @@ -804,15 +804,15 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, @@ -833,15 +833,15 @@ public void Should_honour_and_report_cancellation_during_func_execution() .Handle() .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -859,4 +859,4 @@ public void Should_honour_and_report_cancellation_during_func_execution() #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs b/src/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs index c21859145cd..4ecd5afba40 100644 --- a/src/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs +++ b/src/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs @@ -13,7 +13,7 @@ public void Should_handle_exception_when_TResult_policy_handling_exceptions_only Policy policy = Policy .Handle().Retry(1); - var result = policy.RaiseResultAndOrExceptionSequence(new DivideByZeroException(), ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(new DivideByZeroException(), ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -35,7 +35,7 @@ public void Should_handle_both_exception_and_specified_result_if_raised_same_num .Or() .Retry(2); - var result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -47,7 +47,7 @@ public void Should_handle_both_exception_and_specified_result_if_raised_same_num .OrResult(ResultPrimitive.Fault) .Retry(2); - var result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -61,7 +61,7 @@ public void Should_handle_both_exceptions_and_specified_results_if_raised_same_n .OrResult(ResultPrimitive.FaultAgain) .Retry(4); - var result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -75,7 +75,7 @@ public void Should_handle_both_exceptions_and_specified_results_if_raised_same_n .Or() .Retry(4); - var result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -89,7 +89,7 @@ public void Should_return_handled_result_when_handled_result_returned_next_after .Or() .Retry(3); - var result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultAgain); } @@ -117,7 +117,7 @@ public void Should_return_handled_result_when_handled_result_returned_next_after .OrResult(ResultPrimitive.FaultAgain) .Retry(3); - var result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultAgain); } @@ -143,7 +143,7 @@ public void Should_return_unhandled_result_if_not_one_of_results_or_exceptions_s .Or() .Retry(2); - var result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain); result.Should().Be(ResultPrimitive.FaultAgain); } @@ -167,7 +167,7 @@ public void Should_handle_both_exceptions_and_specified_results_with_predicates( .OrResult(r => r.ResultCode == ResultPrimitive.Fault) .Retry(2); - var result = policy.RaiseResultAndOrExceptionSequence(new ResultClass(ResultPrimitive.Fault), new ArgumentException("message","key"), new ResultClass(ResultPrimitive.Good)); + ResultClass result = policy.RaiseResultAndOrExceptionSequence(new ResultClass(ResultPrimitive.Fault), new ArgumentException("message","key"), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.Good); } @@ -191,7 +191,7 @@ public void Should_return_unhandled_result_if_result_predicate_not_matched() .OrResult(r => r.ResultCode == ResultPrimitive.Fault) .Retry(2); - var result = policy.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "key"), new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); + ResultClass result = policy.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "key"), new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.FaultAgain); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/RetryTResultSpecs.cs b/src/Polly.Specs/Retry/RetryTResultSpecs.cs index 695f961efe5..b51cb3ca968 100644 --- a/src/Polly.Specs/Retry/RetryTResultSpecs.cs +++ b/src/Polly.Specs/Retry/RetryTResultSpecs.cs @@ -19,11 +19,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() Action, int> onRetry = (_, _) => { }; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(-1, onRetry); + .HandleResult(ResultPrimitive.Fault) + .Retry(-1, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -32,11 +32,11 @@ public void Should_throw_when_onretry_action_without_context_is_null() Action, int> nullOnRetry = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(1, nullOnRetry); + .HandleResult(ResultPrimitive.Fault) + .Retry(1, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -45,11 +45,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() Action, int, Context> onRetry = (_, _, _) => { }; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(-1, onRetry); + .HandleResult(ResultPrimitive.Fault) + .Retry(-1, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -58,102 +58,102 @@ public void Should_throw_when_onretry_action_with_context_is_null() Action, int, Context> nullOnRetry = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(1, nullOnRetry); + .HandleResult(ResultPrimitive.Fault) + .Retry(1, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] public void Should_not_return_handled_result_when_handled_result_raised_same_number_of_times_as_retry_count() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(3); - var result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } [Fact] public void Should_not_return_handled_result_when_one_of_the_handled_results_raised_same_number_of_times_as_retry_count() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Retry(3); - var result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } [Fact] public void Should_not_return_handled_result_when_handled_result_raised_less_number_of_times_than_retry_count() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(3); - var result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } [Fact] public void Should_not_return_handled_result_when_all_of_the_handled_results_raised_less_number_of_times_than_retry_count() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Retry(3); - var result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } [Fact] public void Should_return_handled_result_when_handled_result_raised_more_times_then_retry_count() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(3); - var result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Fault); // It should give up retrying after 3 retries and return the last failure, so should return Fault, not Good. } [Fact] public void Should_return_handled_result_when_one_of_the_handled_results_is_raised_more_times_then_retry_count() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Retry(3); - var result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultAgain); } [Fact] public void Should_return_result_when_result_is_not_the_specified_handled_result() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(); - var result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultAgain); } [Fact] public void Should_return_result_when_result_is_not_one_of_the_specified_handled_results() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .OrResult(ResultPrimitive.FaultAgain) .Retry(); - var result = policy.RaiseResultSequence(ResultPrimitive.FaultYetAgain, ResultPrimitive.Good); + ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultYetAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultYetAgain); } @@ -164,7 +164,7 @@ public void Should_return_result_when_specified_result_predicate_is_not_satisfie .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .Retry(); - var result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); + ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.FaultAgain); } @@ -176,7 +176,7 @@ public void Should_return_result_when_none_of_the_specified_result_predicates_ar .OrResult(r => r.ResultCode == ResultPrimitive.FaultAgain) .Retry(); - var result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultYetAgain), new ResultClass(ResultPrimitive.Good)); + ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultYetAgain), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.FaultYetAgain); } @@ -187,7 +187,7 @@ public void Should_not_return_handled_result_when_specified_result_predicate_is_ .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .Retry(); - var result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault), new ResultClass(ResultPrimitive.Good)); + ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.Good); } @@ -199,7 +199,7 @@ public void Should_not_return_handled_result_when_one_of_the_specified_result_pr .OrResult(r => r.ResultCode == ResultPrimitive.FaultAgain) .Retry(); - var result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); + ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.Good); } @@ -209,14 +209,14 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() var expectedRetryCounts = new[] { 1, 2, 3 }; var retryCounts = new List(); - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(3, (_, retryCount) => retryCounts.Add(retryCount)); policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + .ContainInOrder(expectedRetryCounts); } [Fact] @@ -244,7 +244,7 @@ public void Should_not_call_onretry_when_no_retries_are_performed() { var retryCounts = new List(); - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry((_, retryCount) => retryCounts.Add(retryCount)); @@ -259,13 +259,13 @@ public void Should_call_onretry_with_the_passed_context() { IDictionary contextData = null; - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry((_, _, context) => contextData = context); policy.RaiseResultSequence( - new { key1 = "value1", key2 = "value2" }.AsDictionary(), - ResultPrimitive.Fault, ResultPrimitive.Good + new { key1 = "value1", key2 = "value2" }.AsDictionary(), + ResultPrimitive.Fault, ResultPrimitive.Good ) .Should().Be(ResultPrimitive.Good); @@ -279,14 +279,14 @@ public void Should_call_onretry_with_the_passed_context_when_execute_and_capture { IDictionary contextData = null; - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry((_, _, context) => contextData = context); - var result = policy.RaiseResultSequenceOnExecuteAndCapture( + PolicyResult result = policy.RaiseResultSequenceOnExecuteAndCapture( new { key1 = "value1", key2 = "value2" }.AsDictionary(), ResultPrimitive.Fault, ResultPrimitive.Good - ); + ); result.Should().BeEquivalentTo(new { @@ -308,14 +308,14 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( { Context capturedContext = null; - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry((_, _, context) => capturedContext = context); policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); capturedContext.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -323,7 +323,7 @@ public void Should_create_new_context_for_each_call_to_execute() { string contextValue = null; - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry((_, _, context) => contextValue = context["key"].ToString()); @@ -347,7 +347,7 @@ public void Should_create_new_context_for_each_call_to_execute_and_capture() { string contextValue = null; - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry((_, _, context) => contextValue = context["key"].ToString()); @@ -369,7 +369,7 @@ public void Should_create_new_context_for_each_call_to_execute_and_capture() [Fact] public void Should_create_new_state_for_each_call_to_policy() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(1); @@ -382,11 +382,11 @@ public void Should_create_new_state_for_each_call_to_policy() [Fact] public void Should_not_call_onretry_when_retry_count_is_zero_without_context() { - var retryInvoked = false; + bool retryInvoked = false; Action, int> onRetry = (_, _) => { retryInvoked = true; }; - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(0, onRetry); @@ -398,16 +398,16 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() [Fact] public void Should_not_call_onretry_when_retry_count_is_zero_with_context() { - var retryInvoked = false; + bool retryInvoked = false; Action, int, Context> onRetry = (_, _, _) => { retryInvoked = true; }; - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(0, onRetry); policy.RaiseResultSequence( - new { key = "value" }.AsDictionary(), + new { key = "value" }.AsDictionary(), ResultPrimitive.Fault, ResultPrimitive.Good).Should().Be(ResultPrimitive.Fault); retryInvoked.Should().BeFalse(); @@ -422,13 +422,13 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca .HandleResult(ResultPrimitive.Fault) .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; @@ -442,17 +442,17 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca [Fact] public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_cancelled() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; @@ -462,7 +462,7 @@ public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_can ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .Should().Be(ResultPrimitive.Good); attemptsInvoked.Should().Be(1 + 3); } @@ -470,17 +470,17 @@ public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_can [Fact] public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. }; @@ -488,10 +488,10 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -501,27 +501,27 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex [Fact] public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { - var policy = Policy + RetryPolicy policy = Policy .HandleResult(ResultPrimitive.Fault) .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good)) + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -531,27 +531,27 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec [Fact] public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { - var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(3); + RetryPolicy policy = Policy + .HandleResult(ResultPrimitive.Fault) + .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -561,27 +561,27 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ [Fact] public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { - var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(3); + RetryPolicy policy = Policy + .HandleResult(ResultPrimitive.Fault) + .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -591,27 +591,27 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ [Fact] public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { - var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(3); + RetryPolicy policy = Policy + .HandleResult(ResultPrimitive.Fault) + .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 2, ActionObservesCancellation = true }; policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -621,27 +621,27 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ [Fact] public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { - var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(3); + RetryPolicy policy = Policy + .HandleResult(ResultPrimitive.Fault) + .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 2, ActionObservesCancellation = false }; policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -651,28 +651,28 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ [Fact] public void Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken() { - var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(3); + RetryPolicy policy = Policy + .HandleResult(ResultPrimitive.Fault) + .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = true }; policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -682,29 +682,29 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when [Fact] public void Should_report_faulting_from_faulting_last_retry_execution_when_user_delegate_does_not_observe_cancellation_raised_during_last_retry() { - var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(3); + RetryPolicy policy = Policy + .HandleResult(ResultPrimitive.Fault) + .Retry(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = false }; policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Fault); + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good) + .Should().Be(ResultPrimitive.Fault); attemptsInvoked.Should().Be(1 + 3); } @@ -712,30 +712,30 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ [Fact] public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .Retry(3, (_, _) => - { - cancellationTokenSource.Cancel(); - }); + RetryPolicy policy = Policy + .HandleResult(ResultPrimitive.Fault) + .Retry(3, (_, _) => + { + cancellationTokenSource.Cancel(); + }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. ActionObservesCancellation = false }; policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) .Should().Throw() .And.CancellationToken.Should().Be(cancellationToken); @@ -744,4 +744,4 @@ public void Should_report_cancellation_after_faulting_action_execution_and_cance #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/RetryTResultSpecsAsync.cs b/src/Polly.Specs/Retry/RetryTResultSpecsAsync.cs index c4a1ce83017..d937e3e694a 100644 --- a/src/Polly.Specs/Retry/RetryTResultSpecsAsync.cs +++ b/src/Polly.Specs/Retry/RetryTResultSpecsAsync.cs @@ -20,11 +20,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() Action, int> onRetry = (_, _) => { }; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(-1, onRetry); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(-1, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -33,11 +33,11 @@ public void Should_throw_when_onretry_action_without_context_is_null() Action, int> nullOnRetry = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(1, nullOnRetry); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(1, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -46,11 +46,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() Action, int, Context> onRetry = (_, _, _) => { }; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(-1, onRetry); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(-1, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -59,11 +59,11 @@ public void Should_throw_when_onretry_action_with_context_is_null() Action, int, Context> nullOnRetry = null; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(1, nullOnRetry); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(1, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -73,7 +73,7 @@ public async Task Should_not_return_handled_result_when_handled_result_raised_sa .HandleResult(ResultPrimitive.Fault) .RetryAsync(3); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -85,7 +85,7 @@ public async Task Should_not_return_handled_result_when_one_of_the_handled_resul .OrResult(ResultPrimitive.FaultAgain) .RetryAsync(3); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -96,7 +96,7 @@ public async Task Should_not_return_handled_result_when_handled_result_raised_le .HandleResult(ResultPrimitive.Fault) .RetryAsync(3); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -108,7 +108,7 @@ public async Task Should_not_return_handled_result_when_all_of_the_handled_resul .OrResult(ResultPrimitive.FaultAgain) .RetryAsync(3); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Good); } @@ -119,7 +119,7 @@ public async Task Should_return_handled_result_when_handled_result_raised_more_t .HandleResult(ResultPrimitive.Fault) .RetryAsync(3); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.Fault); // It should give up retrying after 3 retries and return the last failure, so should return Fault, not Good. } @@ -131,7 +131,7 @@ public async Task Should_return_handled_result_when_one_of_the_handled_results_i .OrResult(ResultPrimitive.FaultAgain) .RetryAsync(3); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultAgain); } @@ -142,7 +142,7 @@ public async Task Should_return_result_when_result_is_not_the_specified_handled_ .HandleResult(ResultPrimitive.Fault) .RetryAsync(); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultAgain); } @@ -154,7 +154,7 @@ public async Task Should_return_result_when_result_is_not_one_of_the_specified_h .OrResult(ResultPrimitive.FaultAgain) .RetryAsync(); - var result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultYetAgain, ResultPrimitive.Good); + ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultYetAgain, ResultPrimitive.Good); result.Should().Be(ResultPrimitive.FaultYetAgain); } @@ -165,7 +165,7 @@ public async Task Should_return_result_when_specified_result_predicate_is_not_sa .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .RetryAsync(); - var result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); + ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.FaultAgain); } @@ -177,7 +177,7 @@ public async Task Should_return_result_when_none_of_the_specified_result_predica .OrResult(r => r.ResultCode == ResultPrimitive.FaultAgain) .RetryAsync(); - var result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultYetAgain), new ResultClass(ResultPrimitive.Good)); + ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultYetAgain), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.FaultYetAgain); } @@ -188,7 +188,7 @@ public async Task Should_not_return_handled_result_when_specified_result_predica .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .RetryAsync(); - var result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault), new ResultClass(ResultPrimitive.Good)); + ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.Good); } @@ -200,7 +200,7 @@ public async Task Should_not_return_handled_result_when_one_of_the_specified_res .OrResult(r => r.ResultCode == ResultPrimitive.FaultAgain) .RetryAsync(); - var result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); + ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); result.ResultCode.Should().Be(ResultPrimitive.Good); } @@ -218,7 +218,7 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_retry_count .Should().Be(ResultPrimitive.Good); retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + .ContainInOrder(expectedRetryCounts); } [Fact] @@ -268,8 +268,8 @@ public async Task Should_call_onretry_with_the_passed_context() .RetryAsync((_, _, context) => contextData = context); (await policy.RaiseResultSequenceAsync( - new { key1 = "value1", key2 = "value2" }.AsDictionary(), - ResultPrimitive.Fault, ResultPrimitive.Good + new { key1 = "value1", key2 = "value2" }.AsDictionary(), + ResultPrimitive.Fault, ResultPrimitive.Good )) .Should().Be(ResultPrimitive.Good); @@ -287,10 +287,10 @@ public async Task Should_call_onretry_with_the_passed_context_when_execute_and_c .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, context) => contextData = context); - var result = await policy.RaiseResultSequenceOnExecuteAndCaptureAsync( + PolicyResult result = await policy.RaiseResultSequenceOnExecuteAndCaptureAsync( new { key1 = "value1", key2 = "value2" }.AsDictionary(), ResultPrimitive.Fault, ResultPrimitive.Good - ); + ); result.Should().BeEquivalentTo(new { @@ -319,7 +319,7 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); capturedContext.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -386,7 +386,7 @@ public async Task Should_create_new_state_for_each_call_to_policy() [Fact] public async Task Should_not_call_onretry_when_retry_count_is_zero_without_context() { - var retryInvoked = false; + bool retryInvoked = false; Action, int> onRetry = (_, _) => { retryInvoked = true; }; @@ -402,7 +402,7 @@ public async Task Should_not_call_onretry_when_retry_count_is_zero_without_conte [Fact] public async Task Should_not_call_onretry_when_retry_count_is_zero_with_context() { - var retryInvoked = false; + bool retryInvoked = false; Action, int, Context> onRetry = (_, _, _) => { retryInvoked = true; }; @@ -411,7 +411,7 @@ public async Task Should_not_call_onretry_when_retry_count_is_zero_with_context( .RetryAsync(0, onRetry); (await policy.RaiseResultSequenceAsync( - new { key = "value" }.AsDictionary(), + new { key = "value" }.AsDictionary(), ResultPrimitive.Fault, ResultPrimitive.Good)).Should().Be(ResultPrimitive.Fault); retryInvoked.Should().BeFalse(); @@ -427,10 +427,10 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - var shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var executeDelegateInvocations = 0; - var executeDelegateInvocationsWhenOnRetryExits = 0; + int executeDelegateInvocations = 0; + int executeDelegateInvocationsWhenOnRetryExits = 0; var policy = Policy .HandleResult(ResultPrimitive.Fault) @@ -460,13 +460,13 @@ public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_n .HandleResult(ResultPrimitive.Fault) .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, }; @@ -476,219 +476,219 @@ public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_n ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .Should().Be(ResultPrimitive.Good); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var policy = Policy .HandleResult(ResultPrimitive.Fault) .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. }; cancellationTokenSource.Cancel(); - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .HandleResult(ResultPrimitive.Fault) .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(3); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(3); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(3); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 2, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(3); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 2, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken() { var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(3); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1 + 3); } @@ -697,64 +697,64 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when public async Task Should_report_faulting_from_faulting_last_retry_execution_when_user_delegate_does_not_observe_cancellation_raised_during_last_retry() { var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(3); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(3); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = false }; (await policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Fault); + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().Be(ResultPrimitive.Fault); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() + public async Task Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy - .HandleResult(ResultPrimitive.Fault) - .RetryAsync(3, (_, _) => - { - cancellationTokenSource.Cancel(); - }); + .HandleResult(ResultPrimitive.Fault) + .RetryAsync(3, (_, _) => + { + cancellationTokenSource.Cancel(); + }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } - + #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs b/src/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs index 1f8fa3d0ca6..596e0c378da 100644 --- a/src/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs @@ -30,11 +30,11 @@ public void Should_throw_when_sleep_durations_is_null_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(null, onRetry); + .Handle() + .WaitAndRetryAsync(null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + .ParamName.Should().Be("sleepDurations"); } [Fact] @@ -43,185 +43,185 @@ public void Should_throw_when_onretry_action_is_null_without_context() Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(Enumerable.Empty(), nullOnRetry); + .Handle() + .WaitAndRetryAsync(Enumerable.Empty(), nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] - public void Should_not_throw_when_specified_exception_thrown_same_number_of_times_as_there_are_sleep_durations() + public async Task Should_not_throw_when_specified_exception_thrown_same_number_of_times_as_there_are_sleep_durations() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_number_of_times_as_there_are_sleep_durations() + public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_number_of_times_as_there_are_sleep_durations() { var policy = Policy .Handle() .Or() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_specified_exception_thrown_less_number_of_times_than_there_are_sleep_durations() + public async Task Should_not_throw_when_specified_exception_thrown_less_number_of_times_than_there_are_sleep_durations() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(2)) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_number_of_times_than_there_are_sleep_durations() + public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_number_of_times_than_there_are_sleep_durations() { var policy = Policy .Handle() .Or() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(2)) + .Should().NotThrowAsync(); } [Fact] - public void Should_throw_when_specified_exception_thrown_more_times_than_there_are_sleep_durations() + public async Task Should_throw_when_specified_exception_thrown_more_times_than_there_are_sleep_durations() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_times_than_there_are_sleep_durations() + public async Task Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_times_than_there_are_sleep_durations() { var policy = Policy .Handle() .Or() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type() + public async Task Should_throw_when_exception_thrown_is_not_the_specified_exception_type() { var policy = Policy .Handle() .WaitAndRetryAsync(Enumerable.Empty()); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() + public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() { var policy = Policy .Handle() .Or() .WaitAndRetryAsync(Enumerable.Empty()); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_specified_exception_predicate_is_not_satisfied() + public async Task Should_throw_when_specified_exception_predicate_is_not_satisfied() { var policy = Policy .Handle(_ => false) .WaitAndRetryAsync(Enumerable.Empty()); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle(_ => false) .Or(_ => false) .WaitAndRetryAsync(Enumerable.Empty()); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_not_throw_when_specified_exception_predicate_is_satisfied() + public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied() { var policy = Policy .Handle(_ => true) .WaitAndRetryAsync(new[] { - 1.Seconds() + 1.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle(_ => true) .Or(_ => true) - .WaitAndRetryAsync(new[] + .WaitAndRetryAsync(new[] { - 1.Seconds() + 1.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] @@ -233,9 +233,9 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); SystemClock.SleepAsync = (span, _) => @@ -247,11 +247,11 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif await policy.RaiseExceptionAsync(3); totalTimeSlept.Should() - .Be(1 + 2 + 3); + .Be(1 + 2 + 3); } [Fact] - public void Should_sleep_for_the_specified_duration_each_retry_when_specified_exception_thrown_more_number_of_times_than_there_are_sleep_durations() + public async Task Should_sleep_for_the_specified_duration_each_retry_when_specified_exception_thrown_more_number_of_times_than_there_are_sleep_durations() { var totalTimeSlept = 0; @@ -259,9 +259,9 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); SystemClock.SleepAsync = (span, _) => @@ -270,11 +270,11 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex return TaskHelper.EmptyTask; }; - policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) + .Should().ThrowAsync(); totalTimeSlept.Should() - .Be(1 + 2 + 3); + .Be(1 + 2 + 3); } [Fact] @@ -286,9 +286,9 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); SystemClock.SleepAsync = (span, _) => @@ -300,11 +300,11 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif await policy.RaiseExceptionAsync(2); totalTimeSlept.Should() - .Be(1 + 2); + .Be(1 + 2); } [Fact] - public void Should_not_sleep_if_no_retries() + public async Task Should_not_sleep_if_no_retries() { var totalTimeSlept = 0; @@ -318,22 +318,22 @@ public void Should_not_sleep_if_no_retries() return TaskHelper.EmptyTask; }; - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); totalTimeSlept.Should() - .Be(0); + .Be(0); } [Fact] public async Task Should_call_onretry_on_each_retry_with_the_current_timespan() { var expectedRetryWaits = new [] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }; + { + 1.Seconds(), + 2.Seconds(), + 3.Seconds() + }; var actualRetryWaits = new List(); @@ -341,30 +341,30 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_timespan() .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }, (_, timeSpan) => actualRetryWaits.Add(timeSpan)); await policy.RaiseExceptionAsync(3); actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + .ContainInOrder(expectedRetryWaits); } [Fact] public async Task Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] { "Exception #1", "Exception #2", "Exception #3" }; + var expectedExceptions = new string[] { "Exception #1", "Exception #2", "Exception #3" }; var retryExceptions = new List(); var policy = Policy .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }, (exception, _) => retryExceptions.Add(exception)); await policy.RaiseExceptionAsync(3, (e, i) => e.HelpLink = "Exception #" + i); @@ -385,19 +385,19 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_retry_count .Handle() .WaitAndRetryAsync(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }, (_, _, retryCount, _) => retryCounts.Add(retryCount)); await policy.RaiseExceptionAsync(3); retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + .ContainInOrder(expectedRetryCounts); } [Fact] - public void Should_not_call_onretry_when_no_retries_are_performed() + public async Task Should_not_call_onretry_when_no_retries_are_performed() { var retryExceptions = new List(); @@ -405,14 +405,14 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .Handle() .WaitAndRetryAsync(Enumerable.Empty(), (exception, _) => retryExceptions.Add(exception)); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); retryExceptions.Should().BeEmpty(); } [Fact] - public void Should_create_new_state_for_each_call_to_policy() + public async Task Should_create_new_state_for_each_call_to_policy() { var policy = Policy .Handle() @@ -421,11 +421,11 @@ public void Should_create_new_state_for_each_call_to_policy() 1.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] @@ -444,7 +444,7 @@ public async Task Should_call_onretry_with_the_passed_context() await policy.RaiseExceptionAsync( new { key1 = "value1", key2 = "value2" }.AsDictionary() - ); + ); contextData.Should() .ContainKeys("key1", "key2").And @@ -452,7 +452,7 @@ await policy.RaiseExceptionAsync( } [Fact] - public void Context_should_be_empty_if_execute_not_called_with_any_data() + public async Task Context_should_be_empty_if_execute_not_called_with_any_data() { Context capturedContext = null; @@ -464,10 +464,10 @@ public void Context_should_be_empty_if_execute_not_called_with_any_data() 2.Seconds(), 3.Seconds() }, (_, _, context) => capturedContext = context); - policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); capturedContext.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -478,10 +478,10 @@ public async Task Should_create_new_context_for_each_call_to_execute() var policy = Policy .Handle() .WaitAndRetryAsync(new[] - { - 1.Seconds() - }, - (_, _, context) => contextValue = context["key"].ToString()); + { + 1.Seconds() + }, + (_, _, context) => contextValue = context["key"].ToString()); await policy.RaiseExceptionAsync( new { key = "original_value" }.AsDictionary() @@ -502,11 +502,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(-1, _ => TimeSpan.Zero, onRetry); + .Handle() + .WaitAndRetryAsync(-1, _ => TimeSpan.Zero, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -515,11 +515,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(1, null, onRetry); + .Handle() + .WaitAndRetryAsync(1, null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -528,24 +528,24 @@ public void Should_throw_when_onretry_action_is_null_without_context_when_using_ Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(1, _ => TimeSpan.Zero, nullOnRetry); + .Handle() + .WaitAndRetryAsync(1, _ => TimeSpan.Zero, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] public async Task Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + 2.Seconds(), + 4.Seconds(), + 8.Seconds(), + 16.Seconds(), + 32.Seconds() + }; var actualRetryWaits = new List(); @@ -559,7 +559,7 @@ public async Task Should_calculate_retry_timespans_from_current_retry_attempt_an await policy.RaiseExceptionAsync(5); actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + .ContainInOrder(expectedRetryWaits); } [Fact] @@ -567,7 +567,7 @@ public async Task Should_be_able_to_pass_handled_exception_to_sleepdurationprovi { object capturedExceptionInstance = null; - var exceptionInstance = new DivideByZeroException(); + DivideByZeroException exceptionInstance = new DivideByZeroException(); var policy = Policy .Handle() @@ -587,7 +587,7 @@ public async Task Should_be_able_to_pass_handled_exception_to_sleepdurationprovi [Fact] public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {new DivideByZeroException(), 2.Seconds()}, {new ArgumentNullException(), 4.Seconds()}, @@ -622,7 +622,7 @@ public async Task Should_be_able_to_pass_retry_duration_from_execution_to_sleepD var expectedRetryDuration = 1.Seconds(); TimeSpan? actualRetryDuration = null; - var defaultRetryAfter = 30.Seconds(); + TimeSpan defaultRetryAfter = 30.Seconds(); var policy = Policy .Handle() @@ -631,29 +631,29 @@ public async Task Should_be_able_to_pass_retry_duration_from_execution_to_sleepD onRetry: (_, timeSpan, _) => actualRetryDuration = timeSpan // Capture the actual sleep duration that was used, for test verification purposes. ); - var failedOnce = false; + bool failedOnce = false; await policy.ExecuteAsync(async (context, _) => - { - await TaskHelper.EmptyTask; // Run some remote call; maybe it returns a RetryAfter header, which we can pass back to the sleepDurationProvider, via the context. - context["RetryAfter"] = expectedRetryDuration; + { + await TaskHelper.EmptyTask; // Run some remote call; maybe it returns a RetryAfter header, which we can pass back to the sleepDurationProvider, via the context. + context["RetryAfter"] = expectedRetryDuration; - if (!failedOnce) - { - failedOnce = true; - throw new DivideByZeroException(); - } - }, + if (!failedOnce) + { + failedOnce = true; + throw new DivideByZeroException(); + } + }, new { RetryAfter = defaultRetryAfter }.AsDictionary(), // Can also set an initial value for RetryAfter, in the Context passed into the call. CancellationToken.None - ); + ); actualRetryDuration.Should().Be(expectedRetryDuration); } [Fact] - public void Should_not_call_onretry_when_retry_count_is_zero() + public async Task Should_not_call_onretry_when_retry_count_is_zero() { - var retryInvoked = false; + bool retryInvoked = false; Action onRetry = (_, _) => { retryInvoked = true; }; @@ -661,41 +661,41 @@ public void Should_not_call_onretry_when_retry_count_is_zero() .Handle() .WaitAndRetryAsync(0, _ => TimeSpan.FromSeconds(1), onRetry); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); retryInvoked.Should().BeFalse(); } [Fact] - public void Should_wait_asynchronously_for_async_onretry_delegate() + public async Task Should_wait_asynchronously_for_async_onretry_delegate() { // This test relates to https://github.com/App-vNext/Polly/issues/107. // An async (...) => { ... } anonymous delegate with no return type may compile to either an async void or an async Task method; which assign to an Action<...> or Func<..., Task> respectively. However, if it compiles to async void (assigning tp Action<...>), then the delegate, when run, will return at the first await, and execution continues without waiting for the Action to complete, as described by Stephen Toub: http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - var shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var executeDelegateInvocations = 0; - var executeDelegateInvocationsWhenOnRetryExits = 0; + int executeDelegateInvocations = 0; + int executeDelegateInvocationsWhenOnRetryExits = 0; var policy = Policy .Handle() .WaitAndRetryAsync(1, - _ => TimeSpan.Zero, - async (_, _) => - { - await Task.Delay(shimTimeSpan); - executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; - }); + _ => TimeSpan.Zero, + async (_, _) => + { + await Task.Delay(shimTimeSpan); + executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; + }); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; throw new DivideByZeroException(); - })).Should().Throw(); + })).Should().ThrowAsync(); while (executeDelegateInvocationsWhenOnRetryExits == 0) { } // Wait for the onRetry delegate to complete. @@ -704,69 +704,69 @@ public void Should_wait_asynchronously_for_async_onretry_delegate() } [Fact] - public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_not_cancelled() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -774,223 +774,223 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_last_retry_execution_when_user_delegate_does_observe_cancellationToken() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_report_faulting_from_faulting_last_retry_execution_when_user_delegate_does_not_observe_cancellation_raised_during_last_retry() + public async Task Should_report_faulting_from_faulting_last_retry_execution_when_user_delegate_does_not_observe_cancellation_raised_during_last_retry() { var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); attemptsInvoked.Should().Be(1 + 3); } [Fact] - public void Should_honour_cancellation_immediately_during_wait_phase_of_waitandretry() + public async Task Should_honour_cancellation_immediately_during_wait_phase_of_waitandretry() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; SystemClock.SleepAsync = Task.Delay; - var shimTimeSpan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var retryDelay = shimTimeSpan + shimTimeSpan + shimTimeSpan; + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan retryDelay = shimTimeSpan + shimTimeSpan + shimTimeSpan; var policy = Policy .Handle() .WaitAndRetryAsync(new[] { retryDelay }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); watch.Start(); - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 1, AttemptDuringWhichToCancel = null, // Cancellation invoked after delay - see below. @@ -999,72 +999,72 @@ public void Should_honour_cancellation_immediately_during_wait_phase_of_waitandr cancellationTokenSource.CancelAfter(shimTimeSpan); - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); watch.Stop(); attemptsInvoked.Should().Be(1); watch.Elapsed.Should().BeLessThan(retryDelay); - watch.Elapsed.Should().BeCloseTo(shimTimeSpan, precision: (int)(shimTimeSpan.TotalMilliseconds) / 2); // Consider increasing shimTimeSpan, or loosening precision, if test fails transiently in different environments. + watch.Elapsed.Should().BeCloseTo(shimTimeSpan, precision: TimeSpan.FromMilliseconds((int)shimTimeSpan.TotalMilliseconds / 2)); // Consider increasing shimTimeSpan, or loosening precision, if test fails transiently in different environments. } [Fact] - public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() + public async Task Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy .Handle() .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }, - (_, _) => - { - cancellationTokenSource.Cancel(); - }); + (_, _) => + { + cancellationTokenSource.Cancel(); + }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() + public async Task Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var policy = Policy - .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .Handle() + .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action) - .Should().NotThrow(); + await policy.Awaiting(action) + .Should().NotThrowAsync(); result.Should().BeTrue(); @@ -1072,21 +1072,21 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance } [Fact] - public void Should_honour_and_report_cancellation_during_func_execution() + public async Task Should_honour_and_report_cancellation_during_func_execution() { var policy = Policy - .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .Handle() + .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1094,8 +1094,8 @@ public void Should_honour_and_report_cancellation_during_func_execution() }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(action).Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); result.Should().Be(null); @@ -1106,4 +1106,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs b/src/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs index ec1f60caada..4b3f19b8f39 100644 --- a/src/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs @@ -29,11 +29,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryForeverAsync(null, onRetry); + .Handle() + .WaitAndRetryForeverAsync(null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -42,11 +42,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_context() Action onRetry = (_, _, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryForeverAsync(null, onRetry); + .Handle() + .WaitAndRetryForeverAsync(null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -56,11 +56,11 @@ public void Should_throw_when_onretry_action_is_null_without_context() Func provider = _ => TimeSpan.Zero; Action policy = () => Policy - .Handle() - .WaitAndRetryForeverAsync(provider, nullOnRetry); + .Handle() + .WaitAndRetryForeverAsync(provider, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -70,38 +70,38 @@ public void Should_throw_when_onretry_action_is_null_with_context() Func provider = (_, _) => TimeSpan.Zero; Action policy = () => Policy - .Handle() - .WaitAndRetryForeverAsync(provider, nullOnRetry); + .Handle() + .WaitAndRetryForeverAsync(provider, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] - public void Should_not_throw_regardless_of_how_many_times_the_specified_exception_is_raised() + public async Task Should_not_throw_regardless_of_how_many_times_the_specified_exception_is_raised() { var policy = Policy .Handle() .WaitAndRetryForeverAsync(_ => TimeSpan.Zero); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_regardless_of_how_many_times_one_of_the_specified_exception_is_raised() + public async Task Should_not_throw_regardless_of_how_many_times_one_of_the_specified_exception_is_raised() { var policy = Policy .Handle() .Or() .WaitAndRetryForeverAsync(_ => TimeSpan.Zero); - policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync(3)) + .Should().NotThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type() + public async Task Should_throw_when_exception_thrown_is_not_the_specified_exception_type() { Func provider = _ => TimeSpan.Zero; @@ -109,12 +109,12 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty .Handle() .WaitAndRetryForeverAsync(provider); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() + public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() { Func provider = _ => TimeSpan.Zero; @@ -123,12 +123,12 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .Or() .WaitAndRetryForeverAsync(provider); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_specified_exception_predicate_is_not_satisfied() + public async Task Should_throw_when_specified_exception_predicate_is_not_satisfied() { Func provider = _ => TimeSpan.Zero; @@ -136,12 +136,12 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .Handle(_ => false) .WaitAndRetryForeverAsync(provider); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() { Func provider = _ => TimeSpan.Zero; @@ -150,12 +150,12 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .Or(_ => false) .WaitAndRetryForeverAsync(provider); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] - public void Should_not_throw_when_specified_exception_predicate_is_satisfied() + public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied() { Func provider = _ => 1.Seconds(); @@ -163,26 +163,26 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() .Handle(_ => true) .WaitAndRetryForeverAsync(provider); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() + public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { Func provider = _ => 1.Seconds(); var policy = Policy .Handle(_ => true) .Or(_ => true) - .WaitAndRetryForeverAsync(provider); + .WaitAndRetryForeverAsync(provider); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] - public void Should_not_sleep_if_no_retries() + public async Task Should_not_sleep_if_no_retries() { Func provider = _ => 1.Seconds(); @@ -194,17 +194,17 @@ public void Should_not_sleep_if_no_retries() SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); totalTimeSlept.Should() - .Be(0); + .Be(0); } [Fact] public async Task Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] { "Exception #1", "Exception #2", "Exception #3" }; + var expectedExceptions = new string[] { "Exception #1", "Exception #2", "Exception #3" }; var retryExceptions = new List(); Func provider = _ => TimeSpan.Zero; @@ -238,7 +238,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() } [Fact] - public void Should_not_call_onretry_when_no_retries_are_performed() + public async Task Should_not_call_onretry_when_no_retries_are_performed() { Func provider = _ => 1.Seconds(); var retryExceptions = new List(); @@ -247,8 +247,8 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .Handle() .WaitAndRetryForeverAsync(provider, (exception, _) => retryExceptions.Add(exception)); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); retryExceptions.Should().BeEmpty(); } @@ -263,8 +263,8 @@ public void Should_create_new_context_for_each_call_to_policy() var policy = Policy .Handle() .WaitAndRetryForeverAsync( - provider, - (_, _, context) => contextValue = context["key"].ToString()); + provider, + (_, _, context) => contextValue = context["key"].ToString()); policy.RaiseExceptionAsync( new { key = "original_value" }.AsDictionary() @@ -283,13 +283,13 @@ public void Should_create_new_context_for_each_call_to_policy() public async Task Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + 2.Seconds(), + 4.Seconds(), + 8.Seconds(), + 16.Seconds(), + 32.Seconds() + }; var actualRetryWaits = new List(); @@ -303,13 +303,13 @@ public async Task Should_calculate_retry_timespans_from_current_retry_attempt_an await policy.RaiseExceptionAsync(5); actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + .ContainInOrder(expectedRetryWaits); } [Fact] public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {new DivideByZeroException(), 2.Seconds()}, {new ArgumentNullException(), 4.Seconds()}, @@ -345,7 +345,7 @@ public async Task Should_be_able_to_pass_retry_duration_from_execution_to_sleepD var expectedRetryDuration = 1.Seconds(); TimeSpan? actualRetryDuration = null; - var defaultRetryAfter = 30.Seconds(); + TimeSpan defaultRetryAfter = 30.Seconds(); var policy = Policy .Handle() @@ -354,54 +354,54 @@ public async Task Should_be_able_to_pass_retry_duration_from_execution_to_sleepD onRetry: (_, timeSpan, _) => actualRetryDuration = timeSpan // Capture the actual sleep duration that was used, for test verification purposes. ); - var failedOnce = false; + bool failedOnce = false; await policy.ExecuteAsync(async (context, _) => - { - await TaskHelper.EmptyTask; // Run some remote call; maybe it returns a RetryAfter header, which we can pass back to the sleepDurationProvider, via the context. - context["RetryAfter"] = expectedRetryDuration; + { + await TaskHelper.EmptyTask; // Run some remote call; maybe it returns a RetryAfter header, which we can pass back to the sleepDurationProvider, via the context. + context["RetryAfter"] = expectedRetryDuration; - if (!failedOnce) - { - failedOnce = true; - throw new DivideByZeroException(); - } - }, + if (!failedOnce) + { + failedOnce = true; + throw new DivideByZeroException(); + } + }, new { RetryAfter = defaultRetryAfter }.AsDictionary(), // Can also set an initial value for RetryAfter, in the Context passed into the call. CancellationToken.None - ); + ); actualRetryDuration.Should().Be(expectedRetryDuration); } [Fact] - public void Should_wait_asynchronously_for_async_onretry_delegate() + public async Task Should_wait_asynchronously_for_async_onretry_delegate() { // This test relates to https://github.com/App-vNext/Polly/issues/107. // An async (...) => { ... } anonymous delegate with no return type may compile to either an async void or an async Task method; which assign to an Action<...> or Func<..., Task> respectively. However, if it compiles to async void (assigning tp Action<...>), then the delegate, when run, will return at the first await, and execution continues without waiting for the Action to complete, as described by Stephen Toub: http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - var shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var executeDelegateInvocations = 0; - var executeDelegateInvocationsWhenOnRetryExits = 0; + int executeDelegateInvocations = 0; + int executeDelegateInvocationsWhenOnRetryExits = 0; var policy = Policy .Handle() .WaitAndRetryForeverAsync( - _ => TimeSpan.Zero, - async (_, _) => - { - await Task.Delay(shimTimeSpan); - executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; - }); + _ => TimeSpan.Zero, + async (_, _) => + { + await Task.Delay(shimTimeSpan); + executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; + }); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; if (executeDelegateInvocations == 1) { throw new DivideByZeroException(); } - })).Should().NotThrow(); + })).Should().NotThrowAsync(); while (executeDelegateInvocationsWhenOnRetryExits == 0) { } // Wait for the onRetry delegate to complete. @@ -410,7 +410,7 @@ public void Should_wait_asynchronously_for_async_onretry_delegate() } [Fact] - public void Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() + public async Task Should_execute_action_when_non_faulting_and_cancellationToken_not_cancelled() { Func provider = _ => TimeSpan.Zero; @@ -418,25 +418,25 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().NotThrowAsync(); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_not_execute_action_when_cancellationToken_cancelled_before_execute() + public async Task Should_not_execute_action_when_cancellationToken_cancelled_before_execute() { Func provider = _ => TimeSpan.Zero; @@ -444,13 +444,13 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -458,15 +458,15 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(0); } [Fact] - public void Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_otherwise_non_faulting_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { Func provider = _ => TimeSpan.Zero; @@ -474,28 +474,28 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { Func provider = _ => TimeSpan.Zero; @@ -503,28 +503,28 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_initial_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { Func provider = _ => TimeSpan.Zero; @@ -532,28 +532,28 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_observes_cancellationToken() { Func provider = _ => TimeSpan.Zero; @@ -561,28 +561,28 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = true }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() + public async Task Should_report_cancellation_during_faulting_retried_action_execution_and_cancel_further_retries_when_user_delegate_does_not_observe_cancellationToken() { Func provider = _ => TimeSpan.Zero; @@ -590,61 +590,61 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(2); } [Fact] - public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() + public async Task Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { Func provider = _ => TimeSpan.Zero; - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy .Handle() .WaitAndRetryForeverAsync(provider, - (_, _) => - { - cancellationTokenSource.Cancel(); - }); + (_, _) => + { + cancellationTokenSource.Cancel(); + }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. ActionObservesCancellation = false }; - policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) + .Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); attemptsInvoked.Should().Be(1); } [Fact] - public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() + public async Task Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { Func provider = _ => TimeSpan.Zero; @@ -652,21 +652,21 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance .Handle() .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null, }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action).Should().NotThrow(); + await policy.Awaiting(action).Should().NotThrowAsync(); result.Should().BeTrue(); @@ -674,23 +674,23 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance } [Fact] - public void Should_honour_and_report_cancellation_during_func_execution() + public async Task Should_honour_and_report_cancellation_during_func_execution() { Func provider = _ => TimeSpan.Zero; var policy = Policy .Handle() - .WaitAndRetryForeverAsync(provider); + .WaitAndRetryForeverAsync(provider); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new Scenario + Scenario scenario = new Scenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -698,8 +698,8 @@ public void Should_honour_and_report_cancellation_during_func_execution() }; Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - policy.Awaiting(action) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + var ex = await policy.Awaiting(action).Should().ThrowAsync(); + ex.And.CancellationToken.Should().Be(cancellationToken); result.Should().Be(null); @@ -710,4 +710,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs b/src/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs index 30daa2e2f2b..739e4c82d9c 100644 --- a/src/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs @@ -24,11 +24,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryForever(null, onRetry); + .Handle() + .WaitAndRetryForever(null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -39,11 +39,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_context() Func sleepDurationProvider = null; Action policy = () => Policy - .Handle() - .WaitAndRetryForever(sleepDurationProvider, onRetry); + .Handle() + .WaitAndRetryForever(sleepDurationProvider, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -53,11 +53,11 @@ public void Should_throw_when_onretry_action_is_null_without_context() Func provider = _ => TimeSpan.Zero; Action policy = () => Policy - .Handle() - .WaitAndRetryForever(provider, nullOnRetry); + .Handle() + .WaitAndRetryForever(provider, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -67,11 +67,11 @@ public void Should_throw_when_onretry_action_is_null_with_context() Func provider = (_, _) => TimeSpan.Zero; Action policy = () => Policy - .Handle() - .WaitAndRetryForever(provider, nullOnRetry); + .Handle() + .WaitAndRetryForever(provider, nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -82,7 +82,7 @@ public void Should_not_throw_regardless_of_how_many_times_the_specified_exceptio .WaitAndRetryForever(_ => new TimeSpan()); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -94,20 +94,20 @@ public void Should_not_throw_regardless_of_how_many_times_one_of_the_specified_e .WaitAndRetryForever(_ => new TimeSpan()); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type() { Func provider = _ => TimeSpan.Zero; - + var policy = Policy .Handle() .WaitAndRetryForever(provider); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -121,9 +121,9 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .WaitAndRetryForever(provider); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } - + [Fact] public void Should_throw_when_specified_exception_predicate_is_not_satisfied() { @@ -134,7 +134,7 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .WaitAndRetryForever(provider); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -148,7 +148,7 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .WaitAndRetryForever(provider); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -161,9 +161,9 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() .WaitAndRetryForever(provider); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } - + [Fact] public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { @@ -172,10 +172,10 @@ public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_ var policy = Policy .Handle(_ => true) .Or(_ => true) - .WaitAndRetryForever(provider); + .WaitAndRetryForever(provider); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -192,16 +192,16 @@ public void Should_not_sleep_if_no_retries() SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); totalTimeSlept.Should() - .Be(0); + .Be(0); } [Fact] public void Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] { "Exception #1", "Exception #2", "Exception #3" }; + var expectedExceptions = new string[] { "Exception #1", "Exception #2", "Exception #3" }; var retryExceptions = new List(); Func provider = _ => TimeSpan.Zero; @@ -245,7 +245,7 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .WaitAndRetryForever(provider, (exception, _) => retryExceptions.Add(exception)); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryExceptions.Should().BeEmpty(); } @@ -260,8 +260,8 @@ public void Should_create_new_context_for_each_call_to_policy() var policy = Policy .Handle() .WaitAndRetryForever( - provider, - (_, _, context) => contextValue = context["key"].ToString()); + provider, + (_, _, context) => contextValue = context["key"].ToString()); policy.RaiseException( new { key = "original_value" }.AsDictionary() @@ -280,13 +280,13 @@ public void Should_create_new_context_for_each_call_to_policy() public void Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + 2.Seconds(), + 4.Seconds(), + 8.Seconds(), + 16.Seconds(), + 32.Seconds() + }; var actualRetryWaits = new List(); @@ -300,13 +300,13 @@ public void Should_calculate_retry_timespans_from_current_retry_attempt_and_time policy.RaiseException(5); actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + .ContainInOrder(expectedRetryWaits); } [Fact] public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {new DivideByZeroException(), 2.Seconds()}, {new ArgumentNullException(), 4.Seconds()}, @@ -335,7 +335,7 @@ public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDuratio var expectedRetryDuration = 1.Seconds(); TimeSpan? actualRetryDuration = null; - var defaultRetryAfter = 30.Seconds(); + TimeSpan defaultRetryAfter = 30.Seconds(); var policy = Policy .Handle() @@ -344,7 +344,7 @@ public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDuratio onRetry: (_, timeSpan, _) => actualRetryDuration = timeSpan // Capture the actual sleep duration that was used, for test verification purposes. ); - var failedOnce = false; + bool failedOnce = false; policy.Execute(context => { // Run some remote call; maybe it returns a RetryAfter header, which we can pass back to the sleepDurationProvider, via the context. @@ -357,7 +357,7 @@ public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDuratio } }, new {RetryAfter = defaultRetryAfter}.AsDictionary() // Can also set an initial value for RetryAfter, in the Context passed into the call. - ); + ); actualRetryDuration.Should().Be(expectedRetryDuration); } @@ -366,4 +366,4 @@ public void Dispose() { SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs b/src/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs index bf02728026f..461b7b1cc2b 100644 --- a/src/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs @@ -21,7 +21,7 @@ public WaitAndRetryForeverTResultAsyncSpecs() [Fact] public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {ResultPrimitive.Fault, 2.Seconds()}, {ResultPrimitive.FaultAgain, 4.Seconds()}, @@ -58,4 +58,4 @@ public void Dispose() SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs b/src/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs index 79822ef8a73..57507cc6927 100644 --- a/src/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs @@ -20,7 +20,7 @@ public WaitAndRetryForeverTResultSpecs() [Fact] public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {ResultPrimitive.Fault, 2.Seconds()}, {ResultPrimitive.FaultAgain, 4.Seconds()}, @@ -53,4 +53,4 @@ public void Dispose() SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetrySpecs.cs b/src/Polly.Specs/Retry/WaitAndRetrySpecs.cs index d451a1d3a13..7a9c169143c 100644 --- a/src/Polly.Specs/Retry/WaitAndRetrySpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetrySpecs.cs @@ -27,11 +27,11 @@ public void Should_throw_when_sleep_durations_is_null_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(null, onRetry); + .Handle() + .WaitAndRetry(null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + .ParamName.Should().Be("sleepDurations"); } [Fact] @@ -40,11 +40,11 @@ public void Should_throw_when_sleep_durations_is_null_with_context() Action onRetry = (_, _, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(null, onRetry); + .Handle() + .WaitAndRetry(null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + .ParamName.Should().Be("sleepDurations"); } [Fact] @@ -53,11 +53,11 @@ public void Should_throw_when_sleep_durations_is_null_with_attempts_with_context Action onRetry = (_, _, _, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(null, onRetry); + .Handle() + .WaitAndRetry(null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + .ParamName.Should().Be("sleepDurations"); } [Fact] @@ -66,11 +66,11 @@ public void Should_throw_when_onretry_action_is_null_without_context() Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetry(Enumerable.Empty(), nullOnRetry); + .Handle() + .WaitAndRetry(Enumerable.Empty(), nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -79,11 +79,11 @@ public void Should_throw_when_onretry_action_is_null_with_context() Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetry(Enumerable.Empty(), nullOnRetry); + .Handle() + .WaitAndRetry(Enumerable.Empty(), nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -92,11 +92,11 @@ public void Should_throw_when_onretry_action_is_null_with_attempts_with_context( Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetry(Enumerable.Empty(), nullOnRetry); + .Handle() + .WaitAndRetry(Enumerable.Empty(), nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -106,13 +106,13 @@ public void Should_not_throw_when_specified_exception_thrown_same_number_of_time .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -123,13 +123,13 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_nu .Or() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -139,13 +139,13 @@ public void Should_not_throw_when_specified_exception_thrown_less_number_of_time .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); policy.Invoking(x => x.RaiseException(2)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -156,13 +156,13 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_nu .Or() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); policy.Invoking(x => x.RaiseException(2)) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -172,13 +172,13 @@ public void Should_throw_when_specified_exception_thrown_more_times_than_there_a .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -189,13 +189,13 @@ public void Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_ti .Or() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -206,18 +206,18 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty .WaitAndRetry(Enumerable.Empty()); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type_async() + public async Task Should_throw_when_exception_thrown_is_not_the_specified_exception_type_async() { var policy = Policy .Handle() .WaitAndRetryAsync(Enumerable.Empty()); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] @@ -229,19 +229,19 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .WaitAndRetry(Enumerable.Empty()); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] - public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types_async() + public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types_async() { var policy = Policy .Handle() .Or() .WaitAndRetryAsync(Enumerable.Empty()); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().Throw(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().ThrowAsync(); } [Fact] @@ -252,7 +252,7 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .WaitAndRetry(Enumerable.Empty()); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -264,7 +264,7 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .WaitAndRetry(Enumerable.Empty()); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); } [Fact] @@ -274,25 +274,25 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() .Handle(_ => true) .WaitAndRetry(new[] { - 1.Seconds() + 1.Seconds() }); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] - public void Should_not_throw_when_specified_exception_predicate_is_satisfied_async() + public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied_async() { var policy = Policy .Handle(_ => true) .WaitAndRetryAsync(new[] { - 1.Seconds() + 1.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] @@ -303,26 +303,26 @@ public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_ .Or(_ => true) .WaitAndRetry(new[] { - 1.Seconds() + 1.Seconds() }); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] - public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied_async() + public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied_async() { var policy = Policy .Handle(_ => true) .Or(_ => true) .WaitAndRetryAsync(new[] { - 1.Seconds() + 1.Seconds() }); - policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrow(); + await policy.Awaiting(x => x.RaiseExceptionAsync()) + .Should().NotThrowAsync(); } [Fact] @@ -334,9 +334,9 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; @@ -344,7 +344,7 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex policy.RaiseException(3); totalTimeSlept.Should() - .Be(1 + 2 + 3); + .Be(1 + 2 + 3); } [Fact] @@ -356,18 +356,18 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + .Should().Throw(); totalTimeSlept.Should() - .Be(1 + 2 + 3); + .Be(1 + 2 + 3); } [Fact] @@ -379,9 +379,9 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }); SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; @@ -389,7 +389,7 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex policy.RaiseException(2); totalTimeSlept.Should() - .Be(1 + 2); + .Be(1 + 2); } [Fact] @@ -404,21 +404,21 @@ public void Should_not_sleep_if_no_retries() SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); totalTimeSlept.Should() - .Be(0); + .Be(0); } [Fact] public void Should_call_onretry_on_each_retry_with_the_current_timespan() { var expectedRetryWaits = new [] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }; + { + 1.Seconds(), + 2.Seconds(), + 3.Seconds() + }; var actualRetryWaits = new List(); @@ -426,30 +426,30 @@ public void Should_call_onretry_on_each_retry_with_the_current_timespan() .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }, (_, timeSpan) => actualRetryWaits.Add(timeSpan)); policy.RaiseException(3); actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + .ContainInOrder(expectedRetryWaits); } [Fact] public void Should_call_onretry_on_each_retry_with_the_current_exception() { - var expectedExceptions = new object[] { "Exception #1", "Exception #2", "Exception #3" }; + var expectedExceptions = new string[] { "Exception #1", "Exception #2", "Exception #3" }; var retryExceptions = new List(); var policy = Policy .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }, (exception, _) => retryExceptions.Add(exception)); policy.RaiseException(3, (e, i) => e.HelpLink = "Exception #" + i); @@ -470,15 +470,15 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() .Handle() .WaitAndRetry(new[] { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() + 1.Seconds(), + 2.Seconds(), + 3.Seconds() }, (_, _, retryCount, _) => retryCounts.Add(retryCount)); policy.RaiseException(3); retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + .ContainInOrder(expectedRetryCounts); } [Fact] @@ -491,10 +491,10 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .WaitAndRetry(Enumerable.Empty(), (exception, _) => retryExceptions.Add(exception)); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryExceptions.Should() - .BeEmpty(); + .BeEmpty(); } [Fact] @@ -508,10 +508,10 @@ public void Should_create_new_state_for_each_call_to_policy() }); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + .Should().NotThrow(); } [Fact] @@ -530,7 +530,7 @@ public void Should_call_onretry_with_the_passed_context() policy.RaiseException( new { key1 = "value1", key2 = "value2" }.AsDictionary() - ); + ); contextData.Should() .ContainKeys("key1", "key2").And @@ -545,10 +545,10 @@ public void Should_create_new_context_for_each_call_to_execute() var policy = Policy .Handle() .WaitAndRetry(new[] - { - 1.Seconds() - }, - (_, _, context) => contextValue = context["key"].ToString()); + { + 1.Seconds() + }, + (_, _, context) => contextValue = context["key"].ToString()); policy.RaiseException( new { key = "original_value" }.AsDictionary() @@ -569,11 +569,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(-1, _ => new TimeSpan(), onRetry); + .Handle() + .WaitAndRetry(-1, _ => new TimeSpan(), onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -582,11 +582,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() Action onRetry = (_, _, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(-1, _ => new TimeSpan(), onRetry); + .Handle() + .WaitAndRetry(-1, _ => new TimeSpan(), onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -595,11 +595,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_attempts_with_c Action onRetry = (_, _, _, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(-1, _ => new TimeSpan(), onRetry); + .Handle() + .WaitAndRetry(-1, _ => new TimeSpan(), onRetry); policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + .ParamName.Should().Be("retryCount"); } [Fact] @@ -608,11 +608,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(1, null, onRetry); + .Handle() + .WaitAndRetry(1, null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -621,11 +621,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_context() Action onRetry = (_, _, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(1, (Func) null, onRetry); + .Handle() + .WaitAndRetry(1, (Func) null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -634,11 +634,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_attempts_with Action onRetry = (_, _, _, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetry(1, (Func)null, onRetry); + .Handle() + .WaitAndRetry(1, (Func)null, onRetry); policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + .ParamName.Should().Be("sleepDurationProvider"); } [Fact] @@ -647,11 +647,11 @@ public void Should_throw_when_onretry_action_is_null_without_context_when_using_ Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetry(1, _ => new TimeSpan(), nullOnRetry); + .Handle() + .WaitAndRetry(1, _ => new TimeSpan(), nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -660,11 +660,11 @@ public void Should_throw_when_onretry_action_is_null_with_context_when_using_pro Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetry(1, _ => new TimeSpan(), nullOnRetry); + .Handle() + .WaitAndRetry(1, _ => new TimeSpan(), nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] @@ -673,24 +673,24 @@ public void Should_throw_when_onretry_action_is_null_with_attempts_with_context_ Action nullOnRetry = null; Action policy = () => Policy - .Handle() - .WaitAndRetry(1, _ => new TimeSpan(), nullOnRetry); + .Handle() + .WaitAndRetry(1, _ => new TimeSpan(), nullOnRetry); policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + .ParamName.Should().Be("onRetry"); } [Fact] public void Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + 2.Seconds(), + 4.Seconds(), + 8.Seconds(), + 16.Seconds(), + 32.Seconds() + }; var actualRetryWaits = new List(); @@ -704,7 +704,7 @@ public void Should_calculate_retry_timespans_from_current_retry_attempt_and_time policy.RaiseException(5); actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + .ContainInOrder(expectedRetryWaits); } [Fact] @@ -712,7 +712,7 @@ public void Should_be_able_to_pass_handled_exception_to_sleepdurationprovider() { object capturedExceptionInstance = null; - var exceptionInstance = new DivideByZeroException(); + DivideByZeroException exceptionInstance = new DivideByZeroException(); var policy = Policy .Handle() @@ -735,7 +735,7 @@ public void Should_be_able_to_pass_handled_exception_to_sleepdurationprovider() [Fact] public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {new DivideByZeroException(), 2.Seconds()}, {new ArgumentNullException(), 4.Seconds()}, @@ -764,7 +764,7 @@ public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDuratio var expectedRetryDuration = 1.Seconds(); TimeSpan? actualRetryDuration = null; - var defaultRetryAfter = 30.Seconds(); + TimeSpan defaultRetryAfter = 30.Seconds(); var policy = Policy .Handle() @@ -773,27 +773,27 @@ public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDuratio onRetry: (_, timeSpan, _) => actualRetryDuration = timeSpan // Capture the actual sleep duration that was used, for test verification purposes. ); - var failedOnce = false; + bool failedOnce = false; policy.Execute(context => - { - // Run some remote call; maybe it returns a RetryAfter header, which we can pass back to the sleepDurationProvider, via the context. - context["RetryAfter"] = expectedRetryDuration; + { + // Run some remote call; maybe it returns a RetryAfter header, which we can pass back to the sleepDurationProvider, via the context. + context["RetryAfter"] = expectedRetryDuration; - if (!failedOnce) - { - failedOnce = true; - throw new DivideByZeroException(); - } - }, + if (!failedOnce) + { + failedOnce = true; + throw new DivideByZeroException(); + } + }, new { RetryAfter = defaultRetryAfter }.AsDictionary() // Can also set an initial value for RetryAfter, in the Context passed into the call. - ); + ); actualRetryDuration.Should().Be(expectedRetryDuration); } [Fact] public void Should_not_call_onretry_when_retry_count_is_zero_without_context() { - var retryInvoked = false; + bool retryInvoked = false; Action onRetry = (_, _) => { retryInvoked = true; }; @@ -802,7 +802,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() .WaitAndRetry(0, _ => TimeSpan.FromSeconds(1), onRetry); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryInvoked.Should().BeFalse(); } @@ -810,7 +810,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() [Fact] public void Should_not_call_onretry_when_retry_count_is_zero_with_context() { - var retryInvoked = false; + bool retryInvoked = false; Action onRetry = (_, _, _) => { retryInvoked = true; }; @@ -819,7 +819,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_context() .WaitAndRetry(0, _ => TimeSpan.FromSeconds(1), onRetry); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryInvoked.Should().BeFalse(); } @@ -827,7 +827,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_context() [Fact] public void Should_not_call_onretry_when_retry_count_is_zero_with_attempts_with_context() { - var retryInvoked = false; + bool retryInvoked = false; Action onRetry = (_, _, _, _) => { retryInvoked = true; }; @@ -836,7 +836,7 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_attempts_with_ .WaitAndRetry(0, _ => TimeSpan.FromSeconds(1), onRetry); policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + .Should().Throw(); retryInvoked.Should().BeFalse(); } @@ -850,13 +850,13 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation token cancelled manually below - before any scenario execution. @@ -878,13 +878,13 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -905,13 +905,13 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, @@ -932,13 +932,13 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1, @@ -959,13 +959,13 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, @@ -986,13 +986,13 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 2, @@ -1013,13 +1013,13 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, @@ -1040,13 +1040,13 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = 1 + 3, @@ -1062,25 +1062,25 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ [Fact] public void Should_honour_cancellation_immediately_during_wait_phase_of_waitandretry() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; SystemClock.Sleep = (timeSpan, ct) => Task.Delay(timeSpan, ct).Wait(ct); - var shimTimeSpan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var retryDelay = shimTimeSpan + shimTimeSpan + shimTimeSpan; + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan retryDelay = shimTimeSpan + shimTimeSpan + shimTimeSpan; var policy = Policy .Handle() .WaitAndRetry(new[] { retryDelay }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); watch.Start(); - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 1, AttemptDuringWhichToCancel = null, // Cancellation invoked after delay - see below. @@ -1090,34 +1090,34 @@ public void Should_honour_cancellation_immediately_during_wait_phase_of_waitandr cancellationTokenSource.CancelAfter(shimTimeSpan); policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + .Should().Throw() + .And.CancellationToken.Should().Be(cancellationToken); watch.Stop(); attemptsInvoked.Should().Be(1); watch.Elapsed.Should().BeLessThan(retryDelay); - watch.Elapsed.Should().BeCloseTo(shimTimeSpan, precision: (int)(shimTimeSpan.TotalMilliseconds) / 2); // Consider increasing shimTimeSpan, or loosening precision, if test fails transiently in different environments. + watch.Elapsed.Should().BeCloseTo(shimTimeSpan, precision: TimeSpan.FromMilliseconds((int)shimTimeSpan.TotalMilliseconds / 2)); // Consider increasing shimTimeSpan, or loosening precision, if test fails transiently in different environments. } [Fact] public void Should_report_cancellation_after_faulting_action_execution_and_cancel_further_retries_if_onRetry_invokes_cancellation() { - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; var policy = Policy .Handle() .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }, - (_, _) => - { - cancellationTokenSource.Cancel(); - }); + (_, _) => + { + cancellationTokenSource.Cancel(); + }); - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 1 + 3, AttemptDuringWhichToCancel = null, // Cancellation during onRetry instead - see above. @@ -1135,18 +1135,18 @@ public void Should_report_cancellation_after_faulting_action_execution_and_cance public void Should_execute_func_returning_value_when_cancellationToken_not_cancelled() { var policy = Policy - .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .Handle() + .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = null @@ -1164,18 +1164,18 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance public void Should_honour_and_report_cancellation_during_func_execution() { var policy = Policy - .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .Handle() + .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = cancellationTokenSource.Token; - var attemptsInvoked = 0; + int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; bool? result = null; - var scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario + PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { NumberOfTimesToRaiseException = 0, AttemptDuringWhichToCancel = 1, @@ -1197,4 +1197,4 @@ public void Dispose() SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs b/src/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs index e187312e7fc..f14e70a44fc 100644 --- a/src/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs @@ -21,7 +21,7 @@ public WaitAndRetryTResultAsyncSpecs() [Fact] public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {ResultPrimitive.Fault, 2.Seconds()}, {ResultPrimitive.FaultAgain, 4.Seconds()}, @@ -58,4 +58,4 @@ public void Dispose() SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs b/src/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs index a1a1bfdf466..cb7dac2f693 100644 --- a/src/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs +++ b/src/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs @@ -20,7 +20,7 @@ public WaitAndRetryTResultSpecs() [Fact] public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fault() { - var expectedRetryWaits = new Dictionary(){ + Dictionary expectedRetryWaits = new Dictionary(){ {ResultPrimitive.Fault, 2.Seconds()}, {ResultPrimitive.FaultAgain, 4.Seconds()}, @@ -53,4 +53,4 @@ public void Dispose() SystemClock.Reset(); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs b/src/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs index e36c553d871..1525cc092e3 100644 --- a/src/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs +++ b/src/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs @@ -199,17 +199,17 @@ public void Should_be_able_to_configure_with_timeout_func() #region Timeout operation - pessimistic [Fact] - public void Should_throw_when_timeout_is_less_than_execution_duration__pessimistic() + public async Task Should_throw_when_timeout_is_less_than_execution_duration__pessimistic() { - var timeout = TimeSpan.FromMilliseconds(50); + TimeSpan timeout = TimeSpan.FromMilliseconds(50); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - })).Should().Throw(); + })).Should().ThrowAsync(); } [Fact] @@ -217,45 +217,45 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(1), TimeoutStrategy.Pessimistic); - var result = ResultPrimitive.Undefined; + ResultPrimitive result = ResultPrimitive.Undefined; - var act = async () => + Func act = async () => { result = await policy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); }; - act.Should().NotThrow(); + act.Should().NotThrowAsync(); result.Should().Be(ResultPrimitive.Good); } [Fact] - public void Should_throw_timeout_after_correct_duration__pessimistic() + public async Task Should_throw_timeout_after_correct_duration__pessimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), CancellationToken.None); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), CancellationToken.None); - })) - .Should().Throw(); + })) + .Should().ThrowAsync(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] - public void Should_rethrow_exception_from_inside_delegate__pessimistic() + public async Task Should_rethrow_exception_from_inside_delegate__pessimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic); - policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().ThrowAsync(); } #endregion @@ -264,19 +264,19 @@ public void Should_rethrow_exception_from_inside_delegate__pessimistic() #region Timeout operation - optimistic [Fact] - public void Should_throw_when_timeout_is_less_than_execution_duration__optimistic() + public async Task Should_throw_when_timeout_is_less_than_execution_duration__optimistic() { - var timeout = TimeSpan.FromMilliseconds(50); + TimeSpan timeout = TimeSpan.FromMilliseconds(50); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, userCancellationToken)) - .Should().Throw(); + }, userCancellationToken)) + .Should().ThrowAsync(); } [Fact] @@ -286,47 +286,46 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op var result = ResultPrimitive.Undefined; var userCancellationToken = CancellationToken.None; - var act = async () => { + Func act = async () => { result = await policy.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromMilliseconds(500), ct); - return ResultPrimitive.Good; - }, userCancellationToken); + { + await SystemClock.SleepAsync(TimeSpan.FromMilliseconds(500), ct); + return ResultPrimitive.Good; + }, userCancellationToken); }; - act.Should().NotThrow(); + act.Should().NotThrowAsync(); result.Should().Be(ResultPrimitive.Good); } [Fact] - public void Should_throw_timeout_after_correct_duration__optimistic() + public async Task Should_throw_timeout_after_correct_duration__optimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken.None; - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), ct); - - }, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), ct); + }, userCancellationToken)) + .Should().ThrowAsync(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] - public void Should_rethrow_exception_from_inside_delegate__optimistic() + public async Task Should_rethrow_exception_from_inside_delegate__optimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Optimistic); - policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().ThrowAsync(); } #endregion @@ -334,41 +333,41 @@ public void Should_rethrow_exception_from_inside_delegate__optimistic() #region Non-timeout cancellation - pessimistic (user-delegate does not observe cancellation) [Fact] - public void Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token_before_timeout__pessimistic() + public async Task Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token_before_timeout__pessimistic() { - var timeout = 5; + int timeout = 5; var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { - policy.Awaiting(p => p.ExecuteAsync(async - _ => { + await policy.Awaiting(p => p.ExecuteAsync(async + _ => { userTokenSource.Cancel(); // User token cancels in the middle of execution ... await SystemClock.SleepAsync(TimeSpan.FromSeconds(timeout * 2), CancellationToken.None // ... but if the executed delegate does not observe it - ); + ); }, userTokenSource.Token) - ).Should().Throw(); // ... it's still the timeout we expect. + ).Should().ThrowAsync(); // ... it's still the timeout we expect. } } [Fact] - public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__pessimistic() + public async Task Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__pessimistic() { var policy = Policy.TimeoutAsync(10, TimeoutStrategy.Pessimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); - policy.Awaiting(p => p.ExecuteAsync(_ => - { - executed = true; - return TaskHelper.EmptyTask; - }, cts.Token)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(_ => + { + executed = true; + return TaskHelper.EmptyTask; + }, cts.Token)) + .Should().ThrowAsync(); } executed.Should().BeFalse(); @@ -379,52 +378,52 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled #region Non-timeout cancellation - optimistic (user-delegate observes cancellation) [Fact] - public void Should_be_able_to_cancel_with_user_cancellation_token_before_timeout__optimistic() + public async Task Should_be_able_to_cancel_with_user_cancellation_token_before_timeout__optimistic() { - var timeout = 10; + int timeout = 10; var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { - policy.Awaiting(p => p.ExecuteAsync( - ct => { - userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution - return TaskHelper.EmptyTask; - }, userTokenSource.Token) // ... with user token. - ).Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync( + ct => { + userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution + return TaskHelper.EmptyTask; + }, userTokenSource.Token) // ... with user token. + ).Should().ThrowAsync(); } } [Fact] - public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__optimistic() + public async Task Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__optimistic() { var policy = Policy.TimeoutAsync(10, TimeoutStrategy.Optimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); - policy.Awaiting(p => p.ExecuteAsync(_ => - { - executed = true; - return TaskHelper.EmptyTask; - }, cts.Token)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(_ => + { + executed = true; + return TaskHelper.EmptyTask; + }, cts.Token)) + .Should().ThrowAsync(); } executed.Should().BeFalse(); } [Fact] - public void Should_not_mask_user_exception_if_user_exception_overlaps_with_timeout() + public async Task Should_not_mask_user_exception_if_user_exception_overlaps_with_timeout() { var userException = new Exception(); var shimTimeSpan = TimeSpan.FromSeconds(0.2); var policy = Policy.TimeoutAsync(shimTimeSpan, TimeoutStrategy.Optimistic); - var thrown = policy.Awaiting(p => p.ExecuteAsync(async _ => + var thrown = await policy.Awaiting(p => p.ExecuteAsync(async _ => { try { @@ -443,13 +442,12 @@ public void Should_not_mask_user_exception_if_user_exception_overlaps_with_timeo }, CancellationToken.None)) .Should() - .Throw() - .Which; + .ThrowAsync(); - thrown.Should().NotBeOfType(); - thrown.Should().NotBeOfType(); - thrown.Should().NotBeOfType(); - thrown.Should().BeSameAs(userException); + thrown.NotBeOfType(); + thrown.NotBeOfType(); + thrown.NotBeOfType(); + thrown.Which.Should().BeSameAs(userException); } #endregion @@ -457,9 +455,9 @@ public void Should_not_mask_user_exception_if_user_exception_overlaps_with_timeo #region onTimeout overload - pessimistic [Fact] - public void Should_call_ontimeout_with_configured_timeout__pessimistic() + public async Task Should_call_ontimeout_with_configured_timeout__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -470,21 +468,20 @@ public void Should_call_ontimeout_with_configured_timeout__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); + })) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); } [Fact] - public void Should_call_ontimeout_with_passed_context__pessimistic() + public async Task Should_call_ontimeout_with_passed_context__pessimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Func onTimeoutAsync = (ctx, _, _) => @@ -493,15 +490,14 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async _ => + await policy.Awaiting(p => p.ExecuteAsync(async _ => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - }, contextPassedToExecute)) - .Should().Throw(); + .Should().ThrowAsync(); contextPassedToOnTimeout.Should().NotBeNull(); contextPassedToOnTimeout.OperationKey.Should().Be(operationKey); @@ -512,9 +508,9 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -525,11 +521,11 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); + })) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); } @@ -538,7 +534,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__pessimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__pessimistic(int programaticallyControlledDelay) { Func timeoutProvider = ctx => (TimeSpan)ctx["timeout"]; @@ -552,19 +548,19 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.TimeoutAsync(timeoutProvider, TimeoutStrategy.Pessimistic, onTimeoutAsync); // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; + Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Awaiting(p => p.ExecuteAsync(async _ => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - }, context)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async _ => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); + }, context)) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); } [Fact] - public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimistic() + public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimistic() { Task taskPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, task) => @@ -573,14 +569,14 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimist return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); + })) + .Should().ThrowAsync(); taskPassedToOnTimeout.Should().NotBeNull(); } @@ -601,16 +597,16 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action_allo return TaskHelper.EmptyTask; }; - var shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; + TimeSpan shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.TimeoutAsync(shimTimespan, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken.None); - throw exceptionToThrow; - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken.None); + throw exceptionToThrow; + })) + .Should().ThrowAsync(); await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken.None); exceptionObservedFromTaskPassedToOnTimeout.Should().NotBeNull(); @@ -619,9 +615,9 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action_allo } [Fact] - public void Should_call_ontimeout_with_timing_out_exception__pessimistic() + public async Task Should_call_ontimeout_with_timing_out_exception__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, _, exception) => @@ -632,12 +628,11 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - })) - .Should().Throw(); + .Should().ThrowAsync(); exceptionPassedToOnTimeout.Should().NotBeNull(); exceptionPassedToOnTimeout.Should().BeOfType(typeof(OperationCanceledException)); @@ -648,9 +643,9 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() #region onTimeout overload - optimistic [Fact] - public void Should_call_ontimeout_with_configured_timeout__optimistic() + public async Task Should_call_ontimeout_with_configured_timeout__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -662,21 +657,20 @@ public void Should_call_ontimeout_with_configured_timeout__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - - }, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + }, userCancellationToken)) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); } [Fact] - public void Should_call_ontimeout_with_passed_context__optimistic() + public async Task Should_call_ontimeout_with_passed_context__optimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Func onTimeoutAsync = (ctx, _, _) => @@ -685,16 +679,15 @@ public void Should_call_ontimeout_with_passed_context__optimistic() return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => + await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, contextPassedToExecute, userCancellationToken)) - .Should().Throw(); + .Should().ThrowAsync(); contextPassedToOnTimeout.Should().NotBeNull(); contextPassedToOnTimeout.OperationKey.Should().Be(operationKey); @@ -705,9 +698,9 @@ public void Should_call_ontimeout_with_passed_context__optimistic() [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__optimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__optimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25* programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25* programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -719,12 +712,11 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => + await policy.Awaiting(p => p.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, userCancellationToken)) - .Should().Throw(); + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); } @@ -733,7 +725,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__optimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__optimistic(int programaticallyControlledDelay) { Func timeoutProvider = ctx => (TimeSpan)ctx["timeout"]; @@ -748,23 +740,23 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var userCancellationToken = CancellationToken.None; // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") + Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, context, userCancellationToken)) - .Should().Throw(); + }, context, userCancellationToken)) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); } [Fact] - public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__optimistic() + public async Task Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__optimistic() { Task taskPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, task) => @@ -773,24 +765,23 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - - }, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + }, userCancellationToken)) + .Should().ThrowAsync(); taskPassedToOnTimeout.Should().BeNull(); } [Fact] - public void Should_call_ontimeout_with_timing_out_exception__optimistic() + public async Task Should_call_ontimeout_with_timing_out_exception__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, _, exception) => @@ -802,12 +793,11 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - - }, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + }, userCancellationToken)) + .Should().ThrowAsync(); exceptionPassedToOnTimeout.Should().NotBeNull(); exceptionPassedToOnTimeout.Should().BeOfType(typeof(OperationCanceledException)); @@ -815,4 +805,4 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Timeout/TimeoutSpecs.cs b/src/Polly.Specs/Timeout/TimeoutSpecs.cs index 2accf7efb64..9e87f005cec 100644 --- a/src/Polly.Specs/Timeout/TimeoutSpecs.cs +++ b/src/Polly.Specs/Timeout/TimeoutSpecs.cs @@ -233,7 +233,7 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe var result = ResultPrimitive.Undefined; var userCancellationToken = CancellationToken.None; - var act = () => { + Action act = () => { result = policy.Execute(ct => { SystemClock.Sleep(TimeSpan.FromMilliseconds(500), ct); @@ -248,19 +248,19 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe [Fact] public void Should_throw_timeout_after_correct_duration__pessimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(10), CancellationToken.None))) .Should().Throw(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -278,7 +278,7 @@ public void Should_rethrow_aggregate_exception_from_inside_delegate__pessimistic var msg = "Aggregate Exception thrown from the delegate"; // Check to see if nested aggregate exceptions are unwrapped correctly - var exception = new AggregateException(msg, new NotImplementedException()); + AggregateException exception = new AggregateException(msg, new NotImplementedException()); policy.Invoking(p => p.Execute(() => { Helper_ThrowException(exception); })) .Should().Throw() @@ -295,7 +295,7 @@ public void Should_rethrow_aggregate_exception_with_multiple_exceptions_from_ins Exception innerException1 = new NotImplementedException(); Exception innerException2 = new DivideByZeroException(); - var aggregateException = new AggregateException(msg, innerException1, innerException2); + AggregateException aggregateException = new AggregateException(msg, innerException1, innerException2); Action action = () => throw aggregateException; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. @@ -315,10 +315,10 @@ public void Should_rethrow_aggregate_exception_with_example_cause_of_multiple_ex Exception innerException1 = new NotImplementedException(); Exception innerException2 = new DivideByZeroException(); - var action = () => + Action action = () => { - var task1 = Task.Run(() => throw innerException1); - var task2 = Task.Run(() => throw innerException2); + Task task1 = Task.Run(() => throw innerException1); + Task task2 = Task.Run(() => throw innerException2); Task.WhenAll(task1, task2).Wait(); }; @@ -337,7 +337,7 @@ public void Should_rethrow_aggregate_exception_with_another_example_cause_of_mul Exception innerException1 = new NotImplementedException(); Exception innerException2 = new DivideByZeroException(); - var action = () => + Action action = () => { Action action1 = () => throw innerException1; Action action2 = () => throw innerException2; @@ -373,12 +373,12 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op var result = ResultPrimitive.Undefined; var userCancellationToken = CancellationToken.None; - var act = () => { + Action act = () => { result = policy.Execute(ct => - { - SystemClock.Sleep(TimeSpan.FromMilliseconds(500), ct); - return ResultPrimitive.Good; - }, userCancellationToken); + { + SystemClock.Sleep(TimeSpan.FromMilliseconds(500), ct); + return ResultPrimitive.Good; + }, userCancellationToken); }; act.Should().NotThrow(); @@ -388,20 +388,20 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op [Fact] public void Should_throw_timeout_after_correct_duration__optimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout); var userCancellationToken = CancellationToken.None; - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); policy.Invoking(p => p.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(10), ct), userCancellationToken)) // Delegate observes cancellation token, so permitting optimistic cancellation. .Should().Throw(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -420,10 +420,10 @@ public void Should_rethrow_exception_from_inside_delegate__optimistic() [Fact] public void Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token_before_timeout__pessimistic() { - var timeout = 5; + int timeout = 5; var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { policy.Invoking(p => p.Execute( _ => @@ -431,10 +431,10 @@ public void Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token userTokenSource.Cancel(); // User token cancels in the middle of execution ... SystemClock.Sleep(TimeSpan.FromSeconds(timeout * 2), CancellationToken.None // ... but if the executed delegate does not observe it - ); + ); } , userTokenSource.Token) - ).Should().Throw(); // ... it's still the timeout we expect. + ).Should().Throw(); // ... it's still the timeout we expect. } } @@ -443,9 +443,9 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { var policy = Policy.Timeout(10, TimeoutStrategy.Pessimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); @@ -463,15 +463,15 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled [Fact] public void Should_be_able_to_cancel_with_user_cancellation_token_before_timeout__optimistic() { - var timeout = 10; + int timeout = 10; var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { policy.Invoking(p => p.Execute( - ct => { userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); } // Simulate cancel in the middle of execution - , userTokenSource.Token) // ... with user token. - ).Should().Throw(); // Not a TimeoutRejectedException; i.e. policy can distinguish user cancellation from timeout cancellation. + ct => { userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); } // Simulate cancel in the middle of execution + , userTokenSource.Token) // ... with user token. + ).Should().Throw(); // Not a TimeoutRejectedException; i.e. policy can distinguish user cancellation from timeout cancellation. } } @@ -480,9 +480,9 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { var policy = Policy.Timeout(10, TimeoutStrategy.Optimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); @@ -535,7 +535,7 @@ public void Should_not_mask_user_exception_if_user_exception_overlaps_with_timeo [Fact] public void Should_call_ontimeout_with_configured_timeout__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -551,13 +551,13 @@ public void Should_call_ontimeout_with_configured_timeout__pessimistic() [Fact] public void Should_call_ontimeout_with_passed_context__pessimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Action onTimeout = (ctx, _, _) => { contextPassedToOnTimeout = ctx; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); policy.Invoking(p => p.Execute(_ => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken.None), contextPassedToExecute)) @@ -574,7 +574,7 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() [InlineData(3)] public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -600,7 +600,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.Timeout(timeoutProvider, TimeoutStrategy.Pessimistic, onTimeout); // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") {["timeout"] = TimeSpan.FromMilliseconds(25* programaticallyControlledDelay) }; + Context context = new Context("SomeOperationKey") {["timeout"] = TimeSpan.FromMilliseconds(25* programaticallyControlledDelay) }; policy.Invoking(p => p.Execute(_ => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken.None), context)) .Should().Throw(); @@ -614,7 +614,7 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimist Task taskPassedToOnTimeout = null; Action onTimeout = (_, _, task) => { taskPassedToOnTimeout = task; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken.None))) @@ -638,15 +638,15 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action_allowing_c task.ContinueWith(t => exceptionObservedFromTaskPassedToOnTimeout = t.Exception.InnerException); }; - var shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; + TimeSpan shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.Timeout(shimTimespan, TimeoutStrategy.Pessimistic, onTimeout); policy.Invoking(p => p.Execute(() => - { - SystemClock.Sleep(thriceShimTimeSpan, CancellationToken.None); - throw exceptionToThrow; - })) + { + SystemClock.Sleep(thriceShimTimeSpan, CancellationToken.None); + throw exceptionToThrow; + })) .Should().Throw(); SystemClock.Sleep(thriceShimTimeSpan, CancellationToken.None); @@ -658,7 +658,7 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action_allowing_c [Fact] public void Should_call_ontimeout_with_timing_out_exception__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Action onTimeout = (_, _, _, exception) => { exceptionPassedToOnTimeout = exception; }; @@ -679,7 +679,7 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() [Fact] public void Should_call_ontimeout_with_configured_timeout__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -696,13 +696,13 @@ public void Should_call_ontimeout_with_configured_timeout__optimistic() [Fact] public void Should_call_ontimeout_with_passed_context__optimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Action onTimeout = (ctx, _, _) => { contextPassedToOnTimeout = ctx; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken.None; @@ -720,7 +720,7 @@ public void Should_call_ontimeout_with_passed_context__optimistic() [InlineData(3)] public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__optimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -749,7 +749,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var userCancellationToken = CancellationToken.None; // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") + Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; @@ -766,7 +766,7 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o Task taskPassedToOnTimeout = null; Action onTimeout = (_, _, task) => { taskPassedToOnTimeout = task; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken.None; @@ -779,7 +779,7 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o [Fact] public void Should_call_ontimeout_with_timing_out_exception__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Action onTimeout = (_, _, _, exception) => { exceptionPassedToOnTimeout = exception; }; @@ -795,4 +795,4 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Timeout/TimeoutSpecsBase.cs b/src/Polly.Specs/Timeout/TimeoutSpecsBase.cs index c4fe4798384..e5deefbea6e 100644 --- a/src/Polly.Specs/Timeout/TimeoutSpecsBase.cs +++ b/src/Polly.Specs/Timeout/TimeoutSpecsBase.cs @@ -22,7 +22,7 @@ public abstract class TimeoutSpecsBase : IDisposable private DateTimeOffset _offsetUtcNow = DateTimeOffset.UtcNow; private DateTime _utcNow = DateTime.UtcNow; - + protected TimeoutSpecsBase() { // Override the SystemClock, to return time stored in variables we manipulate. @@ -36,7 +36,7 @@ protected TimeoutSpecsBase() _trackedTokenSource = tokenSource; - var newCancelAt = _offsetUtcNow.Add(timespan); + DateTimeOffset newCancelAt = _offsetUtcNow.Add(timespan); _cancelAt = newCancelAt < _cancelAt ? newCancelAt : _cancelAt; SystemClock.Sleep(TimeSpan.Zero, CancellationToken.None); // Invoke our custom definition of sleep, to check for immediate cancellation. @@ -56,7 +56,7 @@ protected TimeoutSpecsBase() else { // Tracking something to cancel - does this sleep hit time to cancel? - var timeToCancellation = _cancelAt - _offsetUtcNow; + TimeSpan timeToCancellation = _cancelAt - _offsetUtcNow; if (sleepTimespan >= timeToCancellation) { // Cancel! (And advance time only to the instant of cancellation) @@ -64,7 +64,7 @@ protected TimeoutSpecsBase() _utcNow += timeToCancellation; // (and stop tracking it after cancelling; it can't be cancelled twice, so there is no need, and the owner may dispose it) - var copySource = _trackedTokenSource; + CancellationTokenSource copySource = _trackedTokenSource; _trackedTokenSource = null; copySource.Cancel(); copySource.Token.ThrowIfCancellationRequested(); @@ -99,4 +99,4 @@ protected void Helper_ThrowException(Exception ex) { throw ex; } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs b/src/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs index acda1c05976..097fef223bd 100644 --- a/src/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs +++ b/src/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs @@ -200,17 +200,17 @@ public void Should_be_able_to_configure_with_timeout_func() #region Timeout operation - pessimistic [Fact] - public void Should_throw_when_timeout_is_less_than_execution_duration__pessimistic() + public async Task Should_throw_when_timeout_is_less_than_execution_duration__pessimistic() { - var timeout = TimeSpan.FromMilliseconds(50); + TimeSpan timeout = TimeSpan.FromMilliseconds(50); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); return ResultPrimitive.WhateverButTooLate; - })).Should().Throw(); + })).Should().ThrowAsync(); } [Fact] @@ -218,42 +218,42 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(1), TimeoutStrategy.Pessimistic); - var result = ResultPrimitive.Undefined; + ResultPrimitive result = ResultPrimitive.Undefined; Func act = async () => result = await policy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); - act.Should().NotThrow(); + act.Should().NotThrowAsync(); result.Should().Be(ResultPrimitive.Good); } [Fact] - public void Should_throw_timeout_after_correct_duration__pessimistic() + public async Task Should_throw_timeout_after_correct_duration__pessimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), CancellationToken.None); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), CancellationToken.None); + return ResultPrimitive.WhateverButTooLate; + })) + .Should().ThrowAsync(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] - public void Should_rethrow_exception_from_inside_delegate__pessimistic() + public async Task Should_rethrow_exception_from_inside_delegate__pessimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic); - policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().ThrowAsync(); } #endregion @@ -261,16 +261,16 @@ public void Should_rethrow_exception_from_inside_delegate__pessimistic() #region Timeout operation - optimistic [Fact] - public void Should_throw_when_timeout_is_less_than_execution_duration__optimistic() + public async Task Should_throw_when_timeout_is_less_than_execution_duration__optimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(50), TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => + await policy.Awaiting(p => p.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)).Should().Throw(); + }, userCancellationToken)).Should().ThrowAsync(); } [Fact] @@ -278,44 +278,44 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(1), TimeoutStrategy.Optimistic); - var result = ResultPrimitive.Undefined; + ResultPrimitive result = ResultPrimitive.Undefined; var userCancellationToken = CancellationToken.None; Func act = async () => result = await policy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), userCancellationToken); - act.Should().NotThrow(); + act.Should().NotThrowAsync(); result.Should().Be(ResultPrimitive.Good); } [Fact] - public void Should_throw_timeout_after_correct_duration__optimistic() + public async Task Should_throw_timeout_after_correct_duration__optimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken.None; - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)) + .Should().ThrowAsync(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] - public void Should_rethrow_exception_from_inside_delegate__optimistic() + public async Task Should_rethrow_exception_from_inside_delegate__optimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Optimistic); - policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotImplementedException())).Should().ThrowAsync(); } #endregion @@ -323,43 +323,43 @@ public void Should_rethrow_exception_from_inside_delegate__optimistic() #region Non-timeout cancellation - pessimistic (user-delegate does not observe cancellation) [Fact] - public void Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token_before_timeout__pessimistic() + public async Task Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token_before_timeout__pessimistic() { - var timeout = 5; + int timeout = 5; var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { - policy.Awaiting(p => p.ExecuteAsync(async - _ => { + await policy.Awaiting(p => p.ExecuteAsync(async + _ => { userTokenSource.Cancel(); // User token cancels in the middle of execution ... await SystemClock.SleepAsync(TimeSpan.FromSeconds(timeout * 2), CancellationToken.None // ... but if the executed delegate does not observe it - ); + ); return ResultPrimitive.WhateverButTooLate; }, userTokenSource.Token) - ).Should().Throw(); // ... it's still the timeout we expect. + ).Should().ThrowAsync(); // ... it's still the timeout we expect. } } [Fact] - public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__pessimistic() + public async Task Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__pessimistic() { var policy = Policy.TimeoutAsync(10, TimeoutStrategy.Pessimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); - policy.Awaiting(p => p.ExecuteAsync(async _ => - { - executed = true; - await TaskHelper.EmptyTask; - return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async _ => + { + executed = true; + await TaskHelper.EmptyTask; + return ResultPrimitive.WhateverButTooLate; + }, cts.Token)) + .Should().ThrowAsync(); } executed.Should().BeFalse(); @@ -370,39 +370,39 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled #region Non-timeout cancellation - optimistic (user-delegate observes cancellation) [Fact] - public void Should_be_able_to_cancel_with_user_cancellation_token_before_timeout__optimistic() + public async Task Should_be_able_to_cancel_with_user_cancellation_token_before_timeout__optimistic() { - var timeout = 10; + int timeout = 10; var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { - policy.Awaiting(p => p.ExecuteAsync( - ct => { - userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution - return Task.FromResult(ResultPrimitive.WhateverButTooLate); - }, userTokenSource.Token) // ... with user token. - ).Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync( + ct => { + userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution + return Task.FromResult(ResultPrimitive.WhateverButTooLate); + }, userTokenSource.Token) // ... with user token. + ).Should().ThrowAsync(); } } [Fact] - public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__optimistic() + public async Task Should_not_execute_user_delegate_if_user_cancellationToken_cancelled_before_delegate_reached__optimistic() { var policy = Policy.TimeoutAsync(10, TimeoutStrategy.Optimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); - policy.Awaiting(p => p.ExecuteAsync(async _ => - { - executed = true; - await TaskHelper.EmptyTask; - return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async _ => + { + executed = true; + await TaskHelper.EmptyTask; + return ResultPrimitive.WhateverButTooLate; + }, cts.Token)) + .Should().ThrowAsync(); } executed.Should().BeFalse(); @@ -413,9 +413,9 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled #region onTimeout overload - pessimistic [Fact] - public void Should_call_ontimeout_with_configured_timeout__pessimistic() + public async Task Should_call_ontimeout_with_configured_timeout__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -426,21 +426,21 @@ public void Should_call_ontimeout_with_configured_timeout__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); + return ResultPrimitive.WhateverButTooLate; + })) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); } [Fact] - public void Should_call_ontimeout_with_passed_context__pessimistic() + public async Task Should_call_ontimeout_with_passed_context__pessimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Func onTimeoutAsync = (ctx, _, _) => @@ -449,15 +449,15 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async _ => + await policy.Awaiting(p => p.ExecuteAsync(async _ => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); return ResultPrimitive.WhateverButTooLate; }, contextPassedToExecute)) - .Should().Throw(); + .Should().ThrowAsync(); contextPassedToOnTimeout.Should().NotBeNull(); contextPassedToOnTimeout.OperationKey.Should().Be(operationKey); @@ -468,9 +468,9 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25* programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25* programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -481,12 +481,12 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); return ResultPrimitive.WhateverButTooLate; })) - .Should().Throw(); + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); } @@ -495,7 +495,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__pessimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__pessimistic(int programaticallyControlledDelay) { Func timeoutProvider = ctx => (TimeSpan)ctx["timeout"]; @@ -509,20 +509,20 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.TimeoutAsync(timeoutProvider, TimeoutStrategy.Pessimistic, onTimeoutAsync); // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; + Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Awaiting(p => p.ExecuteAsync(async _ => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - return ResultPrimitive.WhateverButTooLate; - }, context)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async _ => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); + return ResultPrimitive.WhateverButTooLate; + }, context)) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); } [Fact] - public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimistic() + public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimistic() { Task taskPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, task) => @@ -531,15 +531,15 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimist return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); + return ResultPrimitive.WhateverButTooLate; + })) + .Should().ThrowAsync(); taskPassedToOnTimeout.Should().NotBeNull(); } @@ -560,16 +560,16 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action_allo return TaskHelper.EmptyTask; }; - var shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; + TimeSpan shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.TimeoutAsync(shimTimespan, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken.None); - throw exceptionToThrow; - })) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken.None); + throw exceptionToThrow; + })) + .Should().ThrowAsync(); await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken.None); exceptionObservedFromTaskPassedToOnTimeout.Should().NotBeNull(); @@ -578,9 +578,9 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action_allo } [Fact] - public void Should_call_ontimeout_with_timing_out_exception__pessimistic() + public async Task Should_call_ontimeout_with_timing_out_exception__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, _, exception) => @@ -591,12 +591,12 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - policy.Awaiting(p => p.ExecuteAsync(async () => + await policy.Awaiting(p => p.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None); return ResultPrimitive.WhateverButTooLate; })) - .Should().Throw(); + .Should().ThrowAsync(); exceptionPassedToOnTimeout.Should().NotBeNull(); exceptionPassedToOnTimeout.Should().BeOfType(typeof(OperationCanceledException)); @@ -607,9 +607,9 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() #region onTimeout overload - optimistic [Fact] - public void Should_call_ontimeout_with_configured_timeout__optimistic() + public async Task Should_call_ontimeout_with_configured_timeout__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -621,21 +621,21 @@ public void Should_call_ontimeout_with_configured_timeout__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); } [Fact] - public void Should_call_ontimeout_with_passed_context__optimistic() + public async Task Should_call_ontimeout_with_passed_context__optimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Func onTimeoutAsync = (ctx, _, _) => @@ -644,16 +644,16 @@ public void Should_call_ontimeout_with_passed_context__optimistic() return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => + await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; }, contextPassedToExecute, userCancellationToken)) - .Should().Throw(); + .Should().ThrowAsync(); contextPassedToOnTimeout.Should().NotBeNull(); contextPassedToOnTimeout.OperationKey.Should().Be(operationKey); @@ -664,10 +664,10 @@ public void Should_call_ontimeout_with_passed_context__optimistic() [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__optimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__optimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Func onTimeoutAsync = (_, span, _) => @@ -679,12 +679,12 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => + await policy.Awaiting(p => p.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; }, userCancellationToken)) - .Should().Throw(); + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); } @@ -693,7 +693,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu [InlineData(1)] [InlineData(2)] [InlineData(3)] - public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__optimistic(int programaticallyControlledDelay) + public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__optimistic(int programaticallyControlledDelay) { Func timeoutProvider = ctx => (TimeSpan)ctx["timeout"]; @@ -708,23 +708,23 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var userCancellationToken = CancellationToken.None; // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") + Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, context, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, context, userCancellationToken)) + .Should().ThrowAsync(); timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); } [Fact] - public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__optimistic() + public async Task Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__optimistic() { Task taskPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, task) => @@ -733,24 +733,24 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o return TaskHelper.EmptyTask; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + await policy.Awaiting(p => p.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)) + .Should().ThrowAsync(); taskPassedToOnTimeout.Should().BeNull(); } [Fact] - public void Should_call_ontimeout_with_timing_out_exception__optimistic() + public async Task Should_call_ontimeout_with_timing_out_exception__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Func onTimeoutAsync = (_, _, _, exception) => @@ -762,12 +762,12 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; - policy.Awaiting(p => p.ExecuteAsync(async ct => + await policy.Awaiting(p => p.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; }, userCancellationToken)) - .Should().Throw(); + .Should().ThrowAsync(); exceptionPassedToOnTimeout.Should().NotBeNull(); exceptionPassedToOnTimeout.Should().BeOfType(typeof(OperationCanceledException)); @@ -775,4 +775,4 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Timeout/TimeoutTResultSpecs.cs b/src/Polly.Specs/Timeout/TimeoutTResultSpecs.cs index 025b422084f..4fa0845b6b5 100644 --- a/src/Polly.Specs/Timeout/TimeoutTResultSpecs.cs +++ b/src/Polly.Specs/Timeout/TimeoutTResultSpecs.cs @@ -201,7 +201,7 @@ public void Should_be_able_to_configure_with_timeout_func() [Fact] public void Should_throw_when_timeout_is_less_than_execution_duration__pessimistic() { - var timeout = TimeSpan.FromMilliseconds(50); + TimeSpan timeout = TimeSpan.FromMilliseconds(50); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); @@ -220,7 +220,7 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe var result = ResultPrimitive.Undefined; var userCancellationToken = CancellationToken.None; - var act = () => { + Action act = () => { result = policy.Execute(ct => { SystemClock.Sleep(TimeSpan.FromMilliseconds(500), ct); @@ -235,23 +235,23 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe [Fact] public void Should_throw_timeout_after_correct_duration__pessimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); policy.Invoking(p => p.Execute(() => - { - SystemClock.Sleep(TimeSpan.FromSeconds(10), CancellationToken.None); - return ResultPrimitive.WhateverButTooLate; - })) + { + SystemClock.Sleep(TimeSpan.FromSeconds(10), CancellationToken.None); + return ResultPrimitive.WhateverButTooLate; + })) .Should().Throw(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -269,7 +269,7 @@ public void Should_rethrow_aggregate_exception_from_inside_delegate__pessimistic var msg = "Aggregate Exception thrown from the delegate"; // Check to see if nested aggregate exceptions are unwrapped correctly - var exception = new AggregateException(msg, new NotImplementedException()); + AggregateException exception = new AggregateException(msg, new NotImplementedException()); policy.Invoking(p => p.Execute(() => { Helper_ThrowException(exception); return ResultPrimitive.WhateverButTooLate; })) .Should().Throw() @@ -286,8 +286,8 @@ public void Should_rethrow_aggregate_exception_with_multiple_exceptions_from_ins Exception innerException1 = new NotImplementedException(); Exception innerException2 = new DivideByZeroException(); - var aggregateException = new AggregateException(msg, innerException1, innerException2); - var func = () => { Helper_ThrowException(aggregateException); return ResultPrimitive.WhateverButTooLate; }; + AggregateException aggregateException = new AggregateException(msg, innerException1, innerException2); + Func func = () => { Helper_ThrowException(aggregateException); return ResultPrimitive.WhateverButTooLate; }; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. func.Should().Throw() @@ -306,10 +306,10 @@ public void Should_rethrow_aggregate_exception_with_example_cause_of_multiple_ex Exception innerException1 = new NotImplementedException(); Exception innerException2 = new DivideByZeroException(); - var func = () => + Func func = () => { - var task1 = Task.Run(() => throw innerException1); - var task2 = Task.Run(() => throw innerException2); + Task task1 = Task.Run(() => throw innerException1); + Task task2 = Task.Run(() => throw innerException2); Task.WhenAll(task1, task2).Wait(); return ResultPrimitive.WhateverButTooLate; }; @@ -329,9 +329,9 @@ public void Should_rethrow_aggregate_exception_with_another_example_cause_of_mul Exception innerException1 = new NotImplementedException(); Exception innerException2 = new DivideByZeroException(); - var func = () => + Func func = () => { - var action1 = () => { throw innerException1; }; + Action action1 = () => { throw innerException1; }; Action action2 = () => throw innerException2; Parallel.Invoke(action1, action2); return ResultPrimitive.WhateverButTooLate; @@ -356,11 +356,11 @@ public void Should_throw_when_timeout_is_less_than_execution_duration__optimisti var userCancellationToken = CancellationToken.None; policy.Invoking(p => p.Execute(ct => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)) + .Should().Throw(); } [Fact] @@ -370,7 +370,7 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op var result = ResultPrimitive.Undefined; var userCancellationToken = CancellationToken.None; - var act = () => { + Action act = () => { result = policy.Execute(ct => { SystemClock.Sleep(TimeSpan.FromMilliseconds(500), ct); @@ -385,24 +385,24 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op [Fact] public void Should_throw_timeout_after_correct_duration__optimistic() { - var watch = new Stopwatch(); + Stopwatch watch = new Stopwatch(); - var timeout = TimeSpan.FromSeconds(1); + TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken.None; - var tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); policy.Invoking(p => p.Execute(ct => - { - SystemClock.Sleep(TimeSpan.FromSeconds(10), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) + { + SystemClock.Sleep(TimeSpan.FromSeconds(10), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)) .Should().Throw(); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, ((int)tolerance.TotalMilliseconds)); + watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -420,20 +420,20 @@ public void Should_rethrow_exception_from_inside_delegate__optimistic() [Fact] public void Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token_before_timeout__pessimistic() { - var timeout = 5; + int timeout = 5; var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { policy.Invoking(p => p.Execute( _ => { userTokenSource.Cancel(); // User token cancels in the middle of execution ... SystemClock.Sleep(TimeSpan.FromSeconds(timeout * 2), CancellationToken.None // ... but if the executed delegate does not observe it - ); + ); return ResultPrimitive.WhateverButTooLate; }, userTokenSource.Token) - ).Should().Throw(); // ... it's still the timeout we expect. + ).Should().Throw(); // ... it's still the timeout we expect. } } @@ -442,18 +442,18 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { var policy = Policy.Timeout(10, TimeoutStrategy.Pessimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); policy.Invoking(p => p.Execute(_ => - { - executed = true; - return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().Throw(); + { + executed = true; + return ResultPrimitive.WhateverButTooLate; + }, cts.Token)) + .Should().Throw(); } executed.Should().BeFalse(); @@ -466,16 +466,16 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled [Fact] public void Should_be_able_to_cancel_with_user_cancellation_token_before_timeout__optimistic() { - var timeout = 10; + int timeout = 10; var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic); - using (var userTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource userTokenSource = new CancellationTokenSource()) { policy.Invoking(p => p.Execute( - ct => { - userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution - return ResultPrimitive.WhateverButTooLate; - }, userTokenSource.Token) // ... with user token. - ).Should().Throw(); // Not a TimeoutRejectedException; i.e. policy can distinguish user cancellation from timeout cancellation. + ct => { + userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution + return ResultPrimitive.WhateverButTooLate; + }, userTokenSource.Token) // ... with user token. + ).Should().Throw(); // Not a TimeoutRejectedException; i.e. policy can distinguish user cancellation from timeout cancellation. } } @@ -484,18 +484,18 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { var policy = Policy.Timeout(10, TimeoutStrategy.Optimistic); - var executed = false; + bool executed = false; - using (var cts = new CancellationTokenSource()) + using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.Cancel(); policy.Invoking(p => p.Execute(_ => - { - executed = true; - return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().Throw(); + { + executed = true; + return ResultPrimitive.WhateverButTooLate; + }, cts.Token)) + .Should().Throw(); } executed.Should().BeFalse(); @@ -508,7 +508,7 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled [Fact] public void Should_call_ontimeout_with_configured_timeout__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -516,11 +516,11 @@ public void Should_call_ontimeout_with_configured_timeout__pessimistic() var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeout); policy.Invoking(p => p.Execute(() => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken.None); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken.None); + return ResultPrimitive.WhateverButTooLate; + })) + .Should().Throw(); timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); } @@ -528,13 +528,13 @@ public void Should_call_ontimeout_with_configured_timeout__pessimistic() [Fact] public void Should_call_ontimeout_with_passed_context__pessimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Action onTimeout = (ctx, _, _) => { contextPassedToOnTimeout = ctx; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); policy.Invoking(p => p.Execute(_ => @@ -556,7 +556,7 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -587,7 +587,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.Timeout(timeoutProvider, TimeoutStrategy.Pessimistic, onTimeout); // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; + Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; policy.Invoking(p => p.Execute(_ => { @@ -605,15 +605,15 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimist Task taskPassedToOnTimeout = null; Action onTimeout = (_, _, task) => { taskPassedToOnTimeout = task; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); policy.Invoking(p => p.Execute(() => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken.None); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken.None); + return ResultPrimitive.WhateverButTooLate; + })) + .Should().Throw(); taskPassedToOnTimeout.Should().NotBeNull(); } @@ -633,16 +633,16 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action_allowing_c task.ContinueWith(t => exceptionObservedFromTaskPassedToOnTimeout = t.Exception.InnerException); }; - var shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. - var thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; + TimeSpan shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.Timeout(shimTimespan, TimeoutStrategy.Pessimistic, onTimeout); policy.Invoking(p => p.Execute(() => - { - SystemClock.Sleep(thriceShimTimeSpan, CancellationToken.None); - throw exceptionToThrow; - })) - .Should().Throw(); + { + SystemClock.Sleep(thriceShimTimeSpan, CancellationToken.None); + throw exceptionToThrow; + })) + .Should().Throw(); SystemClock.Sleep(thriceShimTimeSpan, CancellationToken.None); exceptionObservedFromTaskPassedToOnTimeout.Should().NotBeNull(); @@ -653,7 +653,7 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action_allowing_c [Fact] public void Should_call_ontimeout_with_timing_out_exception__pessimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Action onTimeout = (_, _, _, exception) => { exceptionPassedToOnTimeout = exception; }; @@ -679,7 +679,7 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() [Fact] public void Should_call_ontimeout_with_configured_timeout__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -688,11 +688,11 @@ public void Should_call_ontimeout_with_configured_timeout__optimistic() var userCancellationToken = CancellationToken.None; policy.Invoking(p => p.Execute(ct => - { - SystemClock.Sleep(TimeSpan.FromSeconds(1), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + { + SystemClock.Sleep(TimeSpan.FromSeconds(1), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)) + .Should().Throw(); timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); } @@ -700,13 +700,13 @@ public void Should_call_ontimeout_with_configured_timeout__optimistic() [Fact] public void Should_call_ontimeout_with_passed_context__optimistic() { - var operationKey = "SomeKey"; - var contextPassedToExecute = new Context(operationKey); + string operationKey = "SomeKey"; + Context contextPassedToExecute = new Context(operationKey); Context contextPassedToOnTimeout = null; Action onTimeout = (ctx, _, _) => { contextPassedToOnTimeout = ctx; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken.None; @@ -728,7 +728,7 @@ public void Should_call_ontimeout_with_passed_context__optimistic() [InlineData(3)] public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__optimistic(int programaticallyControlledDelay) { - var timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); + Func timeoutFunc = () => TimeSpan.FromMilliseconds(25*programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; @@ -760,7 +760,7 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var userCancellationToken = CancellationToken.None; // Supply a programatically-controlled timeout, via the execution context. - var context = new Context("SomeOperationKey") + Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; @@ -781,16 +781,16 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o Task taskPassedToOnTimeout = null; Action onTimeout = (_, _, task) => { taskPassedToOnTimeout = task; }; - var timeout = TimeSpan.FromMilliseconds(250); + TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken.None; policy.Invoking(p => p.Execute(ct => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)) + .Should().Throw(); taskPassedToOnTimeout.Should().BeNull(); } @@ -798,7 +798,7 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o [Fact] public void Should_call_ontimeout_with_timing_out_exception__optimistic() { - var timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); + TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception exceptionPassedToOnTimeout = null; Action onTimeout = (_, _, _, exception) => { exceptionPassedToOnTimeout = exception; }; @@ -819,4 +819,4 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs b/src/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs index 923c09e6ba3..8f18318b9a7 100644 --- a/src/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs +++ b/src/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs @@ -16,13 +16,13 @@ public class IPolicyWrapExtensionSpecs [Fact] public void Should_pass_all_nested_policies_from_PolicyWrap_in_same_order_they_were_added() { - var policy0 = Policy.NoOp(); - var policy1 = Policy.NoOp(); - var policy2 = Policy.NoOp(); + NoOpPolicy policy0 = Policy.NoOp(); + NoOpPolicy policy1 = Policy.NoOp(); + NoOpPolicy policy2 = Policy.NoOp(); - var policyWrap = Policy.Wrap(policy0, policy1, policy2); + PolicyWrap policyWrap = Policy.Wrap(policy0, policy1, policy2); - var policies = policyWrap.GetPolicies().ToList(); + List policies = policyWrap.GetPolicies().ToList(); policies.Count.Should().Be(3); policies[0].Should().Be(policy0); policies[1].Should().Be(policy1); @@ -34,7 +34,7 @@ public void Should_return_sequence_from_GetPolicies() { Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = Policy.Wrap(policyA, policyB); + PolicyWrap wrap = Policy.Wrap(policyA, policyB); wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB }, options => options @@ -49,7 +49,7 @@ public void Threepolicies_by_static_sequence_should_return_correct_sequence_from Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); Policy policyC = Policy.NoOp(); - var wrap = Policy.Wrap(policyA, policyB, policyC); + PolicyWrap wrap = Policy.Wrap(policyA, policyB, policyC); wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB, policyC }, options => options @@ -64,7 +64,7 @@ public void Threepolicies_lefttree_should_return_correct_sequence_from_GetPolici Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB).Wrap(policyC); + PolicyWrap wrap = policyA.Wrap(policyB).Wrap(policyC); wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB, policyC }, options => options @@ -79,7 +79,7 @@ public void Threepolicies_righttree_should_return_correct_sequence_from_GetPolic Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB, policyC }, options => options @@ -94,7 +94,7 @@ public void GetPoliciesTPolicy_should_return_single_policy_of_type_TPolicy() Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyB }, options => options @@ -109,7 +109,7 @@ public void GetPoliciesTPolicy_should_return_empty_enumerable_if_no_policy_of_ty Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicies().Should().BeEmpty(); } @@ -120,7 +120,7 @@ public void GetPoliciesTPolicy_should_return_multiple_policies_of_type_TPolicy() Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyC }, options => options @@ -132,13 +132,13 @@ public void GetPoliciesTPolicy_should_return_multiple_policies_of_type_TPolicy() [Fact] public void GetPoliciesTPolicy_should_return_policies_of_type_TPolicy_matching_predicate() { - var policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); Policy policyB = Policy.Handle().Retry(); - var policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); policyA.Isolate(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicies(p => p.CircuitState == CircuitState.Closed).Should().BeEquivalentTo(new[] { policyC }, options => options @@ -150,11 +150,11 @@ public void GetPoliciesTPolicy_should_return_policies_of_type_TPolicy_matching_p [Fact] public void GetPoliciesTPolicy_should_return_empty_enumerable_if_none_match_predicate() { - var policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); Policy policyB = Policy.Handle().Retry(); - var policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicies(p => p.CircuitState == CircuitState.Open).Should().BeEmpty(); } @@ -165,7 +165,7 @@ public void GetPoliciesTPolicy_with_predicate_should_return_multiple_policies_of Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicies(_ => true).Should().BeEquivalentTo(new[] { policyA, policyC }, options => options @@ -179,10 +179,10 @@ public void GetPoliciesTPolicy_with_predicate_should_throw_if_predicate_is_null( { Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = policyA.Wrap(policyB); + PolicyWrap wrap = policyA.Wrap(policyB); Action configure = () => wrap.GetPolicies(null); - + configure.Should().Throw().And.ParamName.Should().Be("filter"); } @@ -192,7 +192,7 @@ public void GetPolicyTPolicy_should_return_single_policy_of_type_TPolicy() Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicy().Should().BeSameAs(policyB); } @@ -203,7 +203,7 @@ public void GetPolicyTPolicy_should_return_null_if_no_TPolicy() Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicy().Should().BeNull(); } @@ -214,7 +214,7 @@ public void GetPolicyTPolicy_should_throw_if_multiple_TPolicy() Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.Invoking(p => p.GetPolicy()).Should().Throw(); } @@ -222,13 +222,13 @@ public void GetPolicyTPolicy_should_throw_if_multiple_TPolicy() [Fact] public void GetPolicyTPolicy_should_return_single_policy_of_type_TPolicy_matching_predicate() { - var policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); Policy policyB = Policy.Handle().Retry(); - var policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); policyA.Isolate(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicy(p => p.CircuitState == CircuitState.Closed).Should().BeSameAs(policyC); } @@ -236,11 +236,11 @@ public void GetPolicyTPolicy_should_return_single_policy_of_type_TPolicy_matchin [Fact] public void GetPolicyTPolicy_should_return_null_if_none_match_predicate() { - var policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyA = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); Policy policyB = Policy.Handle().Retry(); - var policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); + CircuitBreakerPolicy policyC = Policy.Handle().CircuitBreaker(1, TimeSpan.Zero); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.GetPolicy(p => p.CircuitState == CircuitState.Open).Should().BeNull(); } @@ -251,7 +251,7 @@ public void GetPolicyTPolicy_with_predicate_should_throw_if_multiple_TPolicy_if_ Policy policyA = Policy.NoOp(); Policy policyB = Policy.Handle().Retry(); Policy policyC = Policy.NoOp(); - var wrap = policyA.Wrap(policyB.Wrap(policyC)); + PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); wrap.Invoking(p => p.GetPolicy(_ => true)).Should().Throw(); } @@ -261,10 +261,10 @@ public void GetPolicyTPolicy_with_predicate_should_throw_if_predicate_is_null() { Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = policyA.Wrap(policyB); + PolicyWrap wrap = policyA.Wrap(policyB); Action configure = () => wrap.GetPolicy(null); configure.Should().Throw().And.ParamName.Should().Be("filter"); } -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs b/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs index f973709918f..fda74b9f571 100644 --- a/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs +++ b/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs @@ -13,9 +13,9 @@ public class PolicyWrapContextAndKeySpecs [Fact] public void Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onRetry = (_, _, context) => @@ -37,9 +37,9 @@ public void Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_Policy [Fact] public void Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onBreak = (_, _, context) => @@ -89,11 +89,11 @@ public void Should_restore_PolicyKey_of_outer_policy_to_execution_context_as_mov [Fact] public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_PolicyWrap_keys_even_when_executing_policies_in_inner_wrap() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var fallbackKey = Guid.NewGuid().ToString(); - var innerWrapKey = Guid.NewGuid().ToString(); - var outerWrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string fallbackKey = Guid.NewGuid().ToString(); + string innerWrapKey = Guid.NewGuid().ToString(); + string outerWrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onBreak = (_, _, context) => @@ -121,11 +121,11 @@ public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_P [Fact] public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_to_innermost_Policy_when_execute_method_generic() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var fallbackKey = Guid.NewGuid().ToString(); - var innerWrapKey = Guid.NewGuid().ToString(); - var outerWrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string fallbackKey = Guid.NewGuid().ToString(); + string innerWrapKey = Guid.NewGuid().ToString(); + string outerWrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onBreak = (_, _, context) => @@ -141,7 +141,7 @@ public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_to_innermost_Pol var innerWrap = retry.Wrap(breaker).WithPolicyKey(innerWrapKey); var outerWrap = fallback.Wrap(innerWrap).WithPolicyKey(outerWrapKey); - var doneOnceOnly = false; + bool doneOnceOnly = false; outerWrap.Execute(() => { if (!doneOnceOnly) @@ -170,9 +170,9 @@ public class PolicyWrapTResultContextAndKeySpecs [Fact] public void Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action, int, Context> onRetry = (_, _, context) => @@ -194,9 +194,9 @@ public void Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_Policy [Fact] public void Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action, TimeSpan, Context> onBreak = (_, _, context) => @@ -237,7 +237,7 @@ public void Should_restore_PolicyKey_of_outer_policy_to_execution_context_as_mov }) .WithPolicyKey("RetryPolicy"); - var policyWrap = Policy.Wrap(fallback, retry) + Policy policyWrap = Policy.Wrap(fallback, retry) .WithPolicyKey("PolicyWrap"); policyWrap.Execute(() => throw new Exception()); @@ -246,11 +246,11 @@ public void Should_restore_PolicyKey_of_outer_policy_to_execution_context_as_mov [Fact] public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_PolicyWrap_keys_even_when_executing_policies_in_inner_wrap() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var fallbackKey = Guid.NewGuid().ToString(); - var innerWrapKey = Guid.NewGuid().ToString(); - var outerWrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string fallbackKey = Guid.NewGuid().ToString(); + string innerWrapKey = Guid.NewGuid().ToString(); + string outerWrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action, TimeSpan, Context> onBreak = (_, _, context) => @@ -277,4 +277,5 @@ public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_P #endregion -} \ No newline at end of file +} + diff --git a/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecsAsync.cs b/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecsAsync.cs index 9ebb3766f77..34e0e956ec2 100644 --- a/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecsAsync.cs +++ b/src/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecsAsync.cs @@ -15,9 +15,9 @@ public class PolicyWrapContextAndKeySpecsAsync [Fact] public async Task Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onRetry = (_, _, context) => @@ -39,9 +39,9 @@ public async Task Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_ [Fact] public async Task Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onBreak = (_, _, context) => @@ -120,11 +120,11 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ [Fact] public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_PolicyWrap_keys_even_when_executing_policies_in_inner_WrapAsync() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var fallbackKey = Guid.NewGuid().ToString(); - var innerWrapKey = Guid.NewGuid().ToString(); - var outerWrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string fallbackKey = Guid.NewGuid().ToString(); + string innerWrapKey = Guid.NewGuid().ToString(); + string outerWrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onBreak = (_, _, context) => @@ -152,11 +152,11 @@ public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_i [Fact] public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_to_innermost_Policy_when_execute_method_generic() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var fallbackKey = Guid.NewGuid().ToString(); - var innerWrapKey = Guid.NewGuid().ToString(); - var outerWrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string fallbackKey = Guid.NewGuid().ToString(); + string innerWrapKey = Guid.NewGuid().ToString(); + string outerWrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action onBreak = (_, _, context) => @@ -172,7 +172,7 @@ public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_to_innermo var innerWrap = retry.WrapAsync(breaker).WithPolicyKey(innerWrapKey); var outerWrap = fallback.WrapAsync(innerWrap).WithPolicyKey(outerWrapKey); - var doneOnceOnly = false; + bool doneOnceOnly = false; await outerWrap.ExecuteAsync(() => { if (!doneOnceOnly) @@ -202,9 +202,9 @@ public class PolicyWrapTResultContextAndKeySpecsAsync [Fact] public async Task Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action, int, Context> onRetry = (_, _, context) => @@ -226,9 +226,9 @@ public async Task Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_ [Fact] public async Task Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_PolicyWrapKey() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var wrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string wrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action, TimeSpan, Context> onBreak = (_, _, context) => @@ -314,11 +314,11 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ [Fact] public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_PolicyWrap_keys_even_when_executing_policies_in_inner_WrapAsync() { - var retryKey = Guid.NewGuid().ToString(); - var breakerKey = Guid.NewGuid().ToString(); - var fallbackKey = Guid.NewGuid().ToString(); - var innerWrapKey = Guid.NewGuid().ToString(); - var outerWrapKey = Guid.NewGuid().ToString(); + string retryKey = Guid.NewGuid().ToString(); + string breakerKey = Guid.NewGuid().ToString(); + string fallbackKey = Guid.NewGuid().ToString(); + string innerWrapKey = Guid.NewGuid().ToString(); + string outerWrapKey = Guid.NewGuid().ToString(); string policyWrapKeySetOnExecutionContext = null; Action, TimeSpan, Context> onBreak = (_, _, context) => @@ -345,4 +345,5 @@ public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_i #endregion -} \ No newline at end of file +} + diff --git a/src/Polly.Specs/Wrap/PolicyWrapSpecs.cs b/src/Polly.Specs/Wrap/PolicyWrapSpecs.cs index 2d786cd0e88..304554475ef 100644 --- a/src/Polly.Specs/Wrap/PolicyWrapSpecs.cs +++ b/src/Polly.Specs/Wrap/PolicyWrapSpecs.cs @@ -16,7 +16,7 @@ public class PolicyWrapSpecs [Fact] public void Nongeneric_wraps_nongeneric_instance_syntax_wrapping_null_should_throw() { - var retry = Policy.Handle().Retry(1); + RetryPolicy retry = Policy.Handle().Retry(1); Action config = () => retry.Wrap((Policy)null); @@ -26,7 +26,7 @@ public void Nongeneric_wraps_nongeneric_instance_syntax_wrapping_null_should_thr [Fact] public void Nongeneric_wraps_generic_instance_syntax_wrapping_null_should_throw() { - var retry = Policy.Handle().Retry(1); + RetryPolicy retry = Policy.Handle().Retry(1); Action config = () => retry.Wrap((Policy)null); @@ -39,7 +39,7 @@ public void Nongeneric_wraps_nongeneric_using_instance_wrap_syntax_should_set_ou Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = policyA.Wrap(policyB); + PolicyWrap wrap = policyA.Wrap(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -51,7 +51,7 @@ public void Nongeneric_wraps_generic_using_instance_wrap_syntax_should_set_outer Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = policyA.Wrap(policyB); + PolicyWrap wrap = policyA.Wrap(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -64,7 +64,7 @@ public void Nongeneric_wraps_generic_using_instance_wrap_syntax_should_set_outer [Fact] public void Generic_wraps_nongeneric_instance_syntax_wrapping_null_should_throw() { - var retry = Policy.HandleResult(0).Retry(1); + RetryPolicy retry = Policy.HandleResult(0).Retry(1); Action config = () => retry.Wrap((Policy)null); @@ -75,7 +75,7 @@ public void Generic_wraps_nongeneric_instance_syntax_wrapping_null_should_throw( [Fact] public void Generic_wraps_generic_instance_syntax_wrapping_null_should_throw() { - var retry = Policy.HandleResult(0).Retry(1); + RetryPolicy retry = Policy.HandleResult(0).Retry(1); Action config = () => retry.Wrap((Policy)null); @@ -88,7 +88,7 @@ public void Generic_wraps_nongeneric_using_instance_wrap_syntax_should_set_outer Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = policyA.Wrap(policyB); + PolicyWrap wrap = policyA.Wrap(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -100,7 +100,7 @@ public void Generic_wraps_generic_using_instance_wrap_syntax_should_set_outer_in Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = policyA.Wrap(policyB); + PolicyWrap wrap = policyA.Wrap(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -295,7 +295,7 @@ public void Wrapping_policies_using_static_wrap_syntax_should_set_outer_inner() Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = Policy.Wrap(policyA, policyB); + PolicyWrap wrap = Policy.Wrap(policyA, policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -350,7 +350,7 @@ public void Wrapping_policies_using_static_wrap_strongly_typed_syntax_should_set Policy policyA = Policy.NoOp(); Policy policyB = Policy.NoOp(); - var wrap = Policy.Wrap(policyA, policyB); + PolicyWrap wrap = Policy.Wrap(policyA, policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -363,11 +363,11 @@ public void Wrapping_policies_using_static_wrap_strongly_typed_syntax_should_set [Fact] public void Wrapping_two_policies_by_instance_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() { - var retry = Policy.Handle().Retry(1); // Two tries in total: first try, plus one retry. - var breaker = Policy.Handle().CircuitBreaker(2, TimeSpan.MaxValue); + RetryPolicy retry = Policy.Handle().Retry(1); // Two tries in total: first try, plus one retry. + CircuitBreakerPolicy breaker = Policy.Handle().CircuitBreaker(2, TimeSpan.MaxValue); - var retryWrappingBreaker = retry.Wrap(breaker); - var breakerWrappingRetry = breaker.Wrap(retry); + PolicyWrap retryWrappingBreaker = retry.Wrap(breaker); + PolicyWrap breakerWrappingRetry = breaker.Wrap(retry); // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); @@ -385,8 +385,8 @@ public void Wrapping_two_policies_by_instance_syntax_and_executing_should_wrap_o [Fact] public void Wrapping_two_generic_policies_by_instance_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() { - var retry = Policy.HandleResult(ResultPrimitive.Fault).Retry(1); // Two tries in total: first try, plus one retry. - var breaker = Policy.HandleResult(ResultPrimitive.Fault).CircuitBreaker(2, TimeSpan.MaxValue); + RetryPolicy retry = Policy.HandleResult(ResultPrimitive.Fault).Retry(1); // Two tries in total: first try, plus one retry. + CircuitBreakerPolicy breaker = Policy.HandleResult(ResultPrimitive.Fault).CircuitBreaker(2, TimeSpan.MaxValue); var retryWrappingBreaker = retry.Wrap(breaker); var breakerWrappingRetry = breaker.Wrap(retry); @@ -411,11 +411,11 @@ public void Wrapping_two_generic_policies_by_instance_syntax_and_executing_shoul [Fact] public void Wrapping_two_policies_by_static_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() { - var retry = Policy.Handle().Retry(1); // Two tries in total: first try, plus one retry. - var breaker = Policy.Handle().CircuitBreaker(2, TimeSpan.MaxValue); + RetryPolicy retry = Policy.Handle().Retry(1); // Two tries in total: first try, plus one retry. + CircuitBreakerPolicy breaker = Policy.Handle().CircuitBreaker(2, TimeSpan.MaxValue); - var retryWrappingBreaker = Policy.Wrap(retry, breaker); - var breakerWrappingRetry = Policy.Wrap(breaker, retry); + PolicyWrap retryWrappingBreaker = Policy.Wrap(retry, breaker); + PolicyWrap breakerWrappingRetry = Policy.Wrap(breaker, retry); // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); @@ -433,8 +433,8 @@ public void Wrapping_two_policies_by_static_syntax_and_executing_should_wrap_out [Fact] public void Wrapping_two_generic_policies_by_static_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() { - var retry = Policy.HandleResult(ResultPrimitive.Fault).Retry(1); // Two tries in total: first try, plus one retry. - var breaker = Policy.HandleResult(ResultPrimitive.Fault).CircuitBreaker(2, TimeSpan.MaxValue); + RetryPolicy retry = Policy.HandleResult(ResultPrimitive.Fault).Retry(1); // Two tries in total: first try, plus one retry. + CircuitBreakerPolicy breaker = Policy.HandleResult(ResultPrimitive.Fault).CircuitBreaker(2, TimeSpan.MaxValue); var retryWrappingBreaker = Policy.Wrap(retry, breaker); var breakerWrappingRetry = Policy.Wrap(breaker, retry); @@ -442,13 +442,13 @@ public void Wrapping_two_generic_policies_by_static_syntax_and_executing_should_ // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); retryWrappingBreaker.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); breakerWrappingRetry.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -459,15 +459,15 @@ public void Wrapping_two_generic_policies_by_static_syntax_and_executing_should_ [Fact] public void Outermost_policy_handling_exception_should_report_as_PolicyWrap_handled_exception() { - var innerHandlingDBZE = Policy + CircuitBreakerPolicy innerHandlingDBZE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var outerHandlingANE = Policy + CircuitBreakerPolicy outerHandlingANE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var wrap = outerHandlingANE.Wrap(innerHandlingDBZE); + PolicyWrap wrap = outerHandlingANE.Wrap(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new ArgumentNullException(); }); + PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new ArgumentNullException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); @@ -477,15 +477,15 @@ public void Outermost_policy_handling_exception_should_report_as_PolicyWrap_hand [Fact] public void Outermost_policy_not_handling_exception_even_if_inner_policies_do_should_report_as_unhandled_exception() { - var innerHandlingDBZE = Policy + CircuitBreakerPolicy innerHandlingDBZE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var outerHandlingANE = Policy + CircuitBreakerPolicy outerHandlingANE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var wrap = outerHandlingANE.Wrap(innerHandlingDBZE); + PolicyWrap wrap = outerHandlingANE.Wrap(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new DivideByZeroException(); }); + PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new DivideByZeroException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); @@ -495,15 +495,15 @@ public void Outermost_policy_not_handling_exception_even_if_inner_policies_do_sh [Fact] public void Outermost_generic_policy_handling_exception_should_report_as_PolicyWrap_handled_exception() { - var innerHandlingDBZE = Policy + CircuitBreakerPolicy innerHandlingDBZE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var outerHandlingANE = Policy + CircuitBreakerPolicy outerHandlingANE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var wrap = outerHandlingANE.Wrap(innerHandlingDBZE); + PolicyWrap wrap = outerHandlingANE.Wrap(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new ArgumentNullException(); }); + PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new ArgumentNullException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); @@ -514,15 +514,15 @@ public void Outermost_generic_policy_handling_exception_should_report_as_PolicyW [Fact] public void Outermost_generic_policy_not_handling_exception_even_if_inner_policies_do_should_report_as_unhandled_exception() { - var innerHandlingDBZE = Policy + CircuitBreakerPolicy innerHandlingDBZE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var outerHandlingANE = Policy + CircuitBreakerPolicy outerHandlingANE = Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - var wrap = outerHandlingANE.Wrap(innerHandlingDBZE); + PolicyWrap wrap = outerHandlingANE.Wrap(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new DivideByZeroException(); }); + PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new DivideByZeroException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); @@ -533,15 +533,15 @@ public void Outermost_generic_policy_not_handling_exception_even_if_inner_polici [Fact] public void Outermost_generic_policy_handling_result_should_report_as_PolicyWrap_handled_result() { - var innerHandlingFaultAgain = Policy + CircuitBreakerPolicy innerHandlingFaultAgain = Policy .HandleResult(ResultPrimitive.FaultAgain) .CircuitBreaker(1, TimeSpan.Zero); - var outerHandlingFault = Policy + CircuitBreakerPolicy outerHandlingFault = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, TimeSpan.Zero); - var wrap = outerHandlingFault.Wrap(innerHandlingFaultAgain); + PolicyWrap wrap = outerHandlingFault.Wrap(innerHandlingFaultAgain); - var executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => ResultPrimitive.Fault); + PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => ResultPrimitive.Fault); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ResultHandledByThisPolicy); @@ -553,15 +553,15 @@ public void Outermost_generic_policy_handling_result_should_report_as_PolicyWrap [Fact] public void Outermost_generic_policy_not_handling_result_even_if_inner_policies_do_should_not_report_as_handled() { - var innerHandlingFaultAgain = Policy + CircuitBreakerPolicy innerHandlingFaultAgain = Policy .HandleResult(ResultPrimitive.FaultAgain) .CircuitBreaker(1, TimeSpan.Zero); - var outerHandlingFault = Policy + CircuitBreakerPolicy outerHandlingFault = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, TimeSpan.Zero); - var wrap = outerHandlingFault.Wrap(innerHandlingFaultAgain); + PolicyWrap wrap = outerHandlingFault.Wrap(innerHandlingFaultAgain); - var executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => ResultPrimitive.FaultAgain); + PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => ResultPrimitive.FaultAgain); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Successful); executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(default(ResultPrimitive)); @@ -571,4 +571,4 @@ public void Outermost_generic_policy_not_handling_result_even_if_inner_policies_ } #endregion -} \ No newline at end of file +} diff --git a/src/Polly.Specs/Wrap/PolicyWrapSpecsAsync.cs b/src/Polly.Specs/Wrap/PolicyWrapSpecsAsync.cs index 11f6d02b75d..72015e808a8 100644 --- a/src/Polly.Specs/Wrap/PolicyWrapSpecsAsync.cs +++ b/src/Polly.Specs/Wrap/PolicyWrapSpecsAsync.cs @@ -39,7 +39,7 @@ public void Nongeneric_wraps_nongeneric_using_instance_wrap_syntax_should_set_ou AsyncPolicy policyA = Policy.NoOpAsync(); AsyncPolicy policyB = Policy.NoOpAsync(); - var wrap = policyA.WrapAsync(policyB); + AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -51,7 +51,7 @@ public void Nongeneric_wraps_generic_using_instance_wrap_syntax_should_set_outer AsyncPolicy policyA = Policy.NoOpAsync(); AsyncPolicy policyB = Policy.NoOpAsync(); - var wrap = policyA.WrapAsync(policyB); + AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -87,7 +87,7 @@ public void Generic_wraps_nongeneric_using_instance_wrap_syntax_should_set_outer AsyncPolicy policyA = Policy.NoOpAsync(); AsyncPolicy policyB = Policy.NoOpAsync(); - var wrap = policyA.WrapAsync(policyB); + AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -99,7 +99,7 @@ public void Generic_wraps_generic_using_instance_wrap_syntax_should_set_outer_in AsyncPolicy policyA = Policy.NoOpAsync(); AsyncPolicy policyB = Policy.NoOpAsync(); - var wrap = policyA.WrapAsync(policyB); + AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -294,7 +294,7 @@ public void Wrapping_policies_using_static_wrap_syntax_should_set_outer_inner() AsyncPolicy policyA = Policy.NoOpAsync(); AsyncPolicy policyB = Policy.NoOpAsync(); - var wrap = Policy.WrapAsync(policyA, policyB); + AsyncPolicyWrap wrap = Policy.WrapAsync(policyA, policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -349,7 +349,7 @@ public void Wrapping_policies_using_static_wrap_strongly_typed_syntax_should_set AsyncPolicy policyA = Policy.NoOpAsync(); AsyncPolicy policyB = Policy.NoOpAsync(); - var wrap = Policy.WrapAsync(policyA, policyB); + AsyncPolicyWrap wrap = Policy.WrapAsync(policyA, policyB); wrap.Outer.Should().BeSameAs(policyA); wrap.Inner.Should().BeSameAs(policyB); @@ -360,24 +360,24 @@ public void Wrapping_policies_using_static_wrap_strongly_typed_syntax_should_set #region Instance-configured: execution tests [Fact] - public void Wrapping_two_policies_by_instance_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() + public async Task Wrapping_two_policies_by_instance_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() { var retry = Policy.Handle().RetryAsync(1); // Two tries in total: first try, plus one retry. var breaker = Policy.Handle().CircuitBreakerAsync(2, TimeSpan.MaxValue); - var retryWrappingBreaker = retry.WrapAsync(breaker); - var breakerWrappingRetry = breaker.WrapAsync(retry); + AsyncPolicyWrap retryWrappingBreaker = retry.WrapAsync(breaker); + AsyncPolicyWrap breakerWrappingRetry = breaker.WrapAsync(retry); // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); - retryWrappingBreaker.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().Throw(); + await retryWrappingBreaker.Awaiting(x => x.RaiseExceptionAsync(2)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); - breakerWrappingRetry.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().Throw(); + await breakerWrappingRetry.Awaiting(x => x.RaiseExceptionAsync(2)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -408,24 +408,24 @@ public async Task Wrapping_two_generic_policies_by_instance_syntax_and_executing #region Static-configured: execution tests [Fact] - public void Wrapping_two_policies_by_static_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() + public async Task Wrapping_two_policies_by_static_syntax_and_executing_should_wrap_outer_then_inner_around_delegate() { var retry = Policy.Handle().RetryAsync(1); // Two tries in total: first try, plus one retry. var breaker = Policy.Handle().CircuitBreakerAsync(2, TimeSpan.MaxValue); - var retryWrappingBreaker = Policy.WrapAsync(retry, breaker); - var breakerWrappingRetry = Policy.WrapAsync(breaker, retry); + AsyncPolicyWrap retryWrappingBreaker = Policy.WrapAsync(retry, breaker); + AsyncPolicyWrap breakerWrappingRetry = Policy.WrapAsync(breaker, retry); // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); - retryWrappingBreaker.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().Throw(); + await retryWrappingBreaker.Awaiting(x => x.RaiseExceptionAsync(2)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); - breakerWrappingRetry.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().Throw(); + await breakerWrappingRetry.Awaiting(x => x.RaiseExceptionAsync(2)) + .Should().ThrowAsync(); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -441,13 +441,13 @@ public async Task Wrapping_two_generic_policies_by_static_syntax_and_executing_s // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); (await retryWrappingBreaker.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); (await breakerWrappingRetry.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .Should().Be(ResultPrimitive.Fault); breaker.CircuitState.Should().Be(CircuitState.Closed); } @@ -464,9 +464,9 @@ public async Task Outermost_policy_handling_exception_should_report_as_PolicyWra var outerHandlingANE = Policy .Handle() .CircuitBreakerAsync(1, TimeSpan.Zero); - var wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); + AsyncPolicyWrap wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = + PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new ArgumentNullException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); @@ -483,9 +483,9 @@ public async Task Outermost_policy_not_handling_exception_even_if_inner_policies var outerHandlingANE = Policy .Handle() .CircuitBreakerAsync(1, TimeSpan.Zero); - var wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); + AsyncPolicyWrap wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = + PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new DivideByZeroException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); @@ -502,9 +502,9 @@ public async Task Outermost_generic_policy_handling_exception_should_report_as_P var outerHandlingANE = Policy .Handle() .CircuitBreakerAsync(1, TimeSpan.Zero); - var wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); + AsyncPolicyWrap wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new ArgumentNullException(); }); + PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new ArgumentNullException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); @@ -521,9 +521,9 @@ public async Task Outermost_generic_policy_not_handling_exception_even_if_inner_ var outerHandlingANE = Policy .Handle() .CircuitBreakerAsync(1, TimeSpan.Zero); - var wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); + AsyncPolicyWrap wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE); - var executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new DivideByZeroException(); }); + PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new DivideByZeroException(); }); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); @@ -540,9 +540,9 @@ public async Task Outermost_generic_policy_handling_result_should_report_as_Poli var outerHandlingFault = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(1, TimeSpan.Zero); - var wrap = outerHandlingFault.WrapAsync(innerHandlingFaultAgain); + AsyncPolicyWrap wrap = outerHandlingFault.WrapAsync(innerHandlingFaultAgain); - var executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.Fault)); + PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.Fault)); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ResultHandledByThisPolicy); @@ -560,9 +560,9 @@ public async Task Outermost_generic_policy_not_handling_result_even_if_inner_pol var outerHandlingFault = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(1, TimeSpan.Zero); - var wrap = outerHandlingFault.WrapAsync(innerHandlingFaultAgain); + AsyncPolicyWrap wrap = outerHandlingFault.WrapAsync(innerHandlingFaultAgain); - var executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.FaultAgain)); + PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.FaultAgain)); executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Successful); executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(default(ResultPrimitive)); @@ -573,4 +573,4 @@ public async Task Outermost_generic_policy_not_handling_result_even_if_inner_pol #endregion -} \ No newline at end of file +} diff --git a/src/Polly/AsyncPolicy.ContextAndKeys.cs b/src/Polly/AsyncPolicy.ContextAndKeys.cs index 4660c69e059..80a83d51b65 100644 --- a/src/Polly/AsyncPolicy.ContextAndKeys.cs +++ b/src/Polly/AsyncPolicy.ContextAndKeys.cs @@ -57,4 +57,4 @@ IAsyncPolicy IAsyncPolicy.WithPolicyKey(string policyKey) policyKeyInternal = policyKey; return this; } -} \ No newline at end of file +} diff --git a/src/Polly/AsyncPolicy.ExecuteOverloads.cs b/src/Polly/AsyncPolicy.ExecuteOverloads.cs index 0bed81a7826..bfc94327e78 100644 --- a/src/Polly/AsyncPolicy.ExecuteOverloads.cs +++ b/src/Polly/AsyncPolicy.ExecuteOverloads.cs @@ -101,7 +101,7 @@ public async Task ExecuteAsync(Func action, Co { if (context == null) throw new ArgumentNullException(nameof(context)); - SetPolicyContext(context, out var priorPolicyWrapKey, out var priorPolicyKey); + SetPolicyContext(context, out string priorPolicyWrapKey, out string priorPolicyKey); try { @@ -221,7 +221,7 @@ public async Task ExecuteAsync(Func> ExecuteAndCaptureAsync(Func ImplementationAsync( CancellationToken cancellationToken, bool continueOnCapturedContext ); -} \ No newline at end of file +} diff --git a/src/Polly/AsyncPolicy.NonGenericImplementation.cs b/src/Polly/AsyncPolicy.NonGenericImplementation.cs index 0ab138ffa28..1f8b947266f 100644 --- a/src/Polly/AsyncPolicy.NonGenericImplementation.cs +++ b/src/Polly/AsyncPolicy.NonGenericImplementation.cs @@ -42,4 +42,4 @@ protected abstract Task ImplementationAsync( bool continueOnCapturedContext ); -} \ No newline at end of file +} diff --git a/src/Polly/AsyncPolicy.TResult.ExecuteOverloads.cs b/src/Polly/AsyncPolicy.TResult.ExecuteOverloads.cs index 4af101b5e00..93ed40231af 100644 --- a/src/Polly/AsyncPolicy.TResult.ExecuteOverloads.cs +++ b/src/Polly/AsyncPolicy.TResult.ExecuteOverloads.cs @@ -111,7 +111,7 @@ public async Task ExecuteAsync(Func> ExecuteAndCaptureAsync(Func> ExecuteAndCaptureAsync(Func policyBuilder = null) : base(policyBuilder) { } -} \ No newline at end of file +} diff --git a/src/Polly/AsyncPolicy.cs b/src/Polly/AsyncPolicy.cs index 9232f3d632b..a1c2b7df9c7 100644 --- a/src/Polly/AsyncPolicy.cs +++ b/src/Polly/AsyncPolicy.cs @@ -22,4 +22,4 @@ protected AsyncPolicy(PolicyBuilder policyBuilder = null) : base(policyBuilder) { } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/AsyncBulkheadEngine.cs b/src/Polly/Bulkhead/AsyncBulkheadEngine.cs index a5ba5933861..e3c3a8f6ec3 100644 --- a/src/Polly/Bulkhead/AsyncBulkheadEngine.cs +++ b/src/Polly/Bulkhead/AsyncBulkheadEngine.cs @@ -4,9 +4,9 @@ namespace Polly.Bulkhead; -internal static class AsyncBulkheadEngine + internal static class AsyncBulkheadEngine { - internal static async Task ImplementationAsync( + internal static async Task ImplementationAsync( Func> action, Context context, Func onBulkheadRejectedAsync, @@ -38,4 +38,4 @@ internal static async Task ImplementationAsync( maxQueuedActionsSemaphore.Release(); } } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/AsyncBulkheadPolicy.cs b/src/Polly/Bulkhead/AsyncBulkheadPolicy.cs index 54633b4cb2c..39b7ec8126d 100644 --- a/src/Polly/Bulkhead/AsyncBulkheadPolicy.cs +++ b/src/Polly/Bulkhead/AsyncBulkheadPolicy.cs @@ -39,8 +39,10 @@ internal AsyncBulkheadPolicy( /// [DebuggerStepThrough] protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncBulkheadEngine.ImplementationAsync(action, context, _onBulkheadRejectedAsync, _maxParallelizationSemaphore, _maxQueuedActionsSemaphore, cancellationToken, continueOnCapturedContext); + bool continueOnCapturedContext) + { + return AsyncBulkheadEngine.ImplementationAsync(action, context, _onBulkheadRejectedAsync, _maxParallelizationSemaphore, _maxQueuedActionsSemaphore, cancellationToken, continueOnCapturedContext); + } /// public void Dispose() @@ -74,8 +76,10 @@ internal AsyncBulkheadPolicy( /// [DebuggerStepThrough] - protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext) => - AsyncBulkheadEngine.ImplementationAsync(action, context, _onBulkheadRejectedAsync, _maxParallelizationSemaphore, _maxQueuedActionsSemaphore, cancellationToken, continueOnCapturedContext); + protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext) + { + return AsyncBulkheadEngine.ImplementationAsync(action, context, _onBulkheadRejectedAsync, _maxParallelizationSemaphore, _maxQueuedActionsSemaphore, cancellationToken, continueOnCapturedContext); + } /// /// Gets the number of slots currently available for executing actions through the bulkhead. @@ -93,4 +97,4 @@ public void Dispose() _maxParallelizationSemaphore.Dispose(); _maxQueuedActionsSemaphore.Dispose(); } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/AsyncBulkheadSyntax.cs b/src/Polly/Bulkhead/AsyncBulkheadSyntax.cs index b4b81e7061f..44a93be2557 100644 --- a/src/Polly/Bulkhead/AsyncBulkheadSyntax.cs +++ b/src/Polly/Bulkhead/AsyncBulkheadSyntax.cs @@ -71,6 +71,6 @@ public static AsyncBulkheadPolicy BulkheadAsync( maxParallelization, maxQueuingActions, onBulkheadRejectedAsync - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/AsyncBulkheadTResultSyntax.cs b/src/Polly/Bulkhead/AsyncBulkheadTResultSyntax.cs index e42c4ad4f49..f082cef5695 100644 --- a/src/Polly/Bulkhead/AsyncBulkheadTResultSyntax.cs +++ b/src/Polly/Bulkhead/AsyncBulkheadTResultSyntax.cs @@ -68,6 +68,6 @@ public static AsyncBulkheadPolicy BulkheadAsync(int maxParalle maxParallelization, maxQueuingActions, onBulkheadRejectedAsync - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/BulkheadEngine.cs b/src/Polly/Bulkhead/BulkheadEngine.cs index d3531621842..6a9827fdd72 100644 --- a/src/Polly/Bulkhead/BulkheadEngine.cs +++ b/src/Polly/Bulkhead/BulkheadEngine.cs @@ -18,7 +18,7 @@ internal static TResult Implementation( onBulkheadRejected(context); throw new BulkheadRejectedException(); } - + try { maxParallelizationSemaphore.Wait(cancellationToken); @@ -36,4 +36,4 @@ internal static TResult Implementation( maxQueuedActionsSemaphore.Release(); } } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/BulkheadPolicy.cs b/src/Polly/Bulkhead/BulkheadPolicy.cs index 9ec5cefea3b..7f7fa27e610 100644 --- a/src/Polly/Bulkhead/BulkheadPolicy.cs +++ b/src/Polly/Bulkhead/BulkheadPolicy.cs @@ -97,4 +97,4 @@ public void Dispose() _maxParallelizationSemaphore.Dispose(); _maxQueuedActionsSemaphore.Dispose(); } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/BulkheadRejectedException.cs b/src/Polly/Bulkhead/BulkheadRejectedException.cs index 82898dbfdb3..bc41a539580 100644 --- a/src/Polly/Bulkhead/BulkheadRejectedException.cs +++ b/src/Polly/Bulkhead/BulkheadRejectedException.cs @@ -3,49 +3,48 @@ using System.Runtime.Serialization; #endif -namespace Polly.Bulkhead +namespace Polly.Bulkhead; + +/// +/// Exception thrown when a bulkhead's semaphore and queue are full. +/// +#if NETSTANDARD2_0 +[Serializable] +#endif +public class BulkheadRejectedException : ExecutionRejectedException { /// - /// Exception thrown when a bulkhead's semaphore and queue are full. + /// Initializes a new instance of the class. /// -#if NETSTANDARD2_0 - [Serializable] -#endif - public class BulkheadRejectedException : ExecutionRejectedException + public BulkheadRejectedException() : this("The bulkhead semaphore and queue are full and execution was rejected.") { - /// - /// Initializes a new instance of the class. - /// - public BulkheadRejectedException() : this("The bulkhead semaphore and queue are full and execution was rejected.") - { - } + } - /// - /// Initializes a new instance of the class. - /// - /// The message. - public BulkheadRejectedException(string message) : base(message) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The message. + public BulkheadRejectedException(string message) : base(message) + { + } - /// - /// Initializes a new instance of the class. - /// - /// The message. - /// The inner exception. - public BulkheadRejectedException(string message, Exception innerException) : base(message, innerException) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner exception. + public BulkheadRejectedException(string message, Exception innerException) : base(message, innerException) + { + } #if NETSTANDARD2_0 - /// - /// Initializes a new instance of the class. - /// - /// The information. - /// The context. - protected BulkheadRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } -#endif + /// + /// Initializes a new instance of the class. + /// + /// The information. + /// The context. + protected BulkheadRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) + { } +#endif } diff --git a/src/Polly/Bulkhead/BulkheadSemaphoreFactory.cs b/src/Polly/Bulkhead/BulkheadSemaphoreFactory.cs index f1dc0671281..a217948f843 100644 --- a/src/Polly/Bulkhead/BulkheadSemaphoreFactory.cs +++ b/src/Polly/Bulkhead/BulkheadSemaphoreFactory.cs @@ -15,4 +15,4 @@ public static (SemaphoreSlim, SemaphoreSlim) CreateBulkheadSemaphores(int maxPar return (maxParallelizationSemaphore, maxQueuedActionsSemaphore); } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/BulkheadSyntax.cs b/src/Polly/Bulkhead/BulkheadSyntax.cs index a84fdb686c6..e166f0db2df 100644 --- a/src/Polly/Bulkhead/BulkheadSyntax.cs +++ b/src/Polly/Bulkhead/BulkheadSyntax.cs @@ -68,5 +68,5 @@ public static BulkheadPolicy Bulkhead(int maxParallelization, int maxQueuingActi onBulkheadRejected ); } - -} \ No newline at end of file + +} diff --git a/src/Polly/Bulkhead/BulkheadTResultSyntax.cs b/src/Polly/Bulkhead/BulkheadTResultSyntax.cs index b6e7e67e7d0..ab6afc1d49e 100644 --- a/src/Polly/Bulkhead/BulkheadTResultSyntax.cs +++ b/src/Polly/Bulkhead/BulkheadTResultSyntax.cs @@ -66,7 +66,7 @@ public static BulkheadPolicy Bulkhead(int maxParallelization, maxParallelization, maxQueuingActions, onBulkheadRejected - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/Bulkhead/IBulkheadPolicy.cs b/src/Polly/Bulkhead/IBulkheadPolicy.cs index df7113e54e9..7a48a593b6e 100644 --- a/src/Polly/Bulkhead/IBulkheadPolicy.cs +++ b/src/Polly/Bulkhead/IBulkheadPolicy.cs @@ -5,6 +5,7 @@ namespace Polly.Bulkhead; /// /// Defines properties and methods common to all bulkhead policies. /// + public interface IBulkheadPolicy : IsPolicy, IDisposable { /// @@ -23,5 +24,5 @@ public interface IBulkheadPolicy : IsPolicy, IDisposable /// public interface IBulkheadPolicy : IBulkheadPolicy { - -} \ No newline at end of file + +} diff --git a/src/Polly/Caching/AbsoluteTtl.cs b/src/Polly/Caching/AbsoluteTtl.cs index 5e5308c133e..e70c412c110 100644 --- a/src/Polly/Caching/AbsoluteTtl.cs +++ b/src/Polly/Caching/AbsoluteTtl.cs @@ -12,4 +12,4 @@ public class AbsoluteTtl : NonSlidingTtl /// /// The UTC point in time until which to consider the cache item valid. public AbsoluteTtl(DateTimeOffset absoluteExpirationTime) : base(absoluteExpirationTime) { } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/AsyncCacheEngine.cs b/src/Polly/Caching/AsyncCacheEngine.cs index 5bcfbf8252f..21fa07ac4e2 100644 --- a/src/Polly/Caching/AsyncCacheEngine.cs +++ b/src/Polly/Caching/AsyncCacheEngine.cs @@ -22,7 +22,7 @@ internal static async Task ImplementationAsync( { cancellationToken.ThrowIfCancellationRequested(); - var cacheKey = cacheKeyStrategy(context); + string cacheKey = cacheKeyStrategy(context); if (cacheKey == null) { return await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); @@ -50,9 +50,9 @@ internal static async Task ImplementationAsync( onCacheMiss(context, cacheKey); } - var result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); + TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); - var ttl = ttlStrategy.GetTtl(context, result); + Ttl ttl = ttlStrategy.GetTtl(context, result); if (ttl.Timespan > TimeSpan.Zero) { try @@ -68,4 +68,4 @@ internal static async Task ImplementationAsync( return result; } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/AsyncCachePolicy.cs b/src/Polly/Caching/AsyncCachePolicy.cs index d1945b1e8c0..e314f98d955 100644 --- a/src/Polly/Caching/AsyncCachePolicy.cs +++ b/src/Polly/Caching/AsyncCachePolicy.cs @@ -46,15 +46,18 @@ protected override Task ImplementationAsync( Func action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => + bool continueOnCapturedContext) + { // Pass-through/NOOP policy action, for void-returning executions through the cache policy. - action(context, cancellationToken); + return action(context, cancellationToken); + } /// [DebuggerStepThrough] protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncCacheEngine.ImplementationAsync( + bool continueOnCapturedContext) + { + return AsyncCacheEngine.ImplementationAsync( _asyncCacheProvider.AsyncFor(), _ttlStrategy.For(), _cacheKeyStrategy, @@ -67,6 +70,7 @@ protected override Task ImplementationAsync(Func @@ -109,8 +113,9 @@ internal AsyncCachePolicy( /// [DebuggerStepThrough] protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncCacheEngine.ImplementationAsync( + bool continueOnCapturedContext) + { + return AsyncCacheEngine.ImplementationAsync( _asyncCacheProvider, _ttlStrategy, _cacheKeyStrategy, @@ -123,4 +128,6 @@ protected override Task ImplementationAsync(Func CacheAsync( if (onCacheGet == null) throw new ArgumentNullException(nameof(onCacheGet)); if (onCacheMiss == null) throw new ArgumentNullException(nameof(onCacheMiss)); if (onCachePut == null) throw new ArgumentNullException(nameof(onCachePut)); - if (onCachePutError == null) throw new ArgumentNullException(nameof(onCachePutError)); + if (onCacheGetError == null) throw new ArgumentNullException(nameof(onCacheGetError)); if (onCachePutError == null) throw new ArgumentNullException(nameof(onCachePutError)); return new AsyncCachePolicy(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError); } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/AsyncGenericCacheProvider.cs b/src/Polly/Caching/AsyncGenericCacheProvider.cs index 1de776ac8ea..c4432d5c662 100644 --- a/src/Polly/Caching/AsyncGenericCacheProvider.cs +++ b/src/Polly/Caching/AsyncGenericCacheProvider.cs @@ -17,10 +17,10 @@ internal AsyncGenericCacheProvider(IAsyncCacheProvider nonGenericCacheProvider) async Task<(bool, TCacheFormat)> IAsyncCacheProvider.TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) { - (var cacheHit, var result) = await _wrappedCacheProvider.TryGetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); + (bool cacheHit, object result) = await _wrappedCacheProvider.TryGetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); return (cacheHit, (TCacheFormat)(result ?? default(TCacheFormat))); } Task IAsyncCacheProvider.PutAsync(string key, TCacheFormat value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext) => _wrappedCacheProvider.PutAsync(key, value, ttl, cancellationToken, continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/AsyncSerializingCacheProvider.cs b/src/Polly/Caching/AsyncSerializingCacheProvider.cs index f5c8a1111ff..e5dfe5e6683 100644 --- a/src/Polly/Caching/AsyncSerializingCacheProvider.cs +++ b/src/Polly/Caching/AsyncSerializingCacheProvider.cs @@ -38,7 +38,7 @@ public AsyncSerializingCacheProvider(IAsyncCacheProvider wrappedCac /// public async Task<(bool, object)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) { - (var cacheHit, var objectToDeserialize) = await _wrappedCacheProvider.TryGetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); + (bool cacheHit, TSerialized objectToDeserialize) = await _wrappedCacheProvider.TryGetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); return (cacheHit, cacheHit ? _serializer.Deserialize(objectToDeserialize) : null); } @@ -55,12 +55,12 @@ public async Task PutAsync(string key, object value, Ttl ttl, CancellationToken bool continueOnCapturedContext) { await _wrappedCacheProvider.PutAsync( - key, - _serializer.Serialize(value), - ttl, - cancellationToken, - continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext); + key, + _serializer.Serialize(value), + ttl, + cancellationToken, + continueOnCapturedContext + ).ConfigureAwait(continueOnCapturedContext); } } @@ -99,7 +99,7 @@ public AsyncSerializingCacheProvider(IAsyncCacheProvider wrappedCac /// public async Task<(bool, TResult)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) { - (var cacheHit, var objectToDeserialize) = await _wrappedCacheProvider.TryGetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); + (bool cacheHit, TSerialized objectToDeserialize) = await _wrappedCacheProvider.TryGetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); return (cacheHit, cacheHit ? _serializer.Deserialize(objectToDeserialize) : default); } @@ -116,11 +116,11 @@ public async Task PutAsync(string key, TResult value, Ttl ttl, CancellationToken bool continueOnCapturedContext) { await _wrappedCacheProvider.PutAsync( - key, - _serializer.Serialize(value), - ttl, - cancellationToken, - continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext); + key, + _serializer.Serialize(value), + ttl, + cancellationToken, + continueOnCapturedContext + ).ConfigureAwait(continueOnCapturedContext); } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/CacheEngine.cs b/src/Polly/Caching/CacheEngine.cs index ca4f173d652..cc1c1be654d 100644 --- a/src/Polly/Caching/CacheEngine.cs +++ b/src/Polly/Caching/CacheEngine.cs @@ -20,7 +20,7 @@ internal static TResult Implementation( { cancellationToken.ThrowIfCancellationRequested(); - var cacheKey = cacheKeyStrategy(context); + string cacheKey = cacheKeyStrategy(context); if (cacheKey == null) { return action(context, cancellationToken); @@ -48,9 +48,9 @@ internal static TResult Implementation( onCacheMiss(context, cacheKey); } - var result = action(context, cancellationToken); + TResult result = action(context, cancellationToken); - var ttl = ttlStrategy.GetTtl(context, result); + Ttl ttl = ttlStrategy.GetTtl(context, result); if (ttl.Timespan > TimeSpan.Zero) { try @@ -66,4 +66,4 @@ internal static TResult Implementation( return result; } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/CachePolicy.cs b/src/Polly/Caching/CachePolicy.cs index 5cdf255c640..f6a82a2e2ad 100644 --- a/src/Polly/Caching/CachePolicy.cs +++ b/src/Polly/Caching/CachePolicy.cs @@ -47,8 +47,9 @@ protected override void Implementation(Action action /// [DebuggerStepThrough] - protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => - CacheEngine.Implementation( + protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) + { + return CacheEngine.Implementation( _syncCacheProvider.For(), _ttlStrategy.For(), _cacheKeyStrategy, @@ -60,6 +61,7 @@ protected override TResult Implementation(Func @@ -113,4 +115,4 @@ protected override TResult Implementation(Func WithSerializer WithSerializer( this IAsyncCacheProvider cacheProvider, ICacheItemSerializer serializer) => new AsyncSerializingCacheProvider(cacheProvider, serializer); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/CacheSyntax.cs b/src/Polly/Caching/CacheSyntax.cs index 5910e9c1d05..a669b1e35b4 100644 --- a/src/Polly/Caching/CacheSyntax.cs +++ b/src/Polly/Caching/CacheSyntax.cs @@ -252,7 +252,7 @@ public static CachePolicy Cache( Action onCachePut, Action onCacheGetError, Action onCachePutError) - => Cache(cacheProvider, ttlStrategy, cacheKeyStrategy.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError); + => Cache(cacheProvider, ttlStrategy, cacheKeyStrategy.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError); /// /// Builds a that will function like a result cache for delegate executions returning a result. @@ -331,9 +331,9 @@ public static CachePolicy Cache( if (onCacheGet == null) throw new ArgumentNullException(nameof(onCacheGet)); if (onCacheMiss == null) throw new ArgumentNullException(nameof(onCacheMiss)); if (onCachePut == null) throw new ArgumentNullException(nameof(onCachePut)); - if (onCachePutError == null) throw new ArgumentNullException(nameof(onCachePutError)); + if (onCacheGetError == null) throw new ArgumentNullException(nameof(onCacheGetError)); if (onCachePutError == null) throw new ArgumentNullException(nameof(onCachePutError)); return new CachePolicy(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError); } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/CacheTResultSyntax.cs b/src/Polly/Caching/CacheTResultSyntax.cs index 957d2f74bb8..fe09af2fea1 100644 --- a/src/Polly/Caching/CacheTResultSyntax.cs +++ b/src/Polly/Caching/CacheTResultSyntax.cs @@ -741,7 +741,7 @@ public static CachePolicy Cache( Action onCachePut, Action onCacheGetError, Action onCachePutError) - => Cache(cacheProvider, new RelativeTtl(ttl), cacheKeyStrategy, onCacheGet, onCacheMiss, + => Cache(cacheProvider, new RelativeTtl(ttl), cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError); /// @@ -819,9 +819,9 @@ public static CachePolicy Cache( if (onCacheGet == null) throw new ArgumentNullException(nameof(onCacheGet)); if (onCacheMiss == null) throw new ArgumentNullException(nameof(onCacheMiss)); if (onCachePut == null) throw new ArgumentNullException(nameof(onCachePut)); - if (onCachePutError == null) throw new ArgumentNullException(nameof(onCachePutError)); + if (onCacheGetError == null) throw new ArgumentNullException(nameof(onCacheGetError)); if (onCachePutError == null) throw new ArgumentNullException(nameof(onCachePutError)); return new CachePolicy(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError); } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/ContextualTtl.cs b/src/Polly/Caching/ContextualTtl.cs index d9f5a46b58b..e36e6d09d98 100644 --- a/src/Polly/Caching/ContextualTtl.cs +++ b/src/Polly/Caching/ContextualTtl.cs @@ -30,9 +30,9 @@ public Ttl GetTtl(Context context, object result) { if (!context.ContainsKey(TimeSpanKey)) return _noTtl; - var sliding = false; + bool sliding = false; - if (context.TryGetValue(SlidingExpirationKey, out var objValue)) + if (context.TryGetValue(SlidingExpirationKey, out object objValue)) { sliding = objValue as bool? ?? false; } @@ -40,4 +40,4 @@ public Ttl GetTtl(Context context, object result) return new Ttl(context[TimeSpanKey] as TimeSpan? ?? TimeSpan.Zero, sliding); } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/DefaultCacheKeyStrategy.cs b/src/Polly/Caching/DefaultCacheKeyStrategy.cs index 1c2b324664b..09a4ff88c85 100644 --- a/src/Polly/Caching/DefaultCacheKeyStrategy.cs +++ b/src/Polly/Caching/DefaultCacheKeyStrategy.cs @@ -16,4 +16,4 @@ public class DefaultCacheKeyStrategy : ICacheKeyStrategy /// Gets an instance of the . /// public static readonly ICacheKeyStrategy Instance = new DefaultCacheKeyStrategy(); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/GenericCacheProvider.cs b/src/Polly/Caching/GenericCacheProvider.cs index 4c0fdba0d90..c4f1498668e 100644 --- a/src/Polly/Caching/GenericCacheProvider.cs +++ b/src/Polly/Caching/GenericCacheProvider.cs @@ -15,10 +15,10 @@ internal GenericCacheProvider(ISyncCacheProvider nonGenericCacheProvider) (bool, TCacheFormat) ISyncCacheProvider.TryGet(string key) { - (var cacheHit, var result) = _wrappedCacheProvider.TryGet(key); + (bool cacheHit, object result) = _wrappedCacheProvider.TryGet(key); return (cacheHit, (TCacheFormat) (result ?? default(TCacheFormat))); } void ISyncCacheProvider.Put(string key, TCacheFormat value, Ttl ttl) => _wrappedCacheProvider.Put(key, value, ttl); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/GenericTtlStrategy.cs b/src/Polly/Caching/GenericTtlStrategy.cs index 44a623534e7..d0929a207e3 100644 --- a/src/Polly/Caching/GenericTtlStrategy.cs +++ b/src/Polly/Caching/GenericTtlStrategy.cs @@ -19,4 +19,4 @@ internal GenericTtlStrategy(ITtlStrategy ttlStrategy) /// The execution result. /// A representing the remaining Ttl of the cached item. public Ttl GetTtl(Context context, TResult result) => _wrappedTtlStrategy.GetTtl(context, result); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/IAsyncCacheProvider.cs b/src/Polly/Caching/IAsyncCacheProvider.cs index 8ebaf4aae6a..be1c9df86d9 100644 --- a/src/Polly/Caching/IAsyncCacheProvider.cs +++ b/src/Polly/Caching/IAsyncCacheProvider.cs @@ -59,4 +59,4 @@ public interface IAsyncCacheProvider /// Whether async calls should continue on a captured synchronization context.Note: if the underlying cache's async API does not support controlling whether to continue on a captured context, async Policy executions with continueOnCapturedContext == true cannot be guaranteed to remain on the captured context. /// A which completes when the value has been cached. Task PutAsync(string key, TResult value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/ICacheItemSerializer.cs b/src/Polly/Caching/ICacheItemSerializer.cs index 48e8f68e024..1c36d393276 100644 --- a/src/Polly/Caching/ICacheItemSerializer.cs +++ b/src/Polly/Caching/ICacheItemSerializer.cs @@ -21,4 +21,4 @@ public interface ICacheItemSerializer /// The deserialized object TResult Deserialize(TSerialized objectToDeserialize); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/ICacheKeyStrategy.cs b/src/Polly/Caching/ICacheKeyStrategy.cs index b81b9bc783f..ad29dedcec9 100644 --- a/src/Polly/Caching/ICacheKeyStrategy.cs +++ b/src/Polly/Caching/ICacheKeyStrategy.cs @@ -11,4 +11,4 @@ public interface ICacheKeyStrategy /// The execution context. /// The cache key string GetCacheKey(Context context); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/ICachePolicy.cs b/src/Polly/Caching/ICachePolicy.cs index 009fa234019..3e9cff77b85 100644 --- a/src/Polly/Caching/ICachePolicy.cs +++ b/src/Polly/Caching/ICachePolicy.cs @@ -3,6 +3,7 @@ /// /// Defines properties and methods common to all Cache policies. /// + public interface ICachePolicy : IsPolicy { } @@ -12,4 +13,4 @@ public interface ICachePolicy : IsPolicy /// public interface ICachePolicy : ICachePolicy { -} \ No newline at end of file +} diff --git a/src/Polly/Caching/ISyncCacheProvider.cs b/src/Polly/Caching/ISyncCacheProvider.cs index 7500f0f1c5d..17a6b0b1ba5 100644 --- a/src/Polly/Caching/ISyncCacheProvider.cs +++ b/src/Polly/Caching/ISyncCacheProvider.cs @@ -46,4 +46,4 @@ public interface ISyncCacheProvider /// The value to put into the cache. /// The time-to-live for the cache entry. void Put(string key, TResult value, Ttl ttl); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/ITtlStrategy.cs b/src/Polly/Caching/ITtlStrategy.cs index 929b5fa26df..f4cf30357f1 100644 --- a/src/Polly/Caching/ITtlStrategy.cs +++ b/src/Polly/Caching/ITtlStrategy.cs @@ -5,7 +5,7 @@ /// public interface ITtlStrategy : ITtlStrategy { - + } /// @@ -20,4 +20,4 @@ public interface ITtlStrategy /// The execution result. /// A representing the remaining Ttl of the cached item. Ttl GetTtl(Context context, TResult result); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/NonSlidingTtl.cs b/src/Polly/Caching/NonSlidingTtl.cs index c96e3b9afcd..85778163307 100644 --- a/src/Polly/Caching/NonSlidingTtl.cs +++ b/src/Polly/Caching/NonSlidingTtl.cs @@ -28,8 +28,8 @@ protected NonSlidingTtl(DateTimeOffset absoluteExpirationTime) /// A representing the remaining Ttl of the cached item. public Ttl GetTtl(Context context, object result) { - var untilPointInTime = absoluteExpirationTime.Subtract(SystemClock.DateTimeOffsetUtcNow()); - var remaining = untilPointInTime > TimeSpan.Zero ? untilPointInTime : TimeSpan.Zero; + TimeSpan untilPointInTime = absoluteExpirationTime.Subtract(SystemClock.DateTimeOffsetUtcNow()); + TimeSpan remaining = untilPointInTime > TimeSpan.Zero ? untilPointInTime : TimeSpan.Zero; return new Ttl(remaining, false); } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/RelativeTtl.cs b/src/Polly/Caching/RelativeTtl.cs index 6b8bb50bcbb..f5d118303da 100644 --- a/src/Polly/Caching/RelativeTtl.cs +++ b/src/Polly/Caching/RelativeTtl.cs @@ -27,4 +27,4 @@ public RelativeTtl(TimeSpan ttl) /// The execution result. /// A representing the remaining Ttl of the cached item. public Ttl GetTtl(Context context, object result) => new Ttl(ttl); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/ResultTtl.cs b/src/Polly/Caching/ResultTtl.cs index f5f7567988b..514ffc54cd4 100644 --- a/src/Polly/Caching/ResultTtl.cs +++ b/src/Polly/Caching/ResultTtl.cs @@ -35,4 +35,4 @@ public ResultTtl(Func ttlFunc) /// A representing the remaining Ttl of the cached item. public Ttl GetTtl(Context context, TResult result) => _ttlFunc(context, result); -} \ No newline at end of file +} diff --git a/src/Polly/Caching/SerializingCacheProvider.cs b/src/Polly/Caching/SerializingCacheProvider.cs index 5a9571fb747..e3f6f9fd915 100644 --- a/src/Polly/Caching/SerializingCacheProvider.cs +++ b/src/Polly/Caching/SerializingCacheProvider.cs @@ -34,7 +34,7 @@ public SerializingCacheProvider(ISyncCacheProvider wrappedCacheProv /// public (bool, object) TryGet(string key) { - (var cacheHit, var objectToDeserialize) = _wrappedCacheProvider.TryGet(key); + (bool cacheHit, TSerialized objectToDeserialize) = _wrappedCacheProvider.TryGet(key); return (cacheHit, cacheHit ? _serializer.Deserialize(objectToDeserialize) : null); } @@ -84,7 +84,7 @@ public SerializingCacheProvider(ISyncCacheProvider wrappedCacheProv /// public (bool, TResult) TryGet(string key) { - (var cacheHit, var objectToDeserialize) = _wrappedCacheProvider.TryGet(key); + (bool cacheHit, TSerialized objectToDeserialize) = _wrappedCacheProvider.TryGet(key); return (cacheHit, cacheHit ? _serializer.Deserialize(objectToDeserialize) : default); } @@ -99,4 +99,4 @@ public void Put(string key, TResult value, Ttl ttl) _wrappedCacheProvider.Put(key, _serializer.Serialize(value), ttl); } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/SlidingTtl.cs b/src/Polly/Caching/SlidingTtl.cs index 78ca9cae16d..de4df8586af 100644 --- a/src/Polly/Caching/SlidingTtl.cs +++ b/src/Polly/Caching/SlidingTtl.cs @@ -5,6 +5,7 @@ namespace Polly.Caching; /// /// Defines a ttl strategy which will cache items with a sliding ttl. /// + public class SlidingTtl : ITtlStrategy { private readonly Ttl ttl; @@ -28,4 +29,4 @@ public SlidingTtl(TimeSpan slidingTtl) /// A representing the remaining Ttl of the cached item. public Ttl GetTtl(Context context, object result) => ttl; -} \ No newline at end of file +} diff --git a/src/Polly/Caching/Ttl.cs b/src/Polly/Caching/Ttl.cs index 214704e9066..7dd10fcbf87 100644 --- a/src/Polly/Caching/Ttl.cs +++ b/src/Polly/Caching/Ttl.cs @@ -36,4 +36,4 @@ public Ttl(TimeSpan timeSpan, bool slidingExpiration) Timespan = timeSpan; SlidingExpiration = slidingExpiration; } -} \ No newline at end of file +} diff --git a/src/Polly/Caching/TtlStrategyExtensions.cs b/src/Polly/Caching/TtlStrategyExtensions.cs index 58a51688429..ed0a7e0c23e 100644 --- a/src/Polly/Caching/TtlStrategyExtensions.cs +++ b/src/Polly/Caching/TtlStrategyExtensions.cs @@ -13,4 +13,4 @@ internal static class TtlStrategyExtensions /// ITtlStrategy{TCacheFormat}. internal static ITtlStrategy For(this ITtlStrategy ttlStrategy) => new GenericTtlStrategy(ttlStrategy); -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/AdvancedCircuitBreakerSyntax.cs b/src/Polly/CircuitBreaker/AdvancedCircuitBreakerSyntax.cs index aad811522b3..9e4cd686179 100644 --- a/src/Polly/CircuitBreaker/AdvancedCircuitBreakerSyntax.cs +++ b/src/Polly/CircuitBreaker/AdvancedCircuitBreakerSyntax.cs @@ -35,14 +35,14 @@ public static class AdvancedCircuitBreakerSyntax public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak) { Action doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.AdvancedCircuitBreaker( failureThreshold, samplingDuration, minimumThroughput, durationOfBreak, doNothingOnBreak, doNothingOnReset - ); + ); } /// @@ -77,7 +77,7 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder pol durationOfBreak, (exception, timespan, _) => onBreak(exception, timespan), _ => onReset() - ); + ); /// /// The circuit will break if, within any timeslice of duration , the proportion of actions resulting in a handled exception exceeds , provided also that the number of actions through the circuit in the timeslice is at least . @@ -107,13 +107,13 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder pol /// onReset public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.AdvancedCircuitBreaker(failureThreshold, samplingDuration, minimumThroughput, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -151,7 +151,7 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder pol (exception, timespan, _) => onBreak(exception, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -245,6 +245,6 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder pol return new CircuitBreakerPolicy( policyBuilder, breakerController - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/AdvancedCircuitBreakerTResultSyntax.cs b/src/Polly/CircuitBreaker/AdvancedCircuitBreakerTResultSyntax.cs index b6b2d21d1db..869f6d6a3ae 100644 --- a/src/Polly/CircuitBreaker/AdvancedCircuitBreakerTResultSyntax.cs +++ b/src/Polly/CircuitBreaker/AdvancedCircuitBreakerTResultSyntax.cs @@ -35,14 +35,14 @@ public static class AdvancedCircuitBreakerTResultSyntax public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak) { Action, TimeSpan> doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.AdvancedCircuitBreaker( failureThreshold, samplingDuration, minimumThroughput, durationOfBreak, doNothingOnBreak, doNothingOnReset - ); + ); } /// @@ -77,7 +77,7 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this durationOfBreak, (outcome, timespan, _) => onBreak(outcome, timespan), _ => onReset() - ); + ); /// /// The circuit will break if, within any timeslice of duration , the proportion of actions resulting in a handled exception or result exceeds , provided also that the number of actions through the circuit in the timeslice is at least . @@ -107,13 +107,13 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this /// onReset public static CircuitBreakerPolicy AdvancedCircuitBreaker(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action, TimeSpan, Context> onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.AdvancedCircuitBreaker(failureThreshold, samplingDuration, minimumThroughput, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -151,7 +151,7 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this (outcome, timespan, _) => onBreak(outcome, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -247,6 +247,6 @@ public static CircuitBreakerPolicy AdvancedCircuitBreaker(this return new CircuitBreakerPolicy( policyBuilder, breakerController - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/AdvancedCircuitController.cs b/src/Polly/CircuitBreaker/AdvancedCircuitController.cs index 27e45aacd06..e40bf28f3df 100644 --- a/src/Polly/CircuitBreaker/AdvancedCircuitController.cs +++ b/src/Polly/CircuitBreaker/AdvancedCircuitController.cs @@ -20,7 +20,7 @@ public AdvancedCircuitController( Action, CircuitState, TimeSpan, Context> onBreak, Action onReset, Action onHalfOpen - ) : base(durationOfBreak, onBreak, onReset, onHalfOpen) + ) : base(durationOfBreak, onBreak, onReset, onHalfOpen) { _metrics = samplingDuration.Ticks < ResolutionOfCircuitTimer * NumberOfWindows ? (IHealthMetrics)new SingleHealthMetrics(samplingDuration) @@ -84,7 +84,7 @@ public override void OnActionFailure(DelegateResult outcome, Context co _metrics.IncrementFailure_NeedsLock(); var healthCount = _metrics.GetHealthCount_NeedsLock(); - var throughput = healthCount.Total; + int throughput = healthCount.Total; if (throughput >= _minimumThroughput && ((double)healthCount.Failures) / throughput >= _failureThreshold) { Break_NeedsLock(context); @@ -101,4 +101,4 @@ public override void OnActionFailure(DelegateResult outcome, Context co } } } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerSyntax.cs b/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerSyntax.cs index 073864a72d8..ffc88a12343 100644 --- a/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerSyntax.cs +++ b/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerSyntax.cs @@ -36,14 +36,14 @@ public static class AsyncAdvancedCircuitBreakerSyntax public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak) { Action doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.AdvancedCircuitBreakerAsync( - failureThreshold, samplingDuration, minimumThroughput, - durationOfBreak, - doNothingOnBreak, - doNothingOnReset - ); + failureThreshold, samplingDuration, minimumThroughput, + durationOfBreak, + doNothingOnBreak, + doNothingOnReset + ); } /// @@ -79,7 +79,7 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyB durationOfBreak, (exception, timespan, _) => onBreak(exception, timespan), _ => onReset() - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -110,14 +110,14 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyB /// onReset public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.AdvancedCircuitBreakerAsync( failureThreshold, samplingDuration, minimumThroughput, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -155,7 +155,7 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyB (exception, timespan, _) => onBreak(exception, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -251,4 +251,4 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyB breakerController ); } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerTResultSyntax.cs b/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerTResultSyntax.cs index 4dcb9879877..1f8472b5846 100644 --- a/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerTResultSyntax.cs +++ b/src/Polly/CircuitBreaker/AsyncAdvancedCircuitBreakerTResultSyntax.cs @@ -35,14 +35,14 @@ public static class AsyncAdvancedCircuitBreakerTResultSyntax public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak) { Action, TimeSpan> doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.AdvancedCircuitBreakerAsync( - failureThreshold, samplingDuration, minimumThroughput, - durationOfBreak, - doNothingOnBreak, - doNothingOnReset - ); + failureThreshold, samplingDuration, minimumThroughput, + durationOfBreak, + doNothingOnBreak, + doNothingOnReset + ); } /// @@ -78,7 +78,7 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync onBreak(outcome, timespan), _ => onReset() - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -109,14 +109,14 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsynconReset public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync(this PolicyBuilder policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action, TimeSpan, Context> onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.AdvancedCircuitBreakerAsync( failureThreshold, samplingDuration, minimumThroughput, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -154,7 +154,7 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync onBreak(outcome, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -250,4 +250,4 @@ public static AsyncCircuitBreakerPolicy AdvancedCircuitBreakerAsync ImplementationAsync( try { - var result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); + TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); if (shouldHandleResultPredicates.AnyMatch(result)) { @@ -37,7 +37,7 @@ internal static async Task ImplementationAsync( } catch (Exception ex) { - var handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; @@ -49,4 +49,5 @@ internal static async Task ImplementationAsync( throw; } } -} \ No newline at end of file +} + diff --git a/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs b/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs index 6f6de525714..ec179516f23 100644 --- a/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs +++ b/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs @@ -16,7 +16,7 @@ public class AsyncCircuitBreakerPolicy : AsyncPolicy, ICircuitBreakerPolicy internal AsyncCircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) + ) : base(policyBuilder) { _breakerController = breakerController; } @@ -70,7 +70,7 @@ public class AsyncCircuitBreakerPolicy : AsyncPolicy, ICircuit internal AsyncCircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) + ) : base(policyBuilder) { _breakerController = breakerController; } @@ -114,4 +114,4 @@ protected override Task ImplementationAsync(Func doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.CircuitBreakerAsync( - exceptionsAllowedBeforeBreaking, - durationOfBreak, - doNothingOnBreak, - doNothingOnReset - ); + exceptionsAllowedBeforeBreaking, + durationOfBreak, + doNothingOnBreak, + doNothingOnReset + ); } /// @@ -68,7 +68,7 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(this PolicyBuilder p durationOfBreak, (exception, timespan, _) => onBreak(exception, timespan), _ => onReset() - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -94,14 +94,14 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(this PolicyBuilder p /// onReset public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(this PolicyBuilder policyBuilder, int exceptionsAllowedBeforeBreaking, TimeSpan durationOfBreak, Action onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.CircuitBreakerAsync( exceptionsAllowedBeforeBreaking, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -134,7 +134,7 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(this PolicyBuilder p (exception, timespan, _) => onBreak(exception, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -213,4 +213,5 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(this PolicyBuilder p breakerController ); } -} \ No newline at end of file +} + diff --git a/src/Polly/CircuitBreaker/AsyncCircuitBreakerTResultSyntax.cs b/src/Polly/CircuitBreaker/AsyncCircuitBreakerTResultSyntax.cs index d181b12ac94..a25361f3ff3 100644 --- a/src/Polly/CircuitBreaker/AsyncCircuitBreakerTResultSyntax.cs +++ b/src/Polly/CircuitBreaker/AsyncCircuitBreakerTResultSyntax.cs @@ -29,14 +29,14 @@ public static class AsyncCircuitBreakerTResultSyntax public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(this PolicyBuilder policyBuilder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) { Action, TimeSpan> doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.CircuitBreakerAsync( - handledEventsAllowedBeforeBreaking, - durationOfBreak, - doNothingOnBreak, - doNothingOnReset - ); + handledEventsAllowedBeforeBreaking, + durationOfBreak, + doNothingOnBreak, + doNothingOnReset + ); } /// @@ -67,7 +67,7 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(th durationOfBreak, (outcome, timespan, _) => onBreak(outcome, timespan), _ => onReset() - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -93,14 +93,14 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(th /// onReset public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(this PolicyBuilder policyBuilder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak, Action, TimeSpan, Context> onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.CircuitBreakerAsync( handledEventsAllowedBeforeBreaking, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -133,7 +133,7 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(th (outcome, timespan, _) => onBreak(outcome, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -212,4 +212,5 @@ public static AsyncCircuitBreakerPolicy CircuitBreakerAsync(th breakerController ); } -} \ No newline at end of file +} + diff --git a/src/Polly/CircuitBreaker/BrokenCircuitException.cs b/src/Polly/CircuitBreaker/BrokenCircuitException.cs index ef2e35c6bd5..61974b58f8d 100644 --- a/src/Polly/CircuitBreaker/BrokenCircuitException.cs +++ b/src/Polly/CircuitBreaker/BrokenCircuitException.cs @@ -4,96 +4,95 @@ using System.Runtime.Serialization; #endif -namespace Polly.CircuitBreaker +namespace Polly.CircuitBreaker; + +/// +/// Exception thrown when a circuit is broken. +/// +#if NETSTANDARD2_0 +[Serializable] +#endif +public class BrokenCircuitException : ExecutionRejectedException { /// - /// Exception thrown when a circuit is broken. + /// Initializes a new instance of the class. /// -#if NETSTANDARD2_0 - [Serializable] -#endif - public class BrokenCircuitException : ExecutionRejectedException + public BrokenCircuitException() { - /// - /// Initializes a new instance of the class. - /// - public BrokenCircuitException() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - public BrokenCircuitException(string message) : base(message) - { - } + } - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - /// The inner exception. - public BrokenCircuitException(string message, Exception inner) : base(message, inner) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The message that describes the error. + public BrokenCircuitException(string message) : base(message) + { + } -#if NETSTANDARD2_0 - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - protected BrokenCircuitException( - SerializationInfo info, - StreamingContext context) : base(info, context) - { - } -#endif + /// + /// Initializes a new instance of the class. + /// + /// The message that describes the error. + /// The inner exception. + public BrokenCircuitException(string message, Exception inner) : base(message, inner) + { } +#if NETSTANDARD2_0 /// - /// Exception thrown when a circuit is broken. + /// Initializes a new instance of the class. /// - /// The type of returned results being handled by the policy. + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected BrokenCircuitException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { + } +#endif +} + +/// +/// Exception thrown when a circuit is broken. +/// +/// The type of returned results being handled by the policy. #if NETSTANDARD2_0 - [Serializable] +[Serializable] #endif - public class BrokenCircuitException : BrokenCircuitException - { - private readonly TResult result; +public class BrokenCircuitException : BrokenCircuitException +{ + private readonly TResult result; - /// - /// Initializes a new instance of the class. - /// - /// The result which caused the circuit to break. - public BrokenCircuitException(TResult result) : base() - => this.result = result; + /// + /// Initializes a new instance of the class. + /// + /// The result which caused the circuit to break. + public BrokenCircuitException(TResult result) : base() + => this.result = result; - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - /// The result which caused the circuit to break. - public BrokenCircuitException(string message, TResult result) : base(message) - => this.result = result; + /// + /// Initializes a new instance of the class. + /// + /// The message that describes the error. + /// The result which caused the circuit to break. + public BrokenCircuitException(string message, TResult result) : base(message) + => this.result = result; - /// - /// The result value which was considered a handled fault, by the policy. - /// - public TResult Result => result; + /// + /// The result value which was considered a handled fault, by the policy. + /// + public TResult Result { get => result; } #if NETSTANDARD2_0 - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - protected BrokenCircuitException( - SerializationInfo info, - StreamingContext context) : base(info, context) - { - } -#endif + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected BrokenCircuitException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { } -} \ No newline at end of file +#endif +} diff --git a/src/Polly/CircuitBreaker/CircuitBreakerEngine.cs b/src/Polly/CircuitBreaker/CircuitBreakerEngine.cs index 9e637caf60c..ad34434ee78 100644 --- a/src/Polly/CircuitBreaker/CircuitBreakerEngine.cs +++ b/src/Polly/CircuitBreaker/CircuitBreakerEngine.cs @@ -20,7 +20,7 @@ internal static TResult Implementation( try { - var result = action(context, cancellationToken); + TResult result = action(context, cancellationToken); if (shouldHandleResultPredicates.AnyMatch(result)) { @@ -35,7 +35,7 @@ internal static TResult Implementation( } catch (Exception ex) { - var handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; @@ -50,4 +50,4 @@ internal static TResult Implementation( throw; } } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs b/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs index 0b45a7f7d96..af202e9663a 100644 --- a/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs +++ b/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs @@ -15,7 +15,7 @@ public class CircuitBreakerPolicy : Policy, ICircuitBreakerPolicy internal CircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) + ) : base(policyBuilder) => _breakerController = breakerController; /// @@ -65,7 +65,7 @@ public class CircuitBreakerPolicy : Policy, ICircuitBreakerPol internal CircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) + ) : base(policyBuilder) => _breakerController = breakerController; /// @@ -105,4 +105,4 @@ protected override TResult Implementation(Func doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.CircuitBreaker - (exceptionsAllowedBeforeBreaking, + (exceptionsAllowedBeforeBreaking, durationOfBreak, doNothingOnBreak, doNothingOnReset - ); + ); } /// @@ -70,7 +70,7 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyBuilder policyBuild durationOfBreak, (exception, timespan, _) => onBreak(exception, timespan), _ => onReset() - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -96,13 +96,13 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyBuilder policyBuild /// onReset public static CircuitBreakerPolicy CircuitBreaker(this PolicyBuilder policyBuilder, int exceptionsAllowedBeforeBreaking, TimeSpan durationOfBreak, Action onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.CircuitBreaker(exceptionsAllowedBeforeBreaking, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -135,7 +135,7 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyBuilder policyBuild (exception, timespan, _) => onBreak(exception, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -212,6 +212,6 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyBuilder policyBuild return new CircuitBreakerPolicy( policyBuilder, breakerController - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/CircuitBreakerTResultSyntax.cs b/src/Polly/CircuitBreaker/CircuitBreakerTResultSyntax.cs index 0694b5a9f26..524c1f22222 100644 --- a/src/Polly/CircuitBreaker/CircuitBreakerTResultSyntax.cs +++ b/src/Polly/CircuitBreaker/CircuitBreakerTResultSyntax.cs @@ -31,14 +31,14 @@ public static class CircuitBreakerTResultSyntax public static CircuitBreakerPolicy CircuitBreaker(this PolicyBuilder policyBuilder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) { Action, TimeSpan> doNothingOnBreak = (_, _) => { }; - var doNothingOnReset = () => { }; + Action doNothingOnReset = () => { }; return policyBuilder.CircuitBreaker - (handledEventsAllowedBeforeBreaking, + (handledEventsAllowedBeforeBreaking, durationOfBreak, doNothingOnBreak, doNothingOnReset - ); + ); } /// @@ -69,7 +69,7 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyB durationOfBreak, (outcome, timespan, _) => onBreak(outcome, timespan), _ => onReset() - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -95,13 +95,13 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyB /// onReset public static CircuitBreakerPolicy CircuitBreaker(this PolicyBuilder policyBuilder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak, Action, TimeSpan, Context> onBreak, Action onReset) { - var doNothingOnHalfOpen = () => { }; + Action doNothingOnHalfOpen = () => { }; return policyBuilder.CircuitBreaker(handledEventsAllowedBeforeBreaking, durationOfBreak, onBreak, onReset, doNothingOnHalfOpen - ); + ); } /// @@ -134,7 +134,7 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyB (outcome, timespan, _) => onBreak(outcome, timespan), _ => onReset(), onHalfOpen - ); + ); /// /// Builds a that will function like a Circuit Breaker. @@ -211,6 +211,6 @@ public static CircuitBreakerPolicy CircuitBreaker(this PolicyB return new CircuitBreakerPolicy( policyBuilder, breakerController - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/CircuitState.cs b/src/Polly/CircuitBreaker/CircuitState.cs index c75762dfa9c..177644b90b7 100644 --- a/src/Polly/CircuitBreaker/CircuitState.cs +++ b/src/Polly/CircuitBreaker/CircuitState.cs @@ -21,4 +21,4 @@ public enum CircuitState /// Isolated - When the circuit has been placed into a fixed open state by a call to . This isolates the circuit manually, blocking execution of all actions until a call to is made. /// Isolated -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/CircuitStateController.cs b/src/Polly/CircuitBreaker/CircuitStateController.cs index da937a5e731..8a6b148299f 100644 --- a/src/Polly/CircuitBreaker/CircuitStateController.cs +++ b/src/Polly/CircuitBreaker/CircuitStateController.cs @@ -18,9 +18,9 @@ internal abstract class CircuitStateController : ICircuitController, CircuitState, TimeSpan, Context> onBreak, - Action onReset, + TimeSpan durationOfBreak, + Action, CircuitState, TimeSpan, Context> onBreak, + Action onReset, Action onHalfOpen) { _durationOfBreak = durationOfBreak; @@ -76,8 +76,13 @@ public TResult LastHandledResult } } - protected bool IsInAutomatedBreak_NeedsLock => - SystemClock.UtcNow().Ticks < _blockedTill; + protected bool IsInAutomatedBreak_NeedsLock + { + get + { + return SystemClock.UtcNow().Ticks < _blockedTill; + } + } public void Isolate() { @@ -93,7 +98,7 @@ public void Isolate() private void BreakFor_NeedsLock(TimeSpan durationOfBreak, Context context) { - var willDurationTakeUsPastDateTimeMaxValue = durationOfBreak > DateTime.MaxValue - SystemClock.UtcNow(); + bool willDurationTakeUsPastDateTimeMaxValue = durationOfBreak > DateTime.MaxValue - SystemClock.UtcNow(); _blockedTill = willDurationTakeUsPastDateTimeMaxValue ? DateTime.MaxValue.Ticks : (SystemClock.UtcNow() + durationOfBreak).Ticks; @@ -111,7 +116,7 @@ protected void ResetInternal_NeedsLock(Context context) _blockedTill = DateTime.MinValue.Ticks; _lastOutcome = null; - var priorState = _circuitState; + CircuitState priorState = _circuitState; _circuitState = CircuitState.Closed; if (priorState != CircuitState.Closed) { @@ -121,7 +126,7 @@ protected void ResetInternal_NeedsLock(Context context) protected bool PermitHalfOpenCircuitTest() { - var currentlyBlockedUntil = _blockedTill; + long currentlyBlockedUntil = _blockedTill; if (SystemClock.UtcNow().Ticks >= currentlyBlockedUntil) { // It's time to permit a / another trial call in the half-open state ... @@ -172,4 +177,5 @@ public void OnActionPreExecute() public abstract void OnActionFailure(DelegateResult outcome, Context context); public abstract void OnCircuitReset(Context context); -} \ No newline at end of file +} + diff --git a/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs b/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs index f1c8b9dd15d..ee93a6ef664 100644 --- a/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs +++ b/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs @@ -14,7 +14,7 @@ public ConsecutiveCountCircuitController( Action, CircuitState, TimeSpan, Context> onBreak, Action onReset, Action onHalfOpen - ) : base(durationOfBreak, onBreak, onReset, onHalfOpen) + ) : base(durationOfBreak, onBreak, onReset, onHalfOpen) { _exceptionsAllowedBeforeBreaking = exceptionsAllowedBeforeBreaking; } @@ -82,4 +82,4 @@ public override void OnActionFailure(DelegateResult outcome, Context co } } } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/HealthCount.cs b/src/Polly/CircuitBreaker/HealthCount.cs index 093184593e5..8a6f7ea46f0 100644 --- a/src/Polly/CircuitBreaker/HealthCount.cs +++ b/src/Polly/CircuitBreaker/HealthCount.cs @@ -6,7 +6,7 @@ internal class HealthCount public int Failures { get; set; } - public int Total => Successes + Failures; + public int Total { get { return Successes + Failures; } } public long StartedAt { get; set; } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/ICircuitBreakerPolicy.cs b/src/Polly/CircuitBreaker/ICircuitBreakerPolicy.cs index 6532faf1cc5..73adf6de2e6 100644 --- a/src/Polly/CircuitBreaker/ICircuitBreakerPolicy.cs +++ b/src/Polly/CircuitBreaker/ICircuitBreakerPolicy.cs @@ -39,4 +39,4 @@ public interface ICircuitBreakerPolicy : ICircuitBreakerPolicy /// This will be default() if no results have been handled by the circuit-breaker since the circuit last closed, or if the last event handled by the circuit was an exception. /// TResult LastHandledResult { get; } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/ICircuitController.cs b/src/Polly/CircuitBreaker/ICircuitController.cs index 494611e6c82..ffa28137c23 100644 --- a/src/Polly/CircuitBreaker/ICircuitController.cs +++ b/src/Polly/CircuitBreaker/ICircuitController.cs @@ -13,4 +13,4 @@ internal interface ICircuitController void OnActionPreExecute(); void OnActionSuccess(Context context); void OnActionFailure(DelegateResult outcome, Context context); -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/IHealthMetrics.cs b/src/Polly/CircuitBreaker/IHealthMetrics.cs index 14f1495ced1..0df590f49ee 100644 --- a/src/Polly/CircuitBreaker/IHealthMetrics.cs +++ b/src/Polly/CircuitBreaker/IHealthMetrics.cs @@ -8,4 +8,4 @@ internal interface IHealthMetrics void Reset_NeedsLock(); HealthCount GetHealthCount_NeedsLock(); -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/IsolatedCircuitException.cs b/src/Polly/CircuitBreaker/IsolatedCircuitException.cs index 127948aea92..ee8e9f7d79f 100644 --- a/src/Polly/CircuitBreaker/IsolatedCircuitException.cs +++ b/src/Polly/CircuitBreaker/IsolatedCircuitException.cs @@ -3,33 +3,32 @@ using System.Runtime.Serialization; #endif -namespace Polly.CircuitBreaker +namespace Polly.CircuitBreaker; + +/// +/// Exception thrown when a circuit is isolated (held open) by manual override. +/// +#if NETSTANDARD2_0 +[Serializable] +#endif +public class IsolatedCircuitException : BrokenCircuitException { /// - /// Exception thrown when a circuit is isolated (held open) by manual override. + /// Initializes a new instance of the class. /// -#if NETSTANDARD2_0 - [Serializable] -#endif - public class IsolatedCircuitException : BrokenCircuitException - { - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - public IsolatedCircuitException(string message) : base(message) { } + /// The message that describes the error. + public IsolatedCircuitException(string message) : base(message) { } #if NETSTANDARD2_0 - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - protected IsolatedCircuitException( - SerializationInfo info, - StreamingContext context) : base(info, context) - { - } -#endif + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected IsolatedCircuitException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { } +#endif } diff --git a/src/Polly/CircuitBreaker/RollingHealthMetrics.cs b/src/Polly/CircuitBreaker/RollingHealthMetrics.cs index 1efb629e91d..1e41e113fe3 100644 --- a/src/Polly/CircuitBreaker/RollingHealthMetrics.cs +++ b/src/Polly/CircuitBreaker/RollingHealthMetrics.cs @@ -44,8 +44,8 @@ public HealthCount GetHealthCount_NeedsLock() { ActualiseCurrentMetric_NeedsLock(); - var successes = 0; - var failures = 0; + int successes = 0; + int failures = 0; foreach (var window in _windows) { successes += window.Successes; @@ -62,7 +62,7 @@ public HealthCount GetHealthCount_NeedsLock() private void ActualiseCurrentMetric_NeedsLock() { - var now = SystemClock.UtcNow().Ticks; + long now = SystemClock.UtcNow().Ticks; if (_currentWindow == null || now - _currentWindow.StartedAt >= _windowDuration) { _currentWindow = new HealthCount { StartedAt = now }; @@ -72,4 +72,4 @@ private void ActualiseCurrentMetric_NeedsLock() while (_windows.Count > 0 && (now - _windows.Peek().StartedAt >= _samplingDuration)) _windows.Dequeue(); } -} \ No newline at end of file +} diff --git a/src/Polly/CircuitBreaker/SingleHealthMetrics.cs b/src/Polly/CircuitBreaker/SingleHealthMetrics.cs index 2bae9c9927d..67be8f3be90 100644 --- a/src/Polly/CircuitBreaker/SingleHealthMetrics.cs +++ b/src/Polly/CircuitBreaker/SingleHealthMetrics.cs @@ -36,10 +36,10 @@ public HealthCount GetHealthCount_NeedsLock() private void ActualiseCurrentMetric_NeedsLock() { - var now = SystemClock.UtcNow().Ticks; + long now = SystemClock.UtcNow().Ticks; if (_current == null || now - _current.StartedAt >= _samplingDuration) { _current = new HealthCount { StartedAt = now }; } } -} \ No newline at end of file +} diff --git a/src/Polly/Context.Dictionary.cs b/src/Polly/Context.Dictionary.cs index fae4cf1c076..60c35e4a7fc 100644 --- a/src/Polly/Context.Dictionary.cs +++ b/src/Polly/Context.Dictionary.cs @@ -33,7 +33,7 @@ internal Context(IDictionary contextData) : this() wrappedDictionary = new Dictionary(contextData); } - #region IDictionary implementation +#region IDictionary implementation /// public ICollection Keys => WrappedDictionary.Keys; @@ -134,5 +134,5 @@ public void Add(string key, object value) /// object IDictionary.this[object key] { get => ((IDictionary)WrappedDictionary)[key]; set => ((IDictionary)WrappedDictionary)[key] = value; } - #endregion -} \ No newline at end of file +#endregion +} diff --git a/src/Polly/Context.cs b/src/Polly/Context.cs index 107e00ce2b5..d814dc77b99 100644 --- a/src/Polly/Context.cs +++ b/src/Polly/Context.cs @@ -55,4 +55,4 @@ public Guid CorrelationId return _correlationId.Value; } } -} \ No newline at end of file +} diff --git a/src/Polly/DelegateResult.cs b/src/Polly/DelegateResult.cs index 9bc11cce986..ecde18d9bc4 100644 --- a/src/Polly/DelegateResult.cs +++ b/src/Polly/DelegateResult.cs @@ -28,4 +28,4 @@ public class DelegateResult /// Any exception thrown while executing the delegate. Will be null if policy executed without exception. /// public Exception Exception { get; } -} \ No newline at end of file +} diff --git a/src/Polly/ExceptionPredicate.cs b/src/Polly/ExceptionPredicate.cs index 4d22a9a39c0..810e98440d0 100644 --- a/src/Polly/ExceptionPredicate.cs +++ b/src/Polly/ExceptionPredicate.cs @@ -7,4 +7,4 @@ namespace Polly; /// /// The passed exception, against which to evaluate the predicate. /// A matched ; or null, if an exception was not matched. ExceptionPredicate implementations may return the passed Exception , indicating that it matched the predicate. They may also return inner exceptions of the passed Exception , to indicate that the returned inner exception matched the predicate. -public delegate Exception ExceptionPredicate(Exception ex); \ No newline at end of file +public delegate Exception ExceptionPredicate(Exception ex); diff --git a/src/Polly/ExceptionPredicates.cs b/src/Polly/ExceptionPredicates.cs index 8f63689e2f8..964c6a9e810 100644 --- a/src/Polly/ExceptionPredicates.cs +++ b/src/Polly/ExceptionPredicates.cs @@ -30,4 +30,5 @@ internal void Add(ExceptionPredicate predicate) /// Specifies that no Exception-handling filters are applied or are required. /// public static readonly ExceptionPredicates None = new ExceptionPredicates(); -} \ No newline at end of file +} + diff --git a/src/Polly/ExecutionRejectedException.cs b/src/Polly/ExecutionRejectedException.cs index e756f176496..0d9c0dd37e8 100644 --- a/src/Polly/ExecutionRejectedException.cs +++ b/src/Polly/ExecutionRejectedException.cs @@ -3,49 +3,48 @@ using System.Runtime.Serialization; #endif -namespace Polly +namespace Polly; + +/// +/// Exception thrown when a policy rejects execution of a delegate. +/// More specific exceptions which derive from this type, are generally thrown. +/// +public abstract class ExecutionRejectedException : Exception { /// - /// Exception thrown when a policy rejects execution of a delegate. - /// More specific exceptions which derive from this type, are generally thrown. + /// Initializes a new instance of the class. /// - public abstract class ExecutionRejectedException : Exception + protected ExecutionRejectedException() { - /// - /// Initializes a new instance of the class. - /// - protected ExecutionRejectedException() - { - } + } - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - protected ExecutionRejectedException(string message) : base(message) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The message that describes the error. + protected ExecutionRejectedException(string message) : base(message) + { + } - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - /// The inner exception. - protected ExecutionRejectedException(string message, Exception inner) : base(message, inner) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The message that describes the error. + /// The inner exception. + protected ExecutionRejectedException(string message, Exception inner) : base(message, inner) + { + } #if NETSTANDARD2_0 - /// - /// Initializes a new instance of the class. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - protected ExecutionRejectedException( - SerializationInfo info, - StreamingContext context) : base(info, context) - { - } -#endif + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected ExecutionRejectedException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { } +#endif } diff --git a/src/Polly/Fallback/AsyncFallbackEngine.cs b/src/Polly/Fallback/AsyncFallbackEngine.cs index d895ceaf379..29f27e85f08 100644 --- a/src/Polly/Fallback/AsyncFallbackEngine.cs +++ b/src/Polly/Fallback/AsyncFallbackEngine.cs @@ -22,7 +22,7 @@ internal static async Task ImplementationAsync( { cancellationToken.ThrowIfCancellationRequested(); - var result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); + TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); if (!shouldHandleResultPredicates.AnyMatch(result)) { @@ -33,7 +33,7 @@ internal static async Task ImplementationAsync( } catch (Exception ex) { - var handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; @@ -46,4 +46,4 @@ internal static async Task ImplementationAsync( return await fallbackAction(delegateOutcome, context, cancellationToken).ConfigureAwait(continueOnCapturedContext); } -} \ No newline at end of file +} diff --git a/src/Polly/Fallback/AsyncFallbackPolicy.cs b/src/Polly/Fallback/AsyncFallbackPolicy.cs index 7c56de0c0e2..974cddba326 100644 --- a/src/Polly/Fallback/AsyncFallbackPolicy.cs +++ b/src/Polly/Fallback/AsyncFallbackPolicy.cs @@ -16,7 +16,7 @@ public class AsyncFallbackPolicy : AsyncPolicy, IFallbackPolicy internal AsyncFallbackPolicy(PolicyBuilder policyBuilder, Func onFallbackAsync, Func fallbackAction) - : base(policyBuilder) + : base(policyBuilder) { _onFallbackAsync = onFallbackAsync ?? throw new ArgumentNullException(nameof(onFallbackAsync)); _fallbackAction = fallbackAction ?? throw new ArgumentNullException(nameof(fallbackAction)); @@ -48,7 +48,7 @@ protected override Task ImplementationAsync( protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext) => - throw new InvalidOperationException($"You have executed the generic .Execute<{nameof(TResult)}> method on a non-generic {nameof(FallbackPolicy)}. A non-generic {nameof(FallbackPolicy)} only defines a fallback action which returns void; it can never return a substitute {nameof(TResult)} value. To use {nameof(FallbackPolicy)} to provide fallback {nameof(TResult)} values you must define a generic fallback policy {nameof(FallbackPolicy)}<{nameof(TResult)}>. For example, define the policy as Policy<{nameof(TResult)}>.Handle.Fallback<{nameof(TResult)}>(/* some {nameof(TResult)} value or Func<..., {nameof(TResult)}> */);"); + throw new InvalidOperationException($"You have executed the generic .Execute<{nameof(TResult)}> method on a non-generic {nameof(FallbackPolicy)}. A non-generic {nameof(FallbackPolicy)} only defines a fallback action which returns void; it can never return a substitute {nameof(TResult)} value. To use {nameof(FallbackPolicy)} to provide fallback {nameof(TResult)} values you must define a generic fallback policy {nameof(FallbackPolicy)}<{nameof(TResult)}>. For example, define the policy as Policy<{nameof(TResult)}>.Handle.Fallback<{nameof(TResult)}>(/* some {nameof(TResult)} value or Func<..., {nameof(TResult)}> */);"); } /// @@ -64,7 +64,7 @@ internal AsyncFallbackPolicy( PolicyBuilder policyBuilder, Func, Context, Task> onFallbackAsync, Func, Context, CancellationToken, Task> fallbackAction - ) : base(policyBuilder) + ) : base(policyBuilder) { _onFallbackAsync = onFallbackAsync ?? throw new ArgumentNullException(nameof(onFallbackAsync)); _fallbackAction = fallbackAction ?? throw new ArgumentNullException(nameof(fallbackAction)); @@ -83,4 +83,4 @@ protected override Task ImplementationAsync(Func @@ -46,7 +46,7 @@ public static AsyncFallbackPolicy FallbackAsync(this PolicyBuilder policyBuilder return policyBuilder.FallbackAsync( (_, _, ct) => fallbackAction(ct), (outcome, _) => onFallbackAsync(outcome) - ); + ); } /// @@ -101,7 +101,7 @@ public static AsyncFallbackPolicy FallbackAsync(this PolicyBui return policyBuilder.FallbackAsync( _ => Task.FromResult(fallbackValue), doNothing - ); + ); } /// @@ -119,7 +119,7 @@ public static AsyncFallbackPolicy FallbackAsync(this PolicyBui return policyBuilder.FallbackAsync( fallbackAction, doNothing - ); + ); } /// @@ -137,7 +137,7 @@ public static AsyncFallbackPolicy FallbackAsync(this PolicyBui return policyBuilder.FallbackAsync( (_, _, _) => Task.FromResult(fallbackValue), (outcome, _) => onFallbackAsync(outcome) - ); + ); } /// @@ -157,7 +157,7 @@ public static AsyncFallbackPolicy FallbackAsync(this PolicyBui return policyBuilder.FallbackAsync( (_, _, ct) => fallbackAction(ct), (outcome, _) => onFallbackAsync(outcome) - ); + ); } /// @@ -175,7 +175,7 @@ public static AsyncFallbackPolicy FallbackAsync(this PolicyBui return policyBuilder.FallbackAsync( (_, _, _) => Task.FromResult(fallbackValue), onFallbackAsync - ); + ); } /// @@ -210,8 +210,8 @@ public static AsyncFallbackPolicy FallbackAsync(this PolicyBui if (onFallbackAsync == null) throw new ArgumentNullException(nameof(onFallbackAsync)); return new AsyncFallbackPolicy( - policyBuilder, - onFallbackAsync, - fallbackAction); + policyBuilder, + onFallbackAsync, + fallbackAction); } -} \ No newline at end of file +} diff --git a/src/Polly/Fallback/FallbackEngine.cs b/src/Polly/Fallback/FallbackEngine.cs index fe51ba4e4da..2e7f4f4762c 100644 --- a/src/Polly/Fallback/FallbackEngine.cs +++ b/src/Polly/Fallback/FallbackEngine.cs @@ -20,7 +20,7 @@ internal static TResult Implementation( { cancellationToken.ThrowIfCancellationRequested(); - var result = action(context, cancellationToken); + TResult result = action(context, cancellationToken); if (!shouldHandleResultPredicates.AnyMatch(result)) { @@ -31,7 +31,7 @@ internal static TResult Implementation( } catch (Exception ex) { - var handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldHandleExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; @@ -44,4 +44,4 @@ internal static TResult Implementation( return fallbackAction(delegateOutcome, context, cancellationToken); } -} \ No newline at end of file +} diff --git a/src/Polly/Fallback/FallbackPolicy.cs b/src/Polly/Fallback/FallbackPolicy.cs index 3e213cd357e..8933a8c6366 100644 --- a/src/Polly/Fallback/FallbackPolicy.cs +++ b/src/Polly/Fallback/FallbackPolicy.cs @@ -52,7 +52,7 @@ internal FallbackPolicy( PolicyBuilder policyBuilder, Action, Context> onFallback, Func, Context, CancellationToken, TResult> fallbackAction - ) : base(policyBuilder) + ) : base(policyBuilder) { _onFallback = onFallback ?? throw new ArgumentNullException(nameof(onFallback)); _fallbackAction = fallbackAction ?? throw new ArgumentNullException(nameof(fallbackAction)); @@ -69,4 +69,4 @@ protected override TResult Implementation(Func Fallback(this PolicyBuilder /// Defines properties and methods common to all Fallback policies. /// + public interface IFallbackPolicy : IsPolicy { } @@ -12,4 +13,4 @@ public interface IFallbackPolicy : IsPolicy /// public interface IFallbackPolicy : IFallbackPolicy { -} \ No newline at end of file +} diff --git a/src/Polly/IAsyncPolicy.Extensions.cs b/src/Polly/IAsyncPolicy.Extensions.cs index 5425bf0b493..643f2b3fe5e 100644 --- a/src/Polly/IAsyncPolicy.Extensions.cs +++ b/src/Polly/IAsyncPolicy.Extensions.cs @@ -13,4 +13,5 @@ public static class IAsyncPolicyExtensions /// A generic version of the supplied non-generic . public static IAsyncPolicy AsAsyncPolicy(this IAsyncPolicy policy) => policy.WrapAsync(Policy.NoOpAsync()); -} \ No newline at end of file +} + diff --git a/src/Polly/IAsyncPolicy.TResult.cs b/src/Polly/IAsyncPolicy.TResult.cs index c3ed691b2b9..9b3b120e4f8 100644 --- a/src/Polly/IAsyncPolicy.TResult.cs +++ b/src/Polly/IAsyncPolicy.TResult.cs @@ -181,4 +181,4 @@ public interface IAsyncPolicy : IsPolicy /// The captured result /// Please use asynchronous-defined policies when calling asynchronous ExecuteAsync (and similar) methods. Task> ExecuteAndCaptureAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/IAsyncPolicy.cs b/src/Polly/IAsyncPolicy.cs index 675b5e9bdcc..c93424cea73 100644 --- a/src/Polly/IAsyncPolicy.cs +++ b/src/Polly/IAsyncPolicy.cs @@ -345,4 +345,4 @@ public interface IAsyncPolicy : IsPolicy /// The captured result /// Please use asynchronous-defined policies when calling asynchronous ExecuteAsync (and similar) methods. Task> ExecuteAndCaptureAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/ISyncPolicy.Extensions.cs b/src/Polly/ISyncPolicy.Extensions.cs index 60c04f427cf..163be436370 100644 --- a/src/Polly/ISyncPolicy.Extensions.cs +++ b/src/Polly/ISyncPolicy.Extensions.cs @@ -13,4 +13,5 @@ public static class ISyncPolicyExtensions /// A generic version of the supplied non-generic . public static ISyncPolicy AsPolicy(this ISyncPolicy policy) => policy.Wrap(Policy.NoOp()); -} \ No newline at end of file +} + diff --git a/src/Polly/ISyncPolicy.TResult.cs b/src/Polly/ISyncPolicy.TResult.cs index 9d478058352..5c851dce096 100644 --- a/src/Polly/ISyncPolicy.TResult.cs +++ b/src/Polly/ISyncPolicy.TResult.cs @@ -8,6 +8,7 @@ namespace Polly; /// An interface defining all executions available on a synchronous policy generic-typed for executions returning results of type . /// /// The type of the result of funcs executed through the Policy. + public interface ISyncPolicy : IsPolicy { /// @@ -126,4 +127,4 @@ public interface ISyncPolicy : IsPolicy /// The cancellation token. /// The captured result PolicyResult ExecuteAndCapture(Func action, Context context, CancellationToken cancellationToken); -} \ No newline at end of file +} diff --git a/src/Polly/ISyncPolicy.cs b/src/Polly/ISyncPolicy.cs index bda72a4c225..14dee2b9da2 100644 --- a/src/Polly/ISyncPolicy.cs +++ b/src/Polly/ISyncPolicy.cs @@ -228,4 +228,4 @@ public interface ISyncPolicy : IsPolicy /// The cancellation token. /// The captured result PolicyResult ExecuteAndCapture(Func action, Context context, CancellationToken cancellationToken); -} \ No newline at end of file +} diff --git a/src/Polly/IsPolicy.cs b/src/Polly/IsPolicy.cs index 32b4f2f148e..559d815e1a9 100644 --- a/src/Polly/IsPolicy.cs +++ b/src/Polly/IsPolicy.cs @@ -9,4 +9,4 @@ public interface IsPolicy /// A key intended to be unique to each policy instance, which is passed with executions as the property. /// string PolicyKey { get; } -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/AsyncNoOpPolicy.cs b/src/Polly/NoOp/AsyncNoOpPolicy.cs index ac14f676951..39dbc67b577 100644 --- a/src/Polly/NoOp/AsyncNoOpPolicy.cs +++ b/src/Polly/NoOp/AsyncNoOpPolicy.cs @@ -35,4 +35,4 @@ internal AsyncNoOpPolicy() protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext) => NoOpEngine.ImplementationAsync(action, context, cancellationToken, continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/AsyncNoOpSyntax.cs b/src/Polly/NoOp/AsyncNoOpSyntax.cs index efd2a8e4f6c..d18a9b091c7 100644 --- a/src/Polly/NoOp/AsyncNoOpSyntax.cs +++ b/src/Polly/NoOp/AsyncNoOpSyntax.cs @@ -9,4 +9,4 @@ public partial class Policy /// /// The policy instance. public static AsyncNoOpPolicy NoOpAsync() => new AsyncNoOpPolicy(); -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/AsyncNoOpTResultSyntax.cs b/src/Polly/NoOp/AsyncNoOpTResultSyntax.cs index bd4c0f7f012..bfa65dbea5c 100644 --- a/src/Polly/NoOp/AsyncNoOpTResultSyntax.cs +++ b/src/Polly/NoOp/AsyncNoOpTResultSyntax.cs @@ -10,4 +10,4 @@ public partial class Policy /// The type of return values this policy will handle. /// The policy instance. public static AsyncNoOpPolicy NoOpAsync() => new AsyncNoOpPolicy(); -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/INoOpPolicy.cs b/src/Polly/NoOp/INoOpPolicy.cs index cd8e7e4b957..82dadfffe12 100644 --- a/src/Polly/NoOp/INoOpPolicy.cs +++ b/src/Polly/NoOp/INoOpPolicy.cs @@ -3,6 +3,7 @@ /// /// Defines properties and methods common to all NoOp policies. /// + public interface INoOpPolicy : IsPolicy { } @@ -12,4 +13,4 @@ public interface INoOpPolicy : IsPolicy /// public interface INoOpPolicy : INoOpPolicy { -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/NoOpEngine.cs b/src/Polly/NoOp/NoOpEngine.cs index 54869449daa..403a8c70a76 100644 --- a/src/Polly/NoOp/NoOpEngine.cs +++ b/src/Polly/NoOp/NoOpEngine.cs @@ -7,4 +7,4 @@ internal static partial class NoOpEngine { internal static TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => action(context, cancellationToken); -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/NoOpEngineAsync.cs b/src/Polly/NoOp/NoOpEngineAsync.cs index df85c560c0d..1056d0fe9ea 100644 --- a/src/Polly/NoOp/NoOpEngineAsync.cs +++ b/src/Polly/NoOp/NoOpEngineAsync.cs @@ -8,4 +8,4 @@ internal static partial class NoOpEngine { internal static async Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext) => await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/NoOpPolicy.cs b/src/Polly/NoOp/NoOpPolicy.cs index 4717a629c0b..5bfe9fb57e3 100644 --- a/src/Polly/NoOp/NoOpPolicy.cs +++ b/src/Polly/NoOp/NoOpPolicy.cs @@ -33,4 +33,4 @@ internal NoOpPolicy() [DebuggerStepThrough] protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => NoOpEngine.Implementation(action, context, cancellationToken); -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/NoOpSyntax.cs b/src/Polly/NoOp/NoOpSyntax.cs index af780b9a818..149320a0a75 100644 --- a/src/Polly/NoOp/NoOpSyntax.cs +++ b/src/Polly/NoOp/NoOpSyntax.cs @@ -9,4 +9,4 @@ public partial class Policy /// /// The policy instance. public static NoOpPolicy NoOp() => new NoOpPolicy(); -} \ No newline at end of file +} diff --git a/src/Polly/NoOp/NoOpTResultSyntax.cs b/src/Polly/NoOp/NoOpTResultSyntax.cs index 920c8b7c94a..f5d768a7fef 100644 --- a/src/Polly/NoOp/NoOpTResultSyntax.cs +++ b/src/Polly/NoOp/NoOpTResultSyntax.cs @@ -10,4 +10,4 @@ public partial class Policy /// The type of return values this policy will handle. /// The policy instance. public static NoOpPolicy NoOp() => new NoOpPolicy(); -} \ No newline at end of file +} diff --git a/src/Polly/Policy.ContextAndKeys.cs b/src/Polly/Policy.ContextAndKeys.cs index 7c9942566ea..c5b454274ae 100644 --- a/src/Polly/Policy.ContextAndKeys.cs +++ b/src/Polly/Policy.ContextAndKeys.cs @@ -56,4 +56,4 @@ ISyncPolicy ISyncPolicy.WithPolicyKey(string policyKey) policyKeyInternal = policyKey; return this; } -} \ No newline at end of file +} diff --git a/src/Polly/Policy.ExecuteOverloads.cs b/src/Polly/Policy.ExecuteOverloads.cs index 2ddd48dea00..734247514ee 100644 --- a/src/Polly/Policy.ExecuteOverloads.cs +++ b/src/Polly/Policy.ExecuteOverloads.cs @@ -66,7 +66,7 @@ public void Execute(Action action, Context context, { if (context == null) throw new ArgumentNullException(nameof(context)); - SetPolicyContext(context, out var priorPolicyWrapKey, out var priorPolicyKey); + SetPolicyContext(context, out string priorPolicyWrapKey, out string priorPolicyKey); try { @@ -157,7 +157,7 @@ public TResult Execute(Func action { if (context == null) throw new ArgumentNullException(nameof(context)); - SetPolicyContext(context, out var priorPolicyWrapKey, out var priorPolicyKey); + SetPolicyContext(context, out string priorPolicyWrapKey, out string priorPolicyKey); try { @@ -331,4 +331,4 @@ public PolicyResult ExecuteAndCapture(Func HandleResult(Func resultPred /// The PolicyBuilder instance. public static PolicyBuilder HandleResult(TResult result) => HandleResult(r => (r != null && r.Equals(result)) || (r == null && result == null)); -} \ No newline at end of file +} diff --git a/src/Polly/Policy.SyncGenericImplementation.cs b/src/Polly/Policy.SyncGenericImplementation.cs index f8a0f737082..70b5ca642de 100644 --- a/src/Polly/Policy.SyncGenericImplementation.cs +++ b/src/Polly/Policy.SyncGenericImplementation.cs @@ -17,4 +17,4 @@ protected abstract TResult Implementation( Context context, CancellationToken cancellationToken ); -} \ No newline at end of file +} diff --git a/src/Polly/Policy.SyncNonGenericImplementation.cs b/src/Polly/Policy.SyncNonGenericImplementation.cs index da20d0adf15..2e315370840 100644 --- a/src/Polly/Policy.SyncNonGenericImplementation.cs +++ b/src/Polly/Policy.SyncNonGenericImplementation.cs @@ -26,4 +26,4 @@ protected virtual void Implementation(Action action, /// A token to signal that execution should be cancelled. /// A result of the execution. protected abstract TResult Implementation(Func action, Context context, CancellationToken cancellationToken); -} \ No newline at end of file +} diff --git a/src/Polly/Policy.TResult.ExecuteOverloads.cs b/src/Polly/Policy.TResult.ExecuteOverloads.cs index 99698f4dd89..52a33e195fa 100644 --- a/src/Polly/Policy.TResult.ExecuteOverloads.cs +++ b/src/Polly/Policy.TResult.ExecuteOverloads.cs @@ -82,7 +82,7 @@ public TResult Execute(Func action, Context { if (context == null) throw new ArgumentNullException(nameof(context)); - SetPolicyContext(context, out var priorPolicyWrapKey, out var priorPolicyKey); + SetPolicyContext(context, out string priorPolicyWrapKey, out string priorPolicyKey); try { @@ -165,7 +165,7 @@ public PolicyResult ExecuteAndCapture(Func ExecuteAndCapture(Func : PolicyBase /// Predicates indicating which exceptions the policy should handle. /// Predicates indicating which results the policy should handle. internal Policy(ExceptionPredicates exceptionPredicates, ResultPredicates resultPredicates) - : base(exceptionPredicates, resultPredicates) + : base(exceptionPredicates, resultPredicates) { } @@ -23,4 +23,4 @@ protected Policy(PolicyBuilder policyBuilder = null) : base(policyBuilder) { } -} \ No newline at end of file +} diff --git a/src/Polly/Policy.cs b/src/Polly/Policy.cs index adf7c7c8707..192d7d8c2e0 100644 --- a/src/Polly/Policy.cs +++ b/src/Polly/Policy.cs @@ -22,4 +22,4 @@ protected Policy(PolicyBuilder policyBuilder = null) : base(policyBuilder) { } -} \ No newline at end of file +} diff --git a/src/Polly/PolicyBase.ContextAndKeys.cs b/src/Polly/PolicyBase.ContextAndKeys.cs index 28a971e7c53..511bbfa37c7 100644 --- a/src/Polly/PolicyBase.ContextAndKeys.cs +++ b/src/Polly/PolicyBase.ContextAndKeys.cs @@ -42,4 +42,4 @@ internal void RestorePolicyContext(Context executionContext, string priorPolicyW executionContext.PolicyWrapKey = priorPolicyWrapKey; executionContext.PolicyKey = priorPolicyKey; } -} \ No newline at end of file +} diff --git a/src/Polly/PolicyBase.cs b/src/Polly/PolicyBase.cs index e71ecc10d7c..68ac86dc44a 100644 --- a/src/Polly/PolicyBase.cs +++ b/src/Polly/PolicyBase.cs @@ -25,7 +25,7 @@ public abstract partial class PolicyBase internal static ExceptionType GetExceptionType(ExceptionPredicates exceptionPredicates, Exception exception) { - var isExceptionTypeHandledByThisPolicy = exceptionPredicates.FirstMatchOrDefault(exception) != null; + bool isExceptionTypeHandledByThisPolicy = exceptionPredicates.FirstMatchOrDefault(exception) != null; return isExceptionTypeHandledByThisPolicy ? ExceptionType.HandledByThisPolicy @@ -67,7 +67,7 @@ public abstract class PolicyBase : PolicyBase internal PolicyBase( ExceptionPredicates exceptionPredicates, ResultPredicates resultPredicates) - : base(exceptionPredicates) + : base(exceptionPredicates) => ResultPredicates = resultPredicates ?? ResultPredicates.None; /// @@ -78,4 +78,4 @@ protected PolicyBase(PolicyBuilder policyBuilder) : this(policyBuilder?.ExceptionPredicates, policyBuilder?.ResultPredicates) { } -} \ No newline at end of file +} diff --git a/src/Polly/PolicyBuilder.OrSyntax.cs b/src/Polly/PolicyBuilder.OrSyntax.cs index 4f47d037c20..31f5347a665 100644 --- a/src/Polly/PolicyBuilder.OrSyntax.cs +++ b/src/Polly/PolicyBuilder.OrSyntax.cs @@ -178,4 +178,4 @@ public PolicyBuilder OrInner(Func excepti } #endregion -} \ No newline at end of file +} diff --git a/src/Polly/PolicyBuilder.cs b/src/Polly/PolicyBuilder.cs index 8ebf7e7405c..e4628f043ed 100644 --- a/src/Polly/PolicyBuilder.cs +++ b/src/Polly/PolicyBuilder.cs @@ -28,8 +28,10 @@ internal PolicyBuilder(ExceptionPredicate exceptionPredicate) /// A that represents this instance. /// [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => - base.ToString(); + public override string ToString() + { + return base.ToString(); + } /// /// Determines whether the specified is equal to this instance. @@ -39,8 +41,10 @@ public override string ToString() => /// true if the specified is equal to this instance; otherwise, false. /// [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => - base.Equals(obj); + public override bool Equals(object obj) + { + return base.Equals(obj); + } /// /// Returns a hash code for this instance. @@ -49,8 +53,10 @@ public override bool Equals(object obj) => /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => - base.GetHashCode(); + public override int GetHashCode() + { + return base.GetHashCode(); + } /// /// Gets the of the current instance. @@ -59,8 +65,10 @@ public override int GetHashCode() => /// The instance that represents the exact runtime type of the current instance. /// [EditorBrowsable(EditorBrowsableState.Never)] - public new Type GetType() => - base.GetType(); + public new Type GetType() + { + return base.GetType(); + } #endregion } @@ -136,4 +144,4 @@ internal PolicyBuilder(ExceptionPredicates exceptionPredicates) public new Type GetType() => base.GetType(); #endregion -} \ No newline at end of file +} diff --git a/src/Polly/PolicyResult.cs b/src/Polly/PolicyResult.cs index c93c2db687c..5452f1f6d80 100644 --- a/src/Polly/PolicyResult.cs +++ b/src/Polly/PolicyResult.cs @@ -138,8 +138,8 @@ public static PolicyResult Successful(TResult result, Context context) public static PolicyResult Failure(Exception exception, ExceptionType exceptionType, Context context) => new PolicyResult(default, OutcomeType.Failure, exception, exceptionType, default, exceptionType == Polly.ExceptionType.HandledByThisPolicy - ? Polly.FaultType.ExceptionHandledByThisPolicy - : Polly.FaultType.UnhandledException, + ? Polly.FaultType.ExceptionHandledByThisPolicy + : Polly.FaultType.UnhandledException, context); /// @@ -205,4 +205,4 @@ public enum FaultType /// A result value that has been defined to be handled by this policy /// ResultHandledByThisPolicy -} \ No newline at end of file +} diff --git a/src/Polly/Polly.csproj b/src/Polly/Polly.csproj index 6bfe96ca0c8..d1b5712018a 100644 --- a/src/Polly/Polly.csproj +++ b/src/Polly/Polly.csproj @@ -1,12 +1,12 @@ - + netstandard1.1;netstandard2.0;net461;net472 - 7.3.0 + 7.2.4 7.0.0.0 - 7.3.0.0 - 7.3.0.0 - 7.3.0 + 7.2.4.0 + 7.2.4.0 + 7.2.4 App vNext Copyright (c) $([System.DateTime]::Now.ToString(yyyy)), App vNext Polly is a library that allows developers to express resilience and transient fault handling policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner. diff --git a/src/Polly/RateLimit/AsyncRateLimitEngine.cs b/src/Polly/RateLimit/AsyncRateLimitEngine.cs index 2ade2ef4e64..fabb362c3ee 100644 --- a/src/Polly/RateLimit/AsyncRateLimitEngine.cs +++ b/src/Polly/RateLimit/AsyncRateLimitEngine.cs @@ -13,9 +13,9 @@ internal static async Task ImplementationAsync( Context context, CancellationToken cancellationToken, bool continueOnCapturedContext - ) + ) { - (var permit, var retryAfter) = rateLimiter.PermitExecution(); + (bool permit, TimeSpan retryAfter) = rateLimiter.PermitExecution(); if (permit) { @@ -29,4 +29,4 @@ bool continueOnCapturedContext throw new RateLimitRejectedException(retryAfter); } -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/AsyncRateLimitPolicy.cs b/src/Polly/RateLimit/AsyncRateLimitPolicy.cs index b6a58ae6171..be7590aac2b 100644 --- a/src/Polly/RateLimit/AsyncRateLimitPolicy.cs +++ b/src/Polly/RateLimit/AsyncRateLimitPolicy.cs @@ -45,4 +45,4 @@ internal AsyncRateLimitPolicy( protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext) => AsyncRateLimitEngine.ImplementationAsync(_rateLimiter, _retryAfterFactory, action, context, cancellationToken, continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/AsyncRateLimitSyntax.cs b/src/Polly/RateLimit/AsyncRateLimitSyntax.cs index c468741f927..db0d6813898 100644 --- a/src/Polly/RateLimit/AsyncRateLimitSyntax.cs +++ b/src/Polly/RateLimit/AsyncRateLimitSyntax.cs @@ -13,8 +13,10 @@ public partial class Policy /// The policy instance. public static AsyncRateLimitPolicy RateLimitAsync( int numberOfExecutions, - TimeSpan perTimeSpan) => - RateLimitAsync(numberOfExecutions, perTimeSpan, 1); + TimeSpan perTimeSpan) + { + return RateLimitAsync(numberOfExecutions, perTimeSpan, 1); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given. @@ -40,8 +42,8 @@ public static AsyncRateLimitPolicy RateLimitAsync( throw new ArgumentOutOfRangeException(nameof(perTimeSpan), perTimeSpan, "The number of executions per timespan must be positive."); } - var rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); + IRateLimiter rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); return new AsyncRateLimitPolicy(rateLimiter); } -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/AsyncRateLimitTResultSyntax.cs b/src/Polly/RateLimit/AsyncRateLimitTResultSyntax.cs index b264da5a4a1..4844f885013 100644 --- a/src/Polly/RateLimit/AsyncRateLimitTResultSyntax.cs +++ b/src/Polly/RateLimit/AsyncRateLimitTResultSyntax.cs @@ -14,8 +14,10 @@ public partial class Policy /// The policy instance. public static AsyncRateLimitPolicy RateLimitAsync( int numberOfExecutions, - TimeSpan perTimeSpan) => - RateLimitAsync(numberOfExecutions, perTimeSpan, null); + TimeSpan perTimeSpan) + { + return RateLimitAsync(numberOfExecutions, perTimeSpan, null); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given. @@ -29,8 +31,10 @@ public static AsyncRateLimitPolicy RateLimitAsync( public static AsyncRateLimitPolicy RateLimitAsync( int numberOfExecutions, TimeSpan perTimeSpan, - Func retryAfterFactory) => - RateLimitAsync(numberOfExecutions, perTimeSpan, 1, retryAfterFactory); + Func retryAfterFactory) + { + return RateLimitAsync(numberOfExecutions, perTimeSpan, 1, retryAfterFactory); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given. @@ -44,8 +48,10 @@ public static AsyncRateLimitPolicy RateLimitAsync( public static AsyncRateLimitPolicy RateLimitAsync( int numberOfExecutions, TimeSpan perTimeSpan, - int maxBurst) => - RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst, null); + int maxBurst) + { + return RateLimitAsync(numberOfExecutions, perTimeSpan, maxBurst, null); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given, @@ -76,8 +82,8 @@ public static AsyncRateLimitPolicy RateLimitAsync( throw new ArgumentOutOfRangeException(nameof(perTimeSpan), perTimeSpan, "The number of executions per timespan must be positive."); } - var rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); + IRateLimiter rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); return new AsyncRateLimitPolicy(rateLimiter, retryAfterFactory); } -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/IRateLimitPolicy.cs b/src/Polly/RateLimit/IRateLimitPolicy.cs index 1defff8faaf..89cf8404204 100644 --- a/src/Polly/RateLimit/IRateLimitPolicy.cs +++ b/src/Polly/RateLimit/IRateLimitPolicy.cs @@ -12,4 +12,4 @@ public interface IRateLimitPolicy : IsPolicy /// public interface IRateLimitPolicy : IRateLimitPolicy { -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/IRateLimiter.cs b/src/Polly/RateLimit/IRateLimiter.cs index 5fee277f288..74919b97ae9 100644 --- a/src/Polly/RateLimit/IRateLimiter.cs +++ b/src/Polly/RateLimit/IRateLimiter.cs @@ -12,4 +12,4 @@ internal interface IRateLimiter /// Calling this method consumes an execution permit if one is available: a caller receiving a return value true should make an execution. /// (bool permitExecution, TimeSpan retryAfter) PermitExecution(); -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs b/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs index b6fe361ec2a..7120152169f 100644 --- a/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs +++ b/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs @@ -47,7 +47,7 @@ public LockFreeTokenBucketRateLimiter(TimeSpan onePer, long bucketCapacity) while (true) { // Try to get a token. - var tokensAfterGrabOne = Interlocked.Decrement(ref currentTokens); + long tokensAfterGrabOne = Interlocked.Decrement(ref currentTokens); if (tokensAfterGrabOne >= 0) { @@ -56,9 +56,9 @@ public LockFreeTokenBucketRateLimiter(TimeSpan onePer, long bucketCapacity) } // No tokens! We're rate-limited - unless we can refill the bucket. - var now = SystemClock.DateTimeOffsetUtcNow().Ticks; - var currentAddNextTokenAtTicks = Interlocked.Read(ref addNextTokenAtTicks); - var ticksTillAddNextToken = currentAddNextTokenAtTicks - now; + long now = SystemClock.DateTimeOffsetUtcNow().Ticks; + long currentAddNextTokenAtTicks = Interlocked.Read(ref addNextTokenAtTicks); + long ticksTillAddNextToken = currentAddNextTokenAtTicks - now; if (ticksTillAddNextToken > 0) { @@ -69,17 +69,17 @@ public LockFreeTokenBucketRateLimiter(TimeSpan onePer, long bucketCapacity) // Time to add tokens to the bucket! // We definitely need to add one token. In fact, if we haven't hit this bit of code for a while, we might be due to add a bunch of tokens. - var tokensMissedAdding = + long tokensMissedAdding = // Passing addNextTokenAtTicks merits one token 1 + // And any whole token tick intervals further each merit another. (-ticksTillAddNextToken / addTokenTickInterval); // We mustn't exceed bucket capacity though. - var tokensToAdd = Math.Min(bucketCapacity, tokensMissedAdding); + long tokensToAdd = Math.Min(bucketCapacity, tokensMissedAdding); // Work out when tokens would next be due to be added, if we add these tokens. - var newAddNextTokenAtTicks = currentAddNextTokenAtTicks + (tokensToAdd * addTokenTickInterval); + long newAddNextTokenAtTicks = currentAddNextTokenAtTicks + (tokensToAdd * addTokenTickInterval); // But if we were way overdue refilling the bucket (there was inactivity for a while), that value would be out-of-date: the next time we add tokens must be at least addTokenTickInterval from now. newAddNextTokenAtTicks = Math.Max(newAddNextTokenAtTicks, now + addTokenTickInterval); @@ -105,11 +105,11 @@ public LockFreeTokenBucketRateLimiter(TimeSpan onePer, long bucketCapacity) // We want any thread refilling the bucket to have a chance to do so before we try to grab the next token. #if NETSTANDARD2_0 - Thread.Sleep(0); + Thread.Sleep(0); #else - spinner.SpinOnce(); + spinner.SpinOnce(); #endif } } } -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/RateLimitEngine.cs b/src/Polly/RateLimit/RateLimitEngine.cs index aeed16b9da9..80dd425362d 100644 --- a/src/Polly/RateLimit/RateLimitEngine.cs +++ b/src/Polly/RateLimit/RateLimitEngine.cs @@ -13,7 +13,7 @@ internal static TResult Implementation( CancellationToken cancellationToken ) { - (var permit, var retryAfter) = rateLimiter.PermitExecution(); + (bool permit, TimeSpan retryAfter) = rateLimiter.PermitExecution(); if (permit) { @@ -27,4 +27,4 @@ CancellationToken cancellationToken throw new RateLimitRejectedException(retryAfter); } -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/RateLimitPolicy.cs b/src/Polly/RateLimit/RateLimitPolicy.cs index 7a79dea59a1..f1a09defc62 100644 --- a/src/Polly/RateLimit/RateLimitPolicy.cs +++ b/src/Polly/RateLimit/RateLimitPolicy.cs @@ -42,4 +42,4 @@ internal RateLimitPolicy( [DebuggerStepThrough] protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => RateLimitEngine.Implementation(_rateLimiter, _retryAfterFactory, action, context, cancellationToken); -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/RateLimitRejectedException.cs b/src/Polly/RateLimit/RateLimitRejectedException.cs index d30b1557ab9..f2043e569e1 100644 --- a/src/Polly/RateLimit/RateLimitRejectedException.cs +++ b/src/Polly/RateLimit/RateLimitRejectedException.cs @@ -3,77 +3,76 @@ using System.Runtime.Serialization; #endif -namespace Polly.RateLimit +namespace Polly.RateLimit; + +/// +/// Exception thrown when a delegate executed through a is rate-limited. +/// +#if NETSTANDARD2_0 +[Serializable] +#endif +public class RateLimitRejectedException : ExecutionRejectedException { /// - /// Exception thrown when a delegate executed through a is rate-limited. + /// The timespan after which the operation may be retried. /// -#if NETSTANDARD2_0 - [Serializable] -#endif - public class RateLimitRejectedException : ExecutionRejectedException - { - /// - /// The timespan after which the operation may be retried. - /// - public TimeSpan RetryAfter { get; private set; } + public TimeSpan RetryAfter { get; private set; } - /// - /// Initializes a new instance of the class. - /// - /// The timespan after which the operation may be retried. - public RateLimitRejectedException(TimeSpan retryAfter) : this(retryAfter, DefaultMessage(retryAfter)) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The timespan after which the operation may be retried. + public RateLimitRejectedException(TimeSpan retryAfter) : this(retryAfter, DefaultMessage(retryAfter)) + { + } - /// - /// Initializes a new instance of the class. - /// - /// The timespan after which the operation may be retried. - /// The inner exception. - public RateLimitRejectedException(TimeSpan retryAfter, Exception innerException) : base(DefaultMessage(retryAfter), innerException) - { - SetRetryAfter(retryAfter); - } + /// + /// Initializes a new instance of the class. + /// + /// The timespan after which the operation may be retried. + /// The inner exception. + public RateLimitRejectedException(TimeSpan retryAfter, Exception innerException) : base(DefaultMessage(retryAfter), innerException) + { + SetRetryAfter(retryAfter); + } - /// - /// Initializes a new instance of the class. - /// - /// The timespan after which the operation may be retried. - /// The message. - public RateLimitRejectedException(TimeSpan retryAfter, string message) : base(message) - { - SetRetryAfter(retryAfter); - } + /// + /// Initializes a new instance of the class. + /// + /// The timespan after which the operation may be retried. + /// The message. + public RateLimitRejectedException(TimeSpan retryAfter, string message) : base(message) + { + SetRetryAfter(retryAfter); + } - /// - /// Initializes a new instance of the class. - /// - /// The message. - /// The timespan after which the operation may be retried. - /// The inner exception. - public RateLimitRejectedException(TimeSpan retryAfter, string message, Exception innerException) : base(message, innerException) - { - SetRetryAfter(retryAfter); - } + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The timespan after which the operation may be retried. + /// The inner exception. + public RateLimitRejectedException(TimeSpan retryAfter, string message, Exception innerException) : base(message, innerException) + { + SetRetryAfter(retryAfter); + } - private void SetRetryAfter(TimeSpan retryAfter) - { - if (retryAfter < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(retryAfter), retryAfter, $"The {nameof(retryAfter)} parameter must be a TimeSpan greater than or equal to TimeSpan.Zero."); - RetryAfter = retryAfter; - } + private void SetRetryAfter(TimeSpan retryAfter) + { + if (retryAfter < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(retryAfter), retryAfter, $"The {nameof(retryAfter)} parameter must be a TimeSpan greater than or equal to TimeSpan.Zero."); + RetryAfter = retryAfter; + } - private static string DefaultMessage(TimeSpan retryAfter) => $"The operation has been rate-limited and should be retried after {retryAfter}"; + private static string DefaultMessage(TimeSpan retryAfter) => $"The operation has been rate-limited and should be retried after {retryAfter}"; #if NETSTANDARD2_0 - /// - /// Initializes a new instance of the class. - /// - /// The information. - /// The context. - protected RateLimitRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } -#endif + /// + /// Initializes a new instance of the class. + /// + /// The information. + /// The context. + protected RateLimitRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) + { } +#endif } diff --git a/src/Polly/RateLimit/RateLimitSyntax.cs b/src/Polly/RateLimit/RateLimitSyntax.cs index 287d1ff75f5..5f509c9eb6d 100644 --- a/src/Polly/RateLimit/RateLimitSyntax.cs +++ b/src/Polly/RateLimit/RateLimitSyntax.cs @@ -13,8 +13,10 @@ public partial class Policy /// The policy instance. public static RateLimitPolicy RateLimit( int numberOfExecutions, - TimeSpan perTimeSpan) => - RateLimit(numberOfExecutions, perTimeSpan, 1); + TimeSpan perTimeSpan) + { + return RateLimit(numberOfExecutions, perTimeSpan, 1); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given. @@ -40,8 +42,8 @@ public static RateLimitPolicy RateLimit( throw new ArgumentOutOfRangeException(nameof(perTimeSpan), perTimeSpan, "The number of executions per timespan must be positive."); } - var rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); + IRateLimiter rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); return new RateLimitPolicy(rateLimiter); } -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/RateLimitTResultSyntax.cs b/src/Polly/RateLimit/RateLimitTResultSyntax.cs index 96077ed2c58..b6f09c6113b 100644 --- a/src/Polly/RateLimit/RateLimitTResultSyntax.cs +++ b/src/Polly/RateLimit/RateLimitTResultSyntax.cs @@ -14,8 +14,10 @@ public partial class Policy /// The policy instance. public static RateLimitPolicy RateLimit( int numberOfExecutions, - TimeSpan perTimeSpan) => - RateLimit(numberOfExecutions, perTimeSpan, null); + TimeSpan perTimeSpan) + { + return RateLimit(numberOfExecutions, perTimeSpan, null); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given. @@ -29,8 +31,10 @@ public static RateLimitPolicy RateLimit( public static RateLimitPolicy RateLimit( int numberOfExecutions, TimeSpan perTimeSpan, - Func retryAfterFactory) => - RateLimit(numberOfExecutions, perTimeSpan, 1, retryAfterFactory); + Func retryAfterFactory) + { + return RateLimit(numberOfExecutions, perTimeSpan, 1, retryAfterFactory); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given. @@ -44,8 +48,10 @@ public static RateLimitPolicy RateLimit( public static RateLimitPolicy RateLimit( int numberOfExecutions, TimeSpan perTimeSpan, - int maxBurst) => - RateLimit(numberOfExecutions, perTimeSpan, maxBurst, null); + int maxBurst) + { + return RateLimit(numberOfExecutions, perTimeSpan, maxBurst, null); + } /// /// Builds a RateLimit that will rate-limit executions to per the timespan given, @@ -76,8 +82,8 @@ public static RateLimitPolicy RateLimit( throw new ArgumentOutOfRangeException(nameof(perTimeSpan), perTimeSpan, "The number of executions per timespan must be positive."); } - var rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); + IRateLimiter rateLimiter = RateLimiterFactory.Create(onePer, maxBurst); return new RateLimitPolicy(rateLimiter, retryAfterFactory); } -} \ No newline at end of file +} diff --git a/src/Polly/RateLimit/RateLimiterFactory.cs b/src/Polly/RateLimit/RateLimiterFactory.cs index ce610c77fb3..70bf40f2ec9 100644 --- a/src/Polly/RateLimit/RateLimiterFactory.cs +++ b/src/Polly/RateLimit/RateLimiterFactory.cs @@ -6,4 +6,4 @@ internal static class RateLimiterFactory { public static IRateLimiter Create(TimeSpan onePer, int bucketCapacity) => new LockFreeTokenBucketRateLimiter(onePer, bucketCapacity); -} \ No newline at end of file +} diff --git a/src/Polly/Registry/IConcurrentPolicyRegistry.cs b/src/Polly/Registry/IConcurrentPolicyRegistry.cs index d87c217b877..903eeee870d 100644 --- a/src/Polly/Registry/IConcurrentPolicyRegistry.cs +++ b/src/Polly/Registry/IConcurrentPolicyRegistry.cs @@ -86,4 +86,4 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// The new policy for the key. This will be either be addPolicy (if the key was /// absent) or the result of updatePolicyFactory (if the key was present). TPolicy AddOrUpdate(TKey key, TPolicy addPolicy, Func updatePolicyFactory) where TPolicy : IsPolicy; -} \ No newline at end of file +} diff --git a/src/Polly/Registry/IPolicyRegistry.cs b/src/Polly/Registry/IPolicyRegistry.cs index 1e85b8f3bd6..0cce3451a0b 100644 --- a/src/Polly/Registry/IPolicyRegistry.cs +++ b/src/Polly/Registry/IPolicyRegistry.cs @@ -41,4 +41,4 @@ public interface IPolicyRegistry : IReadOnlyPolicyRegistry /// Removes all keys and policies from registry. /// void Clear(); -} \ No newline at end of file +} diff --git a/src/Polly/Registry/IReadOnlyPolicyRegistry.cs b/src/Polly/Registry/IReadOnlyPolicyRegistry.cs index 42c876a32b1..c938c637c60 100644 --- a/src/Polly/Registry/IReadOnlyPolicyRegistry.cs +++ b/src/Polly/Registry/IReadOnlyPolicyRegistry.cs @@ -52,4 +52,4 @@ public interface IReadOnlyPolicyRegistry : IEnumerableTrue if exists otherwise false /// is null bool ContainsKey(TKey key); -} \ No newline at end of file +} diff --git a/src/Polly/Registry/PolicyRegistry.cs b/src/Polly/Registry/PolicyRegistry.cs index 703f687c5d1..a2e04bad108 100644 --- a/src/Polly/Registry/PolicyRegistry.cs +++ b/src/Polly/Registry/PolicyRegistry.cs @@ -112,7 +112,7 @@ public TPolicy Get(string key) where TPolicy : IsPolicy => /// True if Policy exists for the provided Key. False otherwise. public bool TryGet(string key, out TPolicy policy) where TPolicy : IsPolicy { - var got = _registry.TryGetValue(key, out var value); + bool got = _registry.TryGetValue(key, out IsPolicy value); policy = got ? (TPolicy)value : default; return got; } @@ -156,7 +156,7 @@ public bool TryRemove(string key, out TPolicy policy) where TPolicy : I { var registry = ThrowIfNotConcurrentImplementation(); - var got = registry.TryRemove(key, out var value); + bool got = registry.TryRemove(key, out IsPolicy value); policy = got ? (TPolicy) value : default; return got; } @@ -268,4 +268,4 @@ public TPolicy AddOrUpdate(string key, TPolicy addPolicy, Func IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); -} \ No newline at end of file +} diff --git a/src/Polly/ResultPredicate.cs b/src/Polly/ResultPredicate.cs index 720f00d2e88..08f7a14c072 100644 --- a/src/Polly/ResultPredicate.cs +++ b/src/Polly/ResultPredicate.cs @@ -6,4 +6,5 @@ /// The passed result, against which to evaluate the predicate. /// The type of results which this predicate can evaluate. /// True if the passed matched the predicate; otherwise, false. -public delegate bool ResultPredicate(TResult result); \ No newline at end of file + +public delegate bool ResultPredicate(TResult result); diff --git a/src/Polly/ResultPredicates.cs b/src/Polly/ResultPredicates.cs index 8664368210e..293ccfbb358 100644 --- a/src/Polly/ResultPredicates.cs +++ b/src/Polly/ResultPredicates.cs @@ -32,4 +32,5 @@ public bool AnyMatch(TResult result) /// Specifies that no result-handling filters are applied or are required. /// public static readonly ResultPredicates None = new ResultPredicates(); -} \ No newline at end of file +} + diff --git a/src/Polly/Retry/AsyncRetryEngine.cs b/src/Polly/Retry/AsyncRetryEngine.cs index 7bec5052d52..dc8997e5732 100644 --- a/src/Polly/Retry/AsyncRetryEngine.cs +++ b/src/Polly/Retry/AsyncRetryEngine.cs @@ -20,8 +20,8 @@ internal static async Task ImplementationAsync( Func, Context, TimeSpan> sleepDurationProvider = null, bool continueOnCapturedContext = false) { - var tryCount = 0; - var sleepDurationsEnumerator = sleepDurationsEnumerable?.GetEnumerator(); + int tryCount = 0; + IEnumerator sleepDurationsEnumerator = sleepDurationsEnumerable?.GetEnumerator(); try { @@ -34,14 +34,14 @@ internal static async Task ImplementationAsync( try { - var result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); + TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext); if (!shouldRetryResultPredicates.AnyMatch(result)) { return result; } - canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerable == null || sleepDurationsEnumerator.MoveNext()); + canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerator == null || sleepDurationsEnumerator.MoveNext()); if (!canRetry) { @@ -52,13 +52,13 @@ internal static async Task ImplementationAsync( } catch (Exception ex) { - var handledException = shouldRetryExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldRetryExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; } - canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerable == null || sleepDurationsEnumerator.MoveNext()); + canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerator == null || sleepDurationsEnumerator.MoveNext()); if (!canRetry) { @@ -71,7 +71,7 @@ internal static async Task ImplementationAsync( if (tryCount < int.MaxValue) { tryCount++; } - var waitDuration = sleepDurationsEnumerator?.Current ?? (sleepDurationProvider?.Invoke(tryCount, outcome, context) ?? TimeSpan.Zero); + TimeSpan waitDuration = sleepDurationsEnumerator?.Current ?? (sleepDurationProvider?.Invoke(tryCount, outcome, context) ?? TimeSpan.Zero); await onRetryAsync(outcome, waitDuration, tryCount, context).ConfigureAwait(continueOnCapturedContext); @@ -86,4 +86,4 @@ internal static async Task ImplementationAsync( sleepDurationsEnumerator?.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Polly/Retry/AsyncRetryPolicy.cs b/src/Polly/Retry/AsyncRetryPolicy.cs index 359a6c83f24..933dc2dd78d 100644 --- a/src/Polly/Retry/AsyncRetryPolicy.cs +++ b/src/Polly/Retry/AsyncRetryPolicy.cs @@ -94,4 +94,5 @@ protected override Task ImplementationAsync(Func onRetry(outcome, i, ctx) #pragma warning restore 1998 - ); + ); } /// @@ -419,7 +419,7 @@ public static AsyncRetryPolicy WaitAndRetryAsync(this PolicyBuilder policyBuilde #pragma warning disable 1998 // async method has no awaits, will run synchronously onRetryAsync: async (outcome, span, _, ctx) => onRetry(outcome, span, ctx) #pragma warning restore 1998 - ); + ); } /// @@ -505,7 +505,7 @@ public static AsyncRetryPolicy WaitAndRetryAsync(this PolicyBuilder policyBuilde if (sleepDurationProvider == null) throw new ArgumentNullException(nameof(sleepDurationProvider)); if (onRetryAsync == null) throw new ArgumentNullException(nameof(onRetryAsync)); - var sleepDurations = Enumerable.Range(1, retryCount) + IEnumerable sleepDurations = Enumerable.Range(1, retryCount) .Select(sleepDurationProvider); return new AsyncRetryPolicy( @@ -544,7 +544,7 @@ public static AsyncRetryPolicy WaitAndRetryAsync(this PolicyBuilder policyBuilde #pragma warning disable 1998 // async method has no awaits, will run synchronously onRetryAsync: async (outcome, span, _, ctx) => onRetry(outcome, span, ctx) #pragma warning restore 1998 - ); + ); } /// @@ -938,9 +938,9 @@ public static AsyncRetryPolicy WaitAndRetryForeverAsync(this PolicyBuilder polic if (onRetryAsync == null) throw new ArgumentNullException(nameof(onRetryAsync)); return policyBuilder.WaitAndRetryForeverAsync( - (retryCount, _) => sleepDurationProvider(retryCount), - (exception, timespan, _) => onRetryAsync(exception, timespan) - ); + (retryCount, _) => sleepDurationProvider(retryCount), + (exception, timespan, _) => onRetryAsync(exception, timespan) + ); } /// @@ -1104,4 +1104,5 @@ public static AsyncRetryPolicy WaitAndRetryForeverAsync(this PolicyBuilder polic sleepDurationProvider: sleepDurationProvider ); } -} \ No newline at end of file +} + diff --git a/src/Polly/Retry/AsyncRetryTResultSyntax.cs b/src/Polly/Retry/AsyncRetryTResultSyntax.cs index 2e67860071f..a50abd1714c 100644 --- a/src/Polly/Retry/AsyncRetryTResultSyntax.cs +++ b/src/Polly/Retry/AsyncRetryTResultSyntax.cs @@ -136,7 +136,7 @@ public static AsyncRetryPolicy RetryAsync(this PolicyBuilder onRetry(outcome, i, ctx) #pragma warning restore 1998 - ); + ); } /// @@ -189,7 +189,7 @@ public static AsyncRetryPolicy RetryForeverAsync(this PolicyBu #pragma warning disable 1998 // async method has no awaits, will run synchronously onRetryAsync: async (DelegateResult outcome, Context _) => onRetry(outcome) #pragma warning restore 1998 - ); + ); } /// @@ -208,7 +208,7 @@ public static AsyncRetryPolicy RetryForeverAsync(this PolicyBu #pragma warning disable 1998 // async method has no awaits, will run synchronously onRetryAsync: async (outcome, i, _) => onRetry(outcome, i) #pragma warning restore 1998 - ); + ); } /// @@ -505,7 +505,7 @@ public static AsyncRetryPolicy WaitAndRetryAsync(this PolicyBu if (sleepDurationProvider == null) throw new ArgumentNullException(nameof(sleepDurationProvider)); if (onRetryAsync == null) throw new ArgumentNullException(nameof(onRetryAsync)); - var sleepDurations = Enumerable.Range(1, retryCount) + IEnumerable sleepDurations = Enumerable.Range(1, retryCount) .Select(sleepDurationProvider); return new AsyncRetryPolicy( @@ -1102,4 +1102,5 @@ public static AsyncRetryPolicy WaitAndRetryForeverAsync(this P sleepDurationProvider: sleepDurationProvider ); } -} \ No newline at end of file +} + diff --git a/src/Polly/Retry/IRetryPolicy.cs b/src/Polly/Retry/IRetryPolicy.cs index 76f85a8fd48..7b205d7a425 100644 --- a/src/Polly/Retry/IRetryPolicy.cs +++ b/src/Polly/Retry/IRetryPolicy.cs @@ -3,6 +3,7 @@ /// /// Defines properties and methods common to all Retry policies. /// + public interface IRetryPolicy : IsPolicy { } @@ -13,4 +14,4 @@ public interface IRetryPolicy : IsPolicy public interface IRetryPolicy : IRetryPolicy { -} \ No newline at end of file +} diff --git a/src/Polly/Retry/RetryEngine.cs b/src/Polly/Retry/RetryEngine.cs index cbf19e07c64..80b9873208e 100644 --- a/src/Polly/Retry/RetryEngine.cs +++ b/src/Polly/Retry/RetryEngine.cs @@ -18,8 +18,8 @@ internal static TResult Implementation( IEnumerable sleepDurationsEnumerable = null, Func, Context, TimeSpan> sleepDurationProvider = null) { - var tryCount = 0; - var sleepDurationsEnumerator = sleepDurationsEnumerable?.GetEnumerator(); + int tryCount = 0; + IEnumerator sleepDurationsEnumerator = sleepDurationsEnumerable?.GetEnumerator(); try { @@ -32,15 +32,15 @@ internal static TResult Implementation( try { - var result = action(context, cancellationToken); + TResult result = action(context, cancellationToken); if (!shouldRetryResultPredicates.AnyMatch(result)) { return result; } - canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerable == null || sleepDurationsEnumerator.MoveNext()); - + canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerator == null || sleepDurationsEnumerator.MoveNext()); + if (!canRetry) { return result; @@ -50,13 +50,13 @@ internal static TResult Implementation( } catch (Exception ex) { - var handledException = shouldRetryExceptionPredicates.FirstMatchOrDefault(ex); + Exception handledException = shouldRetryExceptionPredicates.FirstMatchOrDefault(ex); if (handledException == null) { throw; } - canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerable == null || sleepDurationsEnumerator.MoveNext()); + canRetry = tryCount < permittedRetryCount && (sleepDurationsEnumerator == null || sleepDurationsEnumerator.MoveNext()); if (!canRetry) { @@ -69,8 +69,8 @@ internal static TResult Implementation( if (tryCount < int.MaxValue) { tryCount++; } - var waitDuration = sleepDurationsEnumerator?.Current ?? (sleepDurationProvider?.Invoke(tryCount, outcome, context) ?? TimeSpan.Zero); - + TimeSpan waitDuration = sleepDurationsEnumerator?.Current ?? (sleepDurationProvider?.Invoke(tryCount, outcome, context) ?? TimeSpan.Zero); + onRetry(outcome, waitDuration, tryCount, context); if (waitDuration > TimeSpan.Zero) @@ -85,4 +85,4 @@ internal static TResult Implementation( sleepDurationsEnumerator?.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Polly/Retry/RetryPolicy.cs b/src/Polly/Retry/RetryPolicy.cs index 7d1216df1ef..7ae2f297117 100644 --- a/src/Polly/Retry/RetryPolicy.cs +++ b/src/Polly/Retry/RetryPolicy.cs @@ -21,7 +21,7 @@ internal RetryPolicy( int permittedRetryCount = Int32.MaxValue, IEnumerable sleepDurationsEnumerable = null, Func sleepDurationProvider = null - ) + ) : base(policyBuilder) { _permittedRetryCount = permittedRetryCount; @@ -33,18 +33,18 @@ internal RetryPolicy( /// protected override TResult Implementation(Func action, Context context, CancellationToken cancellationToken) => RetryEngine.Implementation( - action, - context, - cancellationToken, - ExceptionPredicates, - ResultPredicates.None, - (outcome, timespan, retryCount, ctx) => _onRetry(outcome.Exception, timespan, retryCount, ctx), - _permittedRetryCount, - _sleepDurationsEnumerable, - _sleepDurationProvider != null - ? (retryCount, outcome, ctx) => _sleepDurationProvider(retryCount, outcome.Exception, ctx) - : (Func, Context, TimeSpan>)null - ); + action, + context, + cancellationToken, + ExceptionPredicates, + ResultPredicates.None, + (outcome, timespan, retryCount, ctx) => _onRetry(outcome.Exception, timespan, retryCount, ctx), + _permittedRetryCount, + _sleepDurationsEnumerable, + _sleepDurationProvider != null + ? (retryCount, outcome, ctx) => _sleepDurationProvider(retryCount, outcome.Exception, ctx) + : (Func, Context, TimeSpan>)null + ); } /// @@ -86,4 +86,4 @@ protected override TResult Implementation(Func onRetry(outcome, ctx) - ); + return new RetryPolicy( + policyBuilder, + (outcome, _, _, ctx) => onRetry(outcome, ctx) + ); } /// @@ -211,7 +211,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder policyBuilder, int re retryCount, sleepDurationProvider, (outcome, span, _, _) => onRetry(outcome, span) - ); + ); } /// @@ -239,7 +239,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder policyBuilder, int ret retryCount, sleepDurationProvider, (outcome, span, _, ctx) => onRetry(outcome, span, ctx) - ); + ); } /// @@ -266,14 +266,14 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder policyBuilder, int ret if (onRetry == null) throw new ArgumentNullException(nameof(onRetry)); var sleepDurations = Enumerable.Range(1, retryCount) - .Select(sleepDurationProvider); + .Select(sleepDurationProvider); return new RetryPolicy( policyBuilder, onRetry, retryCount, sleepDurationsEnumerable: sleepDurations - ); + ); } /// @@ -317,7 +317,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder policyBuilder, int ret retryCount, sleepDurationProvider, (outcome, span, _, ctx) => onRetry(outcome, span, ctx) - ); + ); } @@ -370,12 +370,12 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder policyBuilder, int ret if (sleepDurationProvider == null) throw new ArgumentNullException(nameof(sleepDurationProvider)); if (onRetry == null) throw new ArgumentNullException(nameof(onRetry)); - return new RetryPolicy( - policyBuilder, - onRetry, - retryCount, - sleepDurationProvider: sleepDurationProvider - ); + return new RetryPolicy( + policyBuilder, + onRetry, + retryCount, + sleepDurationProvider: sleepDurationProvider + ); } /// @@ -457,7 +457,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder policyBuilder, IEnumer policyBuilder, onRetry, sleepDurationsEnumerable: sleepDurations - ); + ); } /// @@ -628,6 +628,6 @@ public static RetryPolicy WaitAndRetryForever(this PolicyBuilder policyBuilder, policyBuilder, (exception, timespan, i, ctx) => onRetry(exception, i, timespan, ctx), sleepDurationProvider: sleepDurationProvider - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/Retry/RetryTResultSyntax.cs b/src/Polly/Retry/RetryTResultSyntax.cs index 5870c70859b..0183dbd6bbd 100644 --- a/src/Polly/Retry/RetryTResultSyntax.cs +++ b/src/Polly/Retry/RetryTResultSyntax.cs @@ -149,7 +149,7 @@ public static RetryPolicy RetryForever(this PolicyBuilder( policyBuilder, (outcome, _, _, ctx) => onRetry(outcome, ctx) - ); + ); } /// @@ -239,7 +239,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder onRetry(outcome, span, ctx) - ); + ); } /// @@ -266,7 +266,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder( policyBuilder, @@ -317,7 +317,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder onRetry(outcome, span, ctx) - ); + ); } /// @@ -385,7 +385,7 @@ public static RetryPolicy WaitAndRetry(this PolicyBuilder onRetry(outcome, span, ctx) - ); + ); } /// @@ -669,6 +669,6 @@ public static RetryPolicy WaitAndRetryForever(this PolicyBuild policyBuilder, (exception, timespan, i, ctx) => onRetry(exception, i, timespan, ctx), sleepDurationProvider: sleepDurationProvider - ); + ); } -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/AsyncTimeoutEngine.cs b/src/Polly/Timeout/AsyncTimeoutEngine.cs index a75f9a1a1c4..8abf0345a61 100644 --- a/src/Polly/Timeout/AsyncTimeoutEngine.cs +++ b/src/Polly/Timeout/AsyncTimeoutEngine.cs @@ -17,14 +17,14 @@ internal static async Task ImplementationAsync( bool continueOnCapturedContext) { cancellationToken.ThrowIfCancellationRequested(); - var timeout = timeoutProvider(context); + TimeSpan timeout = timeoutProvider(context); - using (var timeoutCancellationTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource timeoutCancellationTokenSource = new CancellationTokenSource()) { - using (var combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token)) + using (CancellationTokenSource combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token)) { Task actionTask = null; - var combinedToken = combinedTokenSource.Token; + CancellationToken combinedToken = combinedTokenSource.Token; try { @@ -36,7 +36,7 @@ internal static async Task ImplementationAsync( // else: timeoutStrategy == TimeoutStrategy.Pessimistic - var timeoutTask = timeoutCancellationTokenSource.Token.AsTask(); + Task timeoutTask = timeoutCancellationTokenSource.Token.AsTask(); SystemClock.CancelTokenAfter(timeoutCancellationTokenSource, timeout); @@ -68,12 +68,12 @@ private static Task AsTask(this CancellationToken cancellation // A generalised version of this method would include a hotpath returning a canceled task (rather than setting up a registration) if (cancellationToken.IsCancellationRequested) on entry. This is omitted, since we only start the timeout countdown in the token _after calling this method. IDisposable registration = null; - registration = cancellationToken.Register(() => - { - tcs.TrySetCanceled(); - registration?.Dispose(); - }, useSynchronizationContext: false); + registration = cancellationToken.Register(() => + { + tcs.TrySetCanceled(); + registration?.Dispose(); + }, useSynchronizationContext: false); return tcs.Task; } -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/AsyncTimeoutPolicy.cs b/src/Polly/Timeout/AsyncTimeoutPolicy.cs index eb09ff6becf..2f54da39504 100644 --- a/src/Polly/Timeout/AsyncTimeoutPolicy.cs +++ b/src/Polly/Timeout/AsyncTimeoutPolicy.cs @@ -18,7 +18,7 @@ internal AsyncTimeoutPolicy( Func timeoutProvider, TimeoutStrategy timeoutStrategy, Func onTimeoutAsync - ) + ) { _timeoutProvider = timeoutProvider ?? throw new ArgumentNullException(nameof(timeoutProvider)); _timeoutStrategy = timeoutStrategy; @@ -31,8 +31,9 @@ protected override Task ImplementationAsync( Func> action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncTimeoutEngine.ImplementationAsync( + bool continueOnCapturedContext) + { + return AsyncTimeoutEngine.ImplementationAsync( action, context, cancellationToken, @@ -40,6 +41,7 @@ protected override Task ImplementationAsync( _timeoutStrategy, _onTimeoutAsync, continueOnCapturedContext); + } } /// @@ -77,4 +79,4 @@ protected override Task ImplementationAsync( _timeoutStrategy, _onTimeoutAsync, continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/AsyncTimeoutSyntax.cs b/src/Polly/Timeout/AsyncTimeoutSyntax.cs index b37ed69c0e7..be177da0e65 100644 --- a/src/Polly/Timeout/AsyncTimeoutSyntax.cs +++ b/src/Polly/Timeout/AsyncTimeoutSyntax.cs @@ -382,9 +382,9 @@ public static AsyncTimeoutPolicy TimeoutAsync( if (onTimeoutAsync == null) throw new ArgumentNullException(nameof(onTimeoutAsync)); return new AsyncTimeoutPolicy( - timeoutProvider, - timeoutStrategy, - onTimeoutAsync - ); + timeoutProvider, + timeoutStrategy, + onTimeoutAsync + ); } -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/AsyncTimeoutTResultSyntax.cs b/src/Polly/Timeout/AsyncTimeoutTResultSyntax.cs index ce047e7d75a..0caf403a8bd 100644 --- a/src/Polly/Timeout/AsyncTimeoutTResultSyntax.cs +++ b/src/Polly/Timeout/AsyncTimeoutTResultSyntax.cs @@ -375,9 +375,9 @@ public static AsyncTimeoutPolicy TimeoutAsync(Func( - timeoutProvider, - timeoutStrategy, - onTimeoutAsync - ); + timeoutProvider, + timeoutStrategy, + onTimeoutAsync + ); } -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/ITimeoutPolicy.cs b/src/Polly/Timeout/ITimeoutPolicy.cs index 720fc1f9053..1dc955573ee 100644 --- a/src/Polly/Timeout/ITimeoutPolicy.cs +++ b/src/Polly/Timeout/ITimeoutPolicy.cs @@ -3,6 +3,7 @@ /// /// Defines properties and methods common to all Timeout policies. /// + public interface ITimeoutPolicy : IsPolicy { } @@ -13,4 +14,4 @@ public interface ITimeoutPolicy : IsPolicy public interface ITimeoutPolicy : ITimeoutPolicy { -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/TimeoutEngine.cs b/src/Polly/Timeout/TimeoutEngine.cs index 9c988355367..9371fc100e0 100644 --- a/src/Polly/Timeout/TimeoutEngine.cs +++ b/src/Polly/Timeout/TimeoutEngine.cs @@ -17,13 +17,13 @@ internal static TResult Implementation( Action onTimeout) { cancellationToken.ThrowIfCancellationRequested(); - var timeout = timeoutProvider(context); + TimeSpan timeout = timeoutProvider(context); - using (var timeoutCancellationTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource timeoutCancellationTokenSource = new CancellationTokenSource()) { - using (var combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token)) + using (CancellationTokenSource combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token)) { - var combinedToken = combinedTokenSource.Token; + CancellationToken combinedToken = combinedTokenSource.Token; Task actionTask = null; try @@ -39,7 +39,7 @@ internal static TResult Implementation( SystemClock.CancelTokenAfter(timeoutCancellationTokenSource, timeout); actionTask = Task.Run(() => - action(context, combinedToken) // cancellation token here allows the user delegate to react to cancellation: possibly clear up; then throw an OperationCanceledException. + action(context, combinedToken) // cancellation token here allows the user delegate to react to cancellation: possibly clear up; then throw an OperationCanceledException. , combinedToken); // cancellation token here only allows Task.Run() to not begin the passed delegate at all, if cancellation occurs prior to invoking the delegate. try { @@ -68,4 +68,4 @@ internal static TResult Implementation( } } -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/TimeoutPolicy.cs b/src/Polly/Timeout/TimeoutPolicy.cs index c127f13c291..45098c040a3 100644 --- a/src/Polly/Timeout/TimeoutPolicy.cs +++ b/src/Polly/Timeout/TimeoutPolicy.cs @@ -64,4 +64,4 @@ protected override TResult Implementation(Func +/// Exception thrown when a delegate executed through a does not complete, before the configured timeout. +/// +#if NETSTANDARD2_0 +[Serializable] +#endif +public class TimeoutRejectedException : ExecutionRejectedException { /// - /// Exception thrown when a delegate executed through a does not complete, before the configured timeout. + /// Initializes a new instance of the class. /// -#if NETSTANDARD2_0 - [Serializable] -#endif - public class TimeoutRejectedException : ExecutionRejectedException + public TimeoutRejectedException() { - /// - /// Initializes a new instance of the class. - /// - public TimeoutRejectedException() - { - } + } - /// - /// Initializes a new instance of the class. - /// - /// The message. - public TimeoutRejectedException(string message) : base(message) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The message. + public TimeoutRejectedException(string message) : base(message) + { + } - /// - /// Initializes a new instance of the class. - /// - /// The message. - /// The inner exception. - public TimeoutRejectedException(string message, Exception innerException) : base(message, innerException) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The inner exception. + public TimeoutRejectedException(string message, Exception innerException) : base(message, innerException) + { + } #if NETSTANDARD2_0 - /// - /// Initializes a new instance of the class. - /// - /// The information. - /// The context. - protected TimeoutRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } -#endif + /// + /// Initializes a new instance of the class. + /// + /// The information. + /// The context. + protected TimeoutRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) + { } +#endif } diff --git a/src/Polly/Timeout/TimeoutStrategy.cs b/src/Polly/Timeout/TimeoutStrategy.cs index 905978ddf62..cb16a1fc859 100644 --- a/src/Polly/Timeout/TimeoutStrategy.cs +++ b/src/Polly/Timeout/TimeoutStrategy.cs @@ -15,4 +15,4 @@ public enum TimeoutStrategy /// An pessimistic . The will assume the delegates passed to be executed will not necessarily honor any timing-out , but the policy will still guarantee timing out (and returning to the caller) by other means. /// Pessimistic -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/TimeoutSyntax.cs b/src/Polly/Timeout/TimeoutSyntax.cs index 8b4b07cce14..e66e157b6f4 100644 --- a/src/Polly/Timeout/TimeoutSyntax.cs +++ b/src/Polly/Timeout/TimeoutSyntax.cs @@ -376,8 +376,8 @@ public static TimeoutPolicy Timeout( if (onTimeout == null) throw new ArgumentNullException(nameof(onTimeout)); return new TimeoutPolicy( - timeoutProvider, - timeoutStrategy, - onTimeout); + timeoutProvider, + timeoutStrategy, + onTimeout); } -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/TimeoutTResultSyntax.cs b/src/Polly/Timeout/TimeoutTResultSyntax.cs index 5786392f4c6..4c1724d6d02 100644 --- a/src/Polly/Timeout/TimeoutTResultSyntax.cs +++ b/src/Polly/Timeout/TimeoutTResultSyntax.cs @@ -383,8 +383,8 @@ public static TimeoutPolicy Timeout( if (onTimeout == null) throw new ArgumentNullException(nameof(onTimeout)); return new TimeoutPolicy( - timeoutProvider, - timeoutStrategy, - onTimeout); + timeoutProvider, + timeoutStrategy, + onTimeout); } -} \ No newline at end of file +} diff --git a/src/Polly/Timeout/TimeoutValidator.cs b/src/Polly/Timeout/TimeoutValidator.cs index 9d5616618b0..3f6e96fdf71 100644 --- a/src/Polly/Timeout/TimeoutValidator.cs +++ b/src/Polly/Timeout/TimeoutValidator.cs @@ -16,4 +16,4 @@ internal static void ValidateTimeSpanTimeout(TimeSpan timeout) $"{nameof(timeout)} must be a positive TimeSpan (or Timeout.InfiniteTimeSpan to indicate no timeout)"); } -} \ No newline at end of file +} diff --git a/src/Polly/Utilities/EmptyStruct.cs b/src/Polly/Utilities/EmptyStruct.cs index 9fc8baac2e4..8031bde0e91 100644 --- a/src/Polly/Utilities/EmptyStruct.cs +++ b/src/Polly/Utilities/EmptyStruct.cs @@ -6,4 +6,4 @@ internal struct EmptyStruct { internal static readonly EmptyStruct Instance = new EmptyStruct(); -} \ No newline at end of file +} diff --git a/src/Polly/Utilities/ExceptionExtensions.cs b/src/Polly/Utilities/ExceptionExtensions.cs index 0ac824e7a29..d60cddd49d3 100644 --- a/src/Polly/Utilities/ExceptionExtensions.cs +++ b/src/Polly/Utilities/ExceptionExtensions.cs @@ -20,4 +20,4 @@ public static void RethrowWithOriginalStackTraceIfDiffersFrom(this Exception exc ExceptionDispatchInfo.Capture(exceptionPossiblyToThrow).Throw(); } } -} \ No newline at end of file +} diff --git a/src/Polly/Utilities/KeyHelper.cs b/src/Polly/Utilities/KeyHelper.cs index a93617ef8e6..d4c19bd3c7e 100644 --- a/src/Polly/Utilities/KeyHelper.cs +++ b/src/Polly/Utilities/KeyHelper.cs @@ -5,4 +5,4 @@ namespace Polly.Utilities; internal static class KeyHelper { public static string GuidPart() => Guid.NewGuid().ToString().Substring(0, 8); -} \ No newline at end of file +} diff --git a/src/Polly/Utilities/SystemClock.cs b/src/Polly/Utilities/SystemClock.cs index 87b8b49656a..51d6fc84ae0 100644 --- a/src/Polly/Utilities/SystemClock.cs +++ b/src/Polly/Utilities/SystemClock.cs @@ -62,4 +62,4 @@ public static void Reset() CancelTokenAfter = (tokenSource, timespan) => tokenSource.CancelAfter(timespan); } -} \ No newline at end of file +} diff --git a/src/Polly/Utilities/TaskHelper.cs b/src/Polly/Utilities/TaskHelper.cs index 0bc8eb3d007..82cb36491d9 100644 --- a/src/Polly/Utilities/TaskHelper.cs +++ b/src/Polly/Utilities/TaskHelper.cs @@ -12,9 +12,9 @@ public static class TaskHelper /// public static Task EmptyTask = #if NETSTANDARD1_1 - Task.FromResult(true) + Task.FromResult(true) #else - Task.CompletedTask + Task.CompletedTask #endif ; -} \ No newline at end of file +} diff --git a/src/Polly/Utilities/TimedLock.cs b/src/Polly/Utilities/TimedLock.cs index db9952a3599..8d01774a39a 100644 --- a/src/Polly/Utilities/TimedLock.cs +++ b/src/Polly/Utilities/TimedLock.cs @@ -2,6 +2,7 @@ using System.Threading; namespace Polly.Utilities; + // Adapted from the link below, with slight modifications. // http://www.interact-sw.co.uk/iangblog/2004/04/26/yetmoretimedlocking @@ -21,15 +22,17 @@ internal struct TimedLock : IDisposable #if DEBUG private static readonly TimeSpan LockTimeout = TimeSpan.FromSeconds(5); #else - private static readonly TimeSpan LockTimeout = TimeSpan.FromMilliseconds(int.MaxValue); + private static readonly TimeSpan LockTimeout = TimeSpan.FromMilliseconds(int.MaxValue); #endif - public static TimedLock Lock(object o) => - Lock(o, LockTimeout); + public static TimedLock Lock(object o) + { + return Lock(o, LockTimeout); + } private static TimedLock Lock(object o, TimeSpan timeout) { - var tl = new TimedLock(o); + TimedLock tl = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { #if DEBUG @@ -74,7 +77,7 @@ private class Sentinel // call Dispose, which means we've failed to leave // a monitor! #if NETSTANDARD2_0 - System.Diagnostics.Debug.Fail("Undisposed lock"); + System.Diagnostics.Debug.Fail("Undisposed lock"); #endif } } @@ -88,4 +91,4 @@ internal class LockTimeoutException : Exception public LockTimeoutException() : base("Timeout waiting for lock") { } -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/AsyncPolicyWrap.ContextAndKeys.cs b/src/Polly/Wrap/AsyncPolicyWrap.ContextAndKeys.cs index 468a49d4d49..4dc57e16620 100644 --- a/src/Polly/Wrap/AsyncPolicyWrap.ContextAndKeys.cs +++ b/src/Polly/Wrap/AsyncPolicyWrap.ContextAndKeys.cs @@ -36,4 +36,4 @@ internal override void SetPolicyContext(Context executionContext, out string pri base.SetPolicyContext(executionContext, out _, out _); } -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/AsyncPolicyWrap.cs b/src/Polly/Wrap/AsyncPolicyWrap.cs index 8897797bfb7..af3e77e5117 100644 --- a/src/Polly/Wrap/AsyncPolicyWrap.cs +++ b/src/Polly/Wrap/AsyncPolicyWrap.cs @@ -174,4 +174,4 @@ protected override Task ImplementationAsync(Func)} must define an outer policy."); } } -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/AsyncPolicyWrapEngine.cs b/src/Polly/Wrap/AsyncPolicyWrapEngine.cs index f82cc6609f3..5c966ed9541 100644 --- a/src/Polly/Wrap/AsyncPolicyWrapEngine.cs +++ b/src/Polly/Wrap/AsyncPolicyWrapEngine.cs @@ -7,7 +7,7 @@ namespace Polly.Wrap; internal static class AsyncPolicyWrapEngine { internal static async Task ImplementationAsync( - Func> func, + Func> func, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext, @@ -19,14 +19,14 @@ internal static async Task ImplementationAsync( ctx, ct, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext), + ).ConfigureAwait(continueOnCapturedContext), context, cancellationToken, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext); + ).ConfigureAwait(continueOnCapturedContext); internal static async Task ImplementationAsync( - Func> func, + Func> func, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext, @@ -38,11 +38,11 @@ internal static async Task ImplementationAsync( ctx, ct, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext), + ).ConfigureAwait(continueOnCapturedContext), context, cancellationToken, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext); + ).ConfigureAwait(continueOnCapturedContext); internal static async Task ImplementationAsync( Func> func, @@ -57,19 +57,19 @@ internal static async Task ImplementationAsync( ctx, ct, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext), + ).ConfigureAwait(continueOnCapturedContext), context, cancellationToken, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext); + ).ConfigureAwait(continueOnCapturedContext); internal static async Task ImplementationAsync( - Func> func, - Context context, - CancellationToken cancellationToken, - bool continueOnCapturedContext, - IAsyncPolicy outerPolicy, - IAsyncPolicy innerPolicy) + Func> func, + Context context, + CancellationToken cancellationToken, + bool continueOnCapturedContext, + IAsyncPolicy outerPolicy, + IAsyncPolicy innerPolicy) => await outerPolicy.ExecuteAsync( async (ctx, ct) => await innerPolicy.ExecuteAsync( func, @@ -95,10 +95,10 @@ internal static async Task ImplementationAsync( ctx, ct, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext), + ).ConfigureAwait(continueOnCapturedContext), context, cancellationToken, continueOnCapturedContext - ).ConfigureAwait(continueOnCapturedContext); + ).ConfigureAwait(continueOnCapturedContext); -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/AsyncPolicyWrapSyntax.cs b/src/Polly/Wrap/AsyncPolicyWrapSyntax.cs index e06d6bab7c5..fc013078b70 100644 --- a/src/Polly/Wrap/AsyncPolicyWrapSyntax.cs +++ b/src/Polly/Wrap/AsyncPolicyWrapSyntax.cs @@ -18,7 +18,7 @@ public AsyncPolicyWrap WrapAsync(IAsyncPolicy innerPolicy) return new AsyncPolicyWrap( this, innerPolicy - ); + ); } /// @@ -34,7 +34,7 @@ public AsyncPolicyWrap WrapAsync(IAsyncPolicy innerPo return new AsyncPolicyWrap( this, innerPolicy - ); + ); } } @@ -52,7 +52,7 @@ public AsyncPolicyWrap WrapAsync(IAsyncPolicy innerPolicy) return new AsyncPolicyWrap( this, innerPolicy - ); + ); } /// @@ -67,7 +67,7 @@ public AsyncPolicyWrap WrapAsync(IAsyncPolicy innerPolicy) return new AsyncPolicyWrap( this, innerPolicy - ); + ); } } @@ -169,4 +169,4 @@ public static AsyncPolicyWrap WrapAsync(this IAsyncPolicy)outerPolicy).WrapAsync(innerPolicy); } -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/IPolicyWrap.cs b/src/Polly/Wrap/IPolicyWrap.cs index c475fc1a559..be593f26cc1 100644 --- a/src/Polly/Wrap/IPolicyWrap.cs +++ b/src/Polly/Wrap/IPolicyWrap.cs @@ -22,4 +22,4 @@ public interface IPolicyWrap : IsPolicy public interface IPolicyWrap : IPolicyWrap { -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/IPolicyWrapExtension.cs b/src/Polly/Wrap/IPolicyWrapExtension.cs index abe5c7974e6..3348254894f 100644 --- a/src/Polly/Wrap/IPolicyWrapExtension.cs +++ b/src/Polly/Wrap/IPolicyWrapExtension.cs @@ -78,4 +78,4 @@ public static TPolicy GetPolicy(this IPolicyWrap policyWrap, Func().SingleOrDefault(filter); } -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/PolicyWrap.ContextAndKeys.cs b/src/Polly/Wrap/PolicyWrap.ContextAndKeys.cs index a8f2659cdbf..6ed12582402 100644 --- a/src/Polly/Wrap/PolicyWrap.ContextAndKeys.cs +++ b/src/Polly/Wrap/PolicyWrap.ContextAndKeys.cs @@ -36,4 +36,4 @@ internal override void SetPolicyContext(Context executionContext, out string pri base.SetPolicyContext(executionContext, out _, out _); } -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/PolicyWrap.cs b/src/Polly/Wrap/PolicyWrap.cs index 8c5843cc908..aef1864cfb0 100644 --- a/src/Polly/Wrap/PolicyWrap.cs +++ b/src/Polly/Wrap/PolicyWrap.cs @@ -160,4 +160,4 @@ protected override TResult Implementation(Func)} must define an outer policy."); } } -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/PolicyWrapEngine.cs b/src/Polly/Wrap/PolicyWrapEngine.cs index 0ecc4316bc5..a0809615535 100644 --- a/src/Polly/Wrap/PolicyWrapEngine.cs +++ b/src/Polly/Wrap/PolicyWrapEngine.cs @@ -14,34 +14,34 @@ internal static TResult Implementation( => outerPolicy.Execute((ctx, ct) => innerPolicy.Execute(func, ctx, ct), context, cancellationToken); internal static TResult Implementation( - Func func, - Context context, - CancellationToken cancellationToken, - ISyncPolicy outerPolicy, - ISyncPolicy innerPolicy) + Func func, + Context context, + CancellationToken cancellationToken, + ISyncPolicy outerPolicy, + ISyncPolicy innerPolicy) => outerPolicy.Execute((ctx, ct) => innerPolicy.Execute(func, ctx, ct), context, cancellationToken); internal static TResult Implementation( - Func func, - Context context, - CancellationToken cancellationToken, - ISyncPolicy outerPolicy, - ISyncPolicy innerPolicy) + Func func, + Context context, + CancellationToken cancellationToken, + ISyncPolicy outerPolicy, + ISyncPolicy innerPolicy) => outerPolicy.Execute((ctx, ct) => innerPolicy.Execute(func, ctx, ct), context, cancellationToken); internal static TResult Implementation( - Func func, - Context context, - CancellationToken cancellationToken, - ISyncPolicy outerPolicy, - ISyncPolicy innerPolicy) + Func func, + Context context, + CancellationToken cancellationToken, + ISyncPolicy outerPolicy, + ISyncPolicy innerPolicy) => outerPolicy.Execute((ctx, ct) => innerPolicy.Execute(func, ctx, ct), context, cancellationToken); internal static void Implementation( - Action action, - Context context, - CancellationToken cancellationToken, - ISyncPolicy outerPolicy, - ISyncPolicy innerPolicy) + Action action, + Context context, + CancellationToken cancellationToken, + ISyncPolicy outerPolicy, + ISyncPolicy innerPolicy) => outerPolicy.Execute((ctx, ct) => innerPolicy.Execute(action, ctx, ct), context, cancellationToken); -} \ No newline at end of file +} diff --git a/src/Polly/Wrap/PolicyWrapSyntax.cs b/src/Polly/Wrap/PolicyWrapSyntax.cs index c83b77363f5..0a057f6d82b 100644 --- a/src/Polly/Wrap/PolicyWrapSyntax.cs +++ b/src/Polly/Wrap/PolicyWrapSyntax.cs @@ -18,7 +18,7 @@ public PolicyWrap Wrap(ISyncPolicy innerPolicy) return new PolicyWrap( this, innerPolicy - ); + ); } /// @@ -34,7 +34,7 @@ public PolicyWrap Wrap(ISyncPolicy innerPolicy) return new PolicyWrap( this, innerPolicy - ); + ); } } @@ -52,7 +52,7 @@ public PolicyWrap Wrap(ISyncPolicy innerPolicy) return new PolicyWrap( this, innerPolicy - ); + ); } /// @@ -67,7 +67,7 @@ public PolicyWrap Wrap(ISyncPolicy innerPolicy) return new PolicyWrap( this, innerPolicy - ); + ); } } @@ -169,4 +169,4 @@ public static PolicyWrap Wrap(this ISyncPolicy outerP if (outerPolicy == null) throw new ArgumentNullException(nameof(outerPolicy)); return ((Policy)outerPolicy).Wrap(innerPolicy); } -} \ No newline at end of file +}