Skip to content

Update to xunit v3 #2440

New issue

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

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

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -47,7 +47,8 @@
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
<PackageVersion Include="System.Text.Json" Version="9.0.0" />
<PackageVersion Include="System.ValueTuple" Version="4.5.0" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.0.0" />
<PackageVersion Include="xunit.v3" Version="1.0.1" />
<PackageVersion Include="xunit.v3.assert" Version="1.0.1" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion build.cake
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ var configuration = Argument<string>("configuration", "Release");
// EXTERNAL NUGET TOOLS
//////////////////////////////////////////////////////////////////////

#Tool "xunit.runner.console&version=2.9.3"
#Tool "xunit.v3.runner.console&version=1.0.1"
#Tool "dotnet-stryker&version=4.5.0"

//////////////////////////////////////////////////////////////////////
2 changes: 1 addition & 1 deletion eng/Test.targets
Original file line number Diff line number Diff line change
@@ -17,8 +17,8 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="ReportGenerator" PrivateAssets="all" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" PrivateAssets="all" />
<PackageReference Include="xunit.v3" />
</ItemGroup>

<PropertyGroup Condition="$([MSBuild]::GetTargetFrameworkIdentifier('$(TargetFramework)')) != '.NETFramework'">
2 changes: 1 addition & 1 deletion src/Snippets/Snippets.csproj
Original file line number Diff line number Diff line change
@@ -18,7 +18,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.v3.assert" />
</ItemGroup>

<ItemGroup>
Original file line number Diff line number Diff line change
@@ -29,7 +29,7 @@ public void Ctor_Isolated(bool isolated)
[Theory]
public async Task IsolateAsync_NotInitialized_Ok(bool closedAfter)
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var control = new CircuitBreakerManualControl();
await control.IsolateAsync(cancellationToken);
if (closedAfter)
@@ -57,7 +57,7 @@ public async Task ResetAsync_NotInitialized_Ok()
var control = new CircuitBreakerManualControl();

await control
.Invoking(c => c.CloseAsync())
.Invoking(c => c.CloseAsync(TestContext.Current.CancellationToken))
.Should()
.NotThrowAsync();
}
@@ -66,7 +66,7 @@ await control
public async Task Initialize_Twice_Ok()
{
int called = 0;
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var control = new CircuitBreakerManualControl();
control.Initialize(_ => Task.CompletedTask, _ => Task.CompletedTask);
control.Initialize(_ => { called++; return Task.CompletedTask; }, _ => { called++; return Task.CompletedTask; });
@@ -81,7 +81,7 @@ public async Task Initialize_Twice_Ok()
public async Task Initialize_DisposeRegistration_ShuldBeCancelled()
{
int called = 0;
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var control = new CircuitBreakerManualControl();
var reg = control.Initialize(_ => { called++; return Task.CompletedTask; }, _ => { called++; return Task.CompletedTask; });

@@ -99,7 +99,7 @@ public async Task Initialize_DisposeRegistration_ShuldBeCancelled()
[Fact]
public async Task Initialize_Ok()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var control = new CircuitBreakerManualControl();
var isolateCalled = false;
var resetCalled = false;
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@ public class CircuitBreakerOptionsTests
public async Task ShouldHandle_EnsureDefaults()
{
var options = new CircuitBreakerStrategyOptions();
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

(await options.ShouldHandle(new CircuitBreakerPredicateArguments<object>(context, Outcome.FromResult<object>("dummy")))).Should().Be(false);
(await options.ShouldHandle(new CircuitBreakerPredicateArguments<object>(context, Outcome.FromException<object>(new OperationCanceledException())))).Should().Be(false);
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class CircuitBreakerPredicateArgumentsTests
public static void Ctor_Ok()
{
var args = new CircuitBreakerPredicateArguments<int>(
ResilienceContextPool.Shared.Get(CancellationToken.None),
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken),
Outcome.FromResult(1));

args.Context.Should().NotBeNull();
Original file line number Diff line number Diff line change
@@ -64,7 +64,7 @@ public void AddCircuitBreaker_Validation()
[Fact]
public void AddCircuitBreaker_IntegrationTest()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
int opened = 0;
int closed = 0;
int halfOpened = 0;
@@ -127,7 +127,7 @@ public void AddCircuitBreaker_IntegrationTest()
[Fact]
public void AddCircuitBreaker_IntegrationTest_WithBreakDurationGenerator()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
int opened = 0;
int closed = 0;
int halfOpened = 0;
@@ -191,7 +191,7 @@ public void AddCircuitBreaker_IntegrationTest_WithBreakDurationGenerator()
[Fact]
public async Task AddCircuitBreakers_WithIsolatedManualControl_ShouldBeIsolated()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var manualControl = new CircuitBreakerManualControl();
await manualControl.IsolateAsync(cancellationToken);

Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ public CircuitBreakerResilienceStrategyTests()
null);
}

private static CancellationToken CancellationToken => CancellationToken.None;
private static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

[Fact]
public void Ctor_Ok() =>
Original file line number Diff line number Diff line change
@@ -26,7 +26,7 @@ public async Task ResetAsync_NotInitialized_Throws()
var control = new CircuitBreakerManualControl();

await control
.Invoking(c => c.CloseAsync(CancellationToken.None))
.Invoking(c => c.CloseAsync(TestContext.Current.CancellationToken))
.Should()
.NotThrowAsync<InvalidOperationException>();
}
Original file line number Diff line number Diff line change
@@ -26,7 +26,7 @@ public void Ctor_EnsureDefaults()
public async Task IsolateAsync_Ok()
{
// arrange
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
bool called = false;
_options.OnOpened = args =>
{
@@ -69,7 +69,7 @@ public async Task IsolateAsync_Ok()
public async Task BreakAsync_Ok()
{
// arrange
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
bool called = false;
_options.OnClosed = args =>
{
@@ -102,7 +102,7 @@ public async Task BreakAsync_Ok()
[Fact]
public async Task Disposed_EnsureThrows()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

var controller = CreateController();
controller.Dispose();
@@ -121,7 +121,7 @@ public async Task Disposed_EnsureThrows()
[Fact]
public async Task OnActionPreExecute_CircuitOpenedByValue()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();

await OpenCircuit(controller, Outcome.FromResult(99));
@@ -138,7 +138,7 @@ public async Task OnActionPreExecute_CircuitOpenedByValue()
public async Task OnActionPreExecute_CircuitOpened_EnsureExceptionStackTraceDoesNotGrow(bool innerException)
{
var stacks = new List<string>();
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();

await OpenCircuit(
@@ -175,7 +175,7 @@ await OpenCircuit(
[Fact]
public async Task HalfOpen_EnsureBreakDuration()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();

await TransitionToState(controller, CircuitState.HalfOpen, context);
@@ -187,7 +187,7 @@ public async Task HalfOpen_EnsureBreakDuration()
[Theory]
public async Task HalfOpen_EnsureCorrectStateTransitionAfterExecution(bool success)
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();

await TransitionToState(controller, CircuitState.HalfOpen, context);
@@ -213,7 +213,7 @@ public async Task HalfOpen_EnsureCorrectStateTransitionAfterExecution(bool succe
[Fact]
public async Task OnActionPreExecute_CircuitOpenedByException()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();

await OpenCircuit(controller, Outcome.FromException<int>(new InvalidOperationException()));
@@ -227,7 +227,7 @@ public async Task OnActionPreExecute_CircuitOpenedByException()
public async Task OnActionFailure_EnsureLock()
{
// arrange
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var context = ResilienceContextPool.Shared.Get(cancellationToken);

using var executing = new ManualResetEvent(false);
@@ -261,7 +261,7 @@ public async Task OnActionFailure_EnsureLock()
public async Task OnActionPreExecute_HalfOpen()
{
// arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var called = false;
_options.OnHalfOpened = _ =>
{
@@ -293,7 +293,7 @@ public async Task OnActionPreExecute_HalfOpen()
public async Task OnActionSuccess_EnsureCorrectBehavior(CircuitState state, CircuitState expectedState)
{
// arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var called = false;
_options.OnClosed = args =>
{
@@ -329,7 +329,7 @@ public async Task OnActionSuccess_EnsureCorrectBehavior(CircuitState state, Circ
public async Task OnActionFailureAsync_EnsureCorrectBehavior(CircuitState state, CircuitState expectedState, bool shouldBreak)
{
// arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var called = false;
_options.OnOpened = args =>
{
@@ -370,7 +370,7 @@ public async Task OnActionFailureAsync_EnsureCorrectBehavior(CircuitState state,
public async Task OnActionFailureAsync_EnsureBreakDurationGeneration()
{
// arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
_options.BreakDurationGenerator = static args =>
{
args.FailureCount.Should().Be(1);
@@ -402,7 +402,7 @@ public async Task OnActionFailureAsync_EnsureBreakDurationGeneration()
public async Task BreakDurationGenerator_EnsureHalfOpenAttempts()
{
// arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var halfOpenAttempts = new List<int>();

_options.BreakDurationGenerator = args =>
@@ -440,7 +440,7 @@ public async Task BreakDurationGenerator_EnsureHalfOpenAttempts()
public async Task OnActionFailureAsync_EnsureBreakDurationNotOverflow(bool overflow)
{
// arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();
var shouldBreak = true;
await TransitionToState(controller, CircuitState.HalfOpen, context);
@@ -475,7 +475,7 @@ public async Task OnActionFailureAsync_EnsureBreakDurationNotOverflow(bool overf
public async Task OnActionFailureAsync_VoidResult_EnsureBreakingExceptionNotSet()
{
// arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();
bool shouldBreak = true;
await TransitionToState(controller, CircuitState.Open, context);
@@ -497,7 +497,7 @@ public async Task OnActionFailureAsync_VoidResult_EnsureBreakingExceptionNotSet(
[Fact]
public async Task Flow_Closed_HalfOpen_Closed()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
using var controller = CreateController();

await TransitionToState(controller, CircuitState.HalfOpen, context);
@@ -512,7 +512,7 @@ public async Task Flow_Closed_HalfOpen_Closed()
[Fact]
public async Task Flow_Closed_HalfOpen_Open_HalfOpen_Closed()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var context = ResilienceContextPool.Shared.Get(cancellationToken);

using var controller = CreateController();
@@ -550,7 +550,7 @@ public async Task Flow_Closed_HalfOpen_Open_HalfOpen_Closed()
[Fact]
public async Task ExecuteScheduledTask_Async_Ok()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var context = ResilienceContextPool.Shared.Get(cancellationToken);

var source = new TaskCompletionSource<string>();
@@ -605,7 +605,7 @@ private async Task OpenCircuit(CircuitStateController<int> controller, Outcome<i

await controller.OnHandledOutcomeAsync(
outcome ?? Outcome.FromResult(10),
ResilienceContextPool.Shared.Get().Initialize<int>(true));
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken).Initialize<int>(true));
}

private void AdvanceTime(TimeSpan timespan) => _timeProvider.Advance(timespan);
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ namespace Polly.Core.Tests.CircuitBreaker.Controller;

public class ScheduledTaskExecutorTests
{
private static CancellationToken CancellationToken => CancellationToken.None;
private static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

[Fact]
public async Task ScheduleTask_Success_EnsureExecuted()
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnCircuitClosedArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new OnCircuitClosedArguments<int>(context, Outcome.FromResult(1), true);
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnCircuitHalfOpenedArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var target = new OnCircuitHalfOpenedArguments(context);
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnCircuitOpenedArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new OnCircuitOpenedArguments<int>(context, Outcome.FromResult(1), TimeSpan.FromSeconds(2), true);
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Fallback/FallbackHandlerTests.cs
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ public class FallbackHandlerTests
public async Task GenerateAction_Generic_Ok()
{
var handler = FallbackHelper.CreateHandler(_ => true, () => Outcome.FromResult("secondary"));
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var outcome = await handler.GetFallbackOutcomeAsync(new FallbackActionArguments<string>(context, Outcome.FromResult("primary")))!;

outcome.Result.Should().Be("secondary");
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@ public void Handle_Result_Ok()
_options.OnFallback = _ => { called = true; return default; };
SetHandler(outcome => outcome.Result == "error", () => Outcome.FromResult("success"));

Create().Execute(_ => "error").Should().Be("success");
Create().Execute(_ => "error", TestContext.Current.CancellationToken).Should().Be("success");

_args.Should().ContainSingle(v => v.Arguments is OnFallbackArguments<string>);
called.Should().BeTrue();
@@ -53,7 +53,7 @@ public void ShouldHandle_ArgumentsSetCorrectly(bool handle)
return Outcome.FromResultAsValueTask("fallback");
});

var result = Create().Execute(_ => "ok");
var result = Create().Execute(_ => "ok", TestContext.Current.CancellationToken);

if (handle)
{
@@ -81,7 +81,7 @@ public void Handle_Exception_Ok()
_options.OnFallback = _ => { called = true; return default; };

SetHandler(outcome => outcome.Exception is InvalidOperationException, () => Outcome.FromResult("secondary"));
Create().Execute<string>(_ => throw new InvalidOperationException()).Should().Be("secondary");
Create().Execute<string>(_ => throw new InvalidOperationException(), TestContext.Current.CancellationToken).Should().Be("secondary");

_args.Should().ContainSingle(v => v.Arguments is OnFallbackArguments<string>);
called.Should().BeTrue();
@@ -112,7 +112,7 @@ public void Handle_UnhandledResult_Ok()
_options.OnFallback = _ => { called = true; return default; };
SetHandler(outcome => false, () => Outcome.FromResult("secondary"));

Create().Execute(_ => "primary").Should().Be("primary");
Create().Execute(_ => "primary", TestContext.Current.CancellationToken).Should().Be("primary");
_args.Should().BeEmpty();
called.Should().BeFalse();
fallbackActionCalled.Should().BeFalse();
Original file line number Diff line number Diff line change
@@ -21,7 +21,7 @@ public void Ctor_EnsureDefaults()
public async Task ShouldHandle_EnsureDefaults()
{
var options = new FallbackStrategyOptions<int>();
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

(await options.ShouldHandle(new FallbackPredicateArguments<int>(context, Outcome.FromResult(0)))).Should().Be(false);
(await options.ShouldHandle(new FallbackPredicateArguments<int>(context, Outcome.FromException<int>(new OperationCanceledException())))).Should().Be(false);
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ public class HedgingControllerTests
[Fact]
public async Task Pooling_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var telemetry = TestUtilities.CreateResilienceTelemetry(_ => { });
var controller = new HedgingController<int>(telemetry, new HedgingTimeProvider(), HedgingHelper.CreateHandler<int>(_ => false, args => null), 3);

Original file line number Diff line number Diff line change
@@ -141,7 +141,7 @@ public async Task TryWaitForCompletedExecutionAsync_SynchronousExecution_Ok()

var task = context.TryWaitForCompletedExecutionAsync(System.Threading.Timeout.InfiniteTimeSpan).AsTask();
#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
task.Wait(20).Should().BeFalse();
task.Wait(20, TestContext.Current.CancellationToken).Should().BeFalse();
#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
_timeProvider.Advance(TimeSpan.FromDays(1));
await task;
@@ -164,7 +164,7 @@ public async Task TryWaitForCompletedExecutionAsync_HedgedExecution_Ok()
var count = _timeProvider.TimerEntries.Count;
var task = context.TryWaitForCompletedExecutionAsync(hedgingDelay).AsTask();
#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
task.Wait(20).Should().BeFalse();
task.Wait(20, TestContext.Current.CancellationToken).Should().BeFalse();
#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
_timeProvider.TimerEntries.Should().HaveCount(count + 1);
_timeProvider.TimerEntries.Last().Delay.Should().Be(hedgingDelay);
@@ -386,7 +386,7 @@ public async Task Complete_EnsurePendingTasksCleaned()

var pending = context.Tasks[1].ExecutionTaskSafe!;
#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
pending.Wait(10).Should().BeFalse();
pending.Wait(10, TestContext.Current.CancellationToken).Should().BeFalse();
#pragma warning restore xUnit1031 // Do not use blocking task operations in test method

context.Tasks[0].AcceptOutcome();
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class HedgingActionGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var primaryContext = ResilienceContextPool.Shared.Get(cancellationToken);
var actionContext = ResilienceContextPool.Shared.Get(cancellationToken);

Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class HedgingDelayGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new HedgingDelayGeneratorArguments(context, 5);
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Hedging/HedgingHandlerTests.cs
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ public static class HedgingHandlerTests
public static async Task GenerateAction_Generic_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

var handler = new HedgingHandler<string>(
args => PredicateResult.True(),
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class HedgingPredicateArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new HedgingPredicateArguments<int>(context, Outcome.FromResult(1));
Original file line number Diff line number Diff line change
@@ -59,7 +59,7 @@ public async Task AddHedging_IntegrationTest()
})
.Build();

var result = await strategy.ExecuteAsync(token => new ValueTask<string>("error"));
var result = await strategy.ExecuteAsync(token => new ValueTask<string>("error"), TestContext.Current.CancellationToken);
result.Should().Be("success");
hedgingCount.Should().Be(3);
}
@@ -91,7 +91,7 @@ public async Task AddHedging_IntegrationTestWithRealDelay()
})
.Build();

var result = await strategy.ExecuteAsync(token => new ValueTask<string>("error"));
var result = await strategy.ExecuteAsync(token => new ValueTask<string>("error"), TestContext.Current.CancellationToken);
result.Should().Be("success");
}
}
Original file line number Diff line number Diff line change
@@ -2,7 +2,6 @@
using Polly.Hedging.Utils;
using Polly.Telemetry;
using Polly.Testing;
using Xunit.Abstractions;

namespace Polly.Core.Tests.Hedging;

6 changes: 3 additions & 3 deletions test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@ public void Ctor_EnsureDefaults()
public async Task HedgingActionGenerator_EnsureDefaults(bool synchronous)
{
var options = new HedgingStrategyOptions<int>();
var context = ResilienceContextPool.Shared.Get().Initialize<int>(synchronous);
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken).Initialize<int>(synchronous);
var threadId = Thread.CurrentThread.ManagedThreadId;
using var semaphore = new SemaphoreSlim(0);

@@ -46,7 +46,7 @@ public async Task HedgingActionGenerator_EnsureDefaults(bool synchronous)

var task = action();
semaphore
.Wait(TimeSpan.FromSeconds(20))
.Wait(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken)
.Should()
.BeTrue("The test thread failed to complete within the timeout");
(await task).Result.Should().Be(99);
@@ -56,7 +56,7 @@ public async Task HedgingActionGenerator_EnsureDefaults(bool synchronous)
public async Task ShouldHandle_EnsureDefaults()
{
var options = new HedgingStrategyOptions<int>();
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

(await options.ShouldHandle(new HedgingPredicateArguments<int>(context, Outcome.FromResult(0)))).Should().Be(false);
(await options.ShouldHandle(new HedgingPredicateArguments<int>(context, Outcome.FromException<int>(new OperationCanceledException())))).Should().Be(false);
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Hedging/OnHedgingArgumentsTests.cs
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnHedgingArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var primaryContext = ResilienceContextPool.Shared.Get(cancellationToken);
var actionContext = ResilienceContextPool.Shared.Get(cancellationToken);

Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ public partial class IssuesTests
[Fact]
public void CircuitBreakerStateSharing_959()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var options = new CircuitBreakerStrategyOptions
{
FailureRatio = 1,
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ public void FlowingContext_849()
.Build();

// execute the retry
strategy.Execute(_ => 0);
strategy.Execute(_ => 0, TestContext.Current.CancellationToken);

contextChecked.Should().BeTrue();
}
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ public partial class IssuesTests
[Fact]
public void HandleMultipleResults_898()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var isRetryKey = new ResiliencePropertyKey<bool>("is-retry");
var options = new RetryStrategyOptions
{
1 change: 1 addition & 0 deletions test/Polly.Core.Tests/Polly.Core.Tests.csproj
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@
<Nullable>enable</Nullable>
<Threshold>100</Threshold>
<NoWarn>$(NoWarn);S6966;SA1600;SA1204</NoWarn>
<OutputType>Exe</OutputType>
<Include>[Polly.Core]*</Include>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
</PropertyGroup>
8 changes: 4 additions & 4 deletions test/Polly.Core.Tests/PredicateBuilderTests.cs
Original file line number Diff line number Diff line change
@@ -86,7 +86,7 @@ public void CreatePredicate_NotConfigured_Throws()
[Fact]
public async Task Operator_RetryStrategyOptions_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var options = new RetryStrategyOptions<string>
{
ShouldHandle = new PredicateBuilder<string>().HandleResult("error")
@@ -100,7 +100,7 @@ public async Task Operator_RetryStrategyOptions_Ok()
[Fact]
public async Task Operator_FallbackStrategyOptions_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var options = new FallbackStrategyOptions<string>
{
ShouldHandle = new PredicateBuilder<string>().HandleResult("error")
@@ -114,7 +114,7 @@ public async Task Operator_FallbackStrategyOptions_Ok()
[Fact]
public async Task Operator_HedgingStrategyOptions_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var options = new HedgingStrategyOptions<string>
{
ShouldHandle = new PredicateBuilder<string>().HandleResult("error")
@@ -128,7 +128,7 @@ public async Task Operator_HedgingStrategyOptions_Ok()
[Fact]
public async Task Operator_AdvancedCircuitBreakerStrategyOptions_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var options = new CircuitBreakerStrategyOptions<string>
{
ShouldHandle = new PredicateBuilder<string>().HandleResult("error")
8 changes: 4 additions & 4 deletions test/Polly.Core.Tests/ResilienceContextPoolTests.cs
Original file line number Diff line number Diff line change
@@ -12,12 +12,12 @@ public void Shared_SameInstance() =>

[Fact]
public void Get_EnsureNotNull() =>
ResilienceContextPool.Shared.Get().Should().NotBeNull();
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken).Should().NotBeNull();

[Fact]
public void Get_EnsureDefaults()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var context = ResilienceContextPool.Shared.Get(cancellationToken);

AssertDefaults(context, cancellationToken);
@@ -38,15 +38,15 @@ public void Get_ContinueOnCapturedContextDefault_ShouldBeFalse()
{
using var token = new CancellationTokenSource();

var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

context.ContinueOnCapturedContext.Should().BeFalse();
}

[Fact]
public void Get_ContinueOnCapturedContext_Ok()
{
var context = ResilienceContextPool.Shared.Get(true);
var context = ResilienceContextPool.Shared.Get(true, TestContext.Current.CancellationToken);

context.ContinueOnCapturedContext.Should().Be(true);
}
6 changes: 3 additions & 3 deletions test/Polly.Core.Tests/ResilienceContextTests.cs
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ public class ResilienceContextTests
[InlineData(false)]
public void Initialize_Typed_Ok(bool synchronous)
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
context.Initialize<bool>(synchronous);

context.ResultType.Should().Be<bool>();
@@ -22,7 +22,7 @@ public void Initialize_Typed_Ok(bool synchronous)
[InlineData(false)]
public void Initialize_From_Ok(bool synchronous)
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var context = ResilienceContextPool.Shared.Get("some-key", cancellationToken);
context.Initialize<bool>(synchronous);
context.ContinueOnCapturedContext = true;
@@ -46,7 +46,7 @@ public void Initialize_From_Ok(bool synchronous)
[Theory]
public void Initialize_Void_Ok(bool synchronous)
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
context.Initialize<VoidResult>(synchronous);

context.ResultType.Should().Be<VoidResult>();
12 changes: 6 additions & 6 deletions test/Polly.Core.Tests/ResiliencePipelineBuilderTests.cs
Original file line number Diff line number Diff line change
@@ -65,7 +65,7 @@ public void AddPipeline_Single_Ok()
var pipeline = builder.Build();

// assert
pipeline.Execute(_ => executions.Add(2));
pipeline.Execute(_ => executions.Add(2), TestContext.Current.CancellationToken);

pipeline.GetPipelineDescriptor().FirstStrategy.StrategyInstance.Should().BeOfType<TestResilienceStrategy>();
executions.Should().BeInAscendingOrder();
@@ -108,7 +108,7 @@ public void AddPipeline_Multiple_Ok()
.Components.Should().HaveCount(3);

// assert
strategy.Execute(_ => executions.Add(4));
strategy.Execute(_ => executions.Add(4), TestContext.Current.CancellationToken);

executions.Should().BeInAscendingOrder();
executions.Should().HaveCount(7);
@@ -194,7 +194,7 @@ public void AddPipeline_MultipleNonDelegating_Ok()
var strategy = builder.Build();

// assert
strategy.Execute(_ => executions.Add(4));
strategy.Execute(_ => executions.Add(4), TestContext.Current.CancellationToken);

executions.Should().BeInAscendingOrder();
executions.Should().HaveCount(7);
@@ -309,7 +309,7 @@ public async Task AddPipeline_Generic_EnsureNotDisposed()
.AddPipelineComponent(_ => internalComponent, new TestResilienceStrategyOptions());
var pipeline = builder.Build();

pipeline.Execute(_ => string.Empty);
pipeline.Execute(_ => string.Empty, TestContext.Current.CancellationToken);

await pipeline.DisposeHelper.DisposeAsync();
await externalComponent.Received(0).DisposeAsync();
@@ -345,7 +345,7 @@ public void AddPipeline_CombinePipelines_Ok()
var strategy = new ResiliencePipelineBuilder().AddPipeline(pipeline1).AddPipeline(pipeline2).Build();

// assert
strategy.Execute(_ => executions.Add(4));
strategy.Execute(_ => executions.Add(4), TestContext.Current.CancellationToken);

executions.Should().BeInAscendingOrder();
executions.Should().HaveCount(7);
@@ -427,7 +427,7 @@ public void ExecuteAsync_EnsureReceivedCallbackExecutesNextStrategy()
var strategy = new ResiliencePipelineBuilder().AddPipeline(first).AddPipeline(second).AddPipeline(third).Build();

// act
strategy.Execute(_ => executions.Add("execute"));
strategy.Execute(_ => executions.Add("execute"), TestContext.Current.CancellationToken);

// assert
executions.SequenceEqual(new[]
6 changes: 3 additions & 3 deletions test/Polly.Core.Tests/ResiliencePipelineTests.Async.cs
Original file line number Diff line number Diff line change
@@ -33,14 +33,14 @@ private static IEnumerable<ExecuteParameters> ExecuteAsync_EnsureCorrectBehavior
AssertContext = AssertResilienceContextAndToken,
};

yield return new ExecuteParameters(r => r.ExecuteAsync(async (_, s) => { s.Should().Be("dummy-state"); }, ResilienceContextPool.Shared.Get(), "dummy-state"))
yield return new ExecuteParameters(r => r.ExecuteAsync(async (_, s) => { s.Should().Be("dummy-state"); }, ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken), "dummy-state"))
{
Caption = "ExecuteAsync_ResilienceContextAndState",
AssertContext = AssertResilienceContext,
AssertContextAfter = AssertContextInitialized,
};

yield return new ExecuteParameters(r => r.ExecuteAsync(context => default, ResilienceContextPool.Shared.Get()))
yield return new ExecuteParameters(r => r.ExecuteAsync(context => default, ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken)))
{
Caption = "ExecuteAsync_ResilienceContext",
AssertContext = AssertResilienceContext,
@@ -87,7 +87,7 @@ public async Task ExecuteAsync_Ok(ExecuteParameters parameters)
[Fact]
public async Task ExecuteAsync_EnsureCallStackPreserved()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

await AssertStackTrace(s => s.ExecuteAsync(_ => MyThrowingMethod()));
await AssertStackTrace(s => s.ExecuteAsync(_ => MyThrowingMethod(), context));
8 changes: 4 additions & 4 deletions test/Polly.Core.Tests/ResiliencePipelineTests.AsyncT.cs
Original file line number Diff line number Diff line change
@@ -34,14 +34,14 @@ private static IEnumerable<ExecuteParameters> ExecuteAsyncT_EnsureCorrectBehavio
AssertContext = AssertResilienceContextAndToken,
};

yield return new ExecuteParameters<long>(r => r.ExecuteAsync(async (_, s) => { s.Should().Be("dummy-state"); return result; }, ResilienceContextPool.Shared.Get(), "dummy-state"), result)
yield return new ExecuteParameters<long>(r => r.ExecuteAsync(async (_, s) => { s.Should().Be("dummy-state"); return result; }, ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken), "dummy-state"), result)
{
Caption = "ExecuteAsyncT_ResilienceContextAndState",
AssertContext = AssertResilienceContext,
AssertContextAfter = AssertContextInitialized,
};

yield return new ExecuteParameters<long>(r => r.ExecuteAsync(async _ => result, ResilienceContextPool.Shared.Get()), result)
yield return new ExecuteParameters<long>(r => r.ExecuteAsync(async _ => result, ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken)), result)
{
Caption = "ExecuteAsyncT_ResilienceContext",
AssertContext = AssertResilienceContext,
@@ -91,7 +91,7 @@ public async Task ExecuteAsyncT_Ok(ExecuteParameters parameters)
[Fact]
public async Task ExecuteAsync_T_EnsureCallStackPreserved()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

await AssertStackTrace(s => s.ExecuteAsync(_ => MyThrowingMethod()));
await AssertStackTrace(s => s.ExecuteAsync(_ => MyThrowingMethod(), context));
@@ -126,7 +126,7 @@ public async Task ExecuteOutcomeAsync_Ok()
context.ResultType.Should().Be<int>();
return Outcome.FromResultAsValueTask(12345);
},
ResilienceContextPool.Shared.Get(),
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken),
"state");

result.Result.Should().Be(12345);
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/ResiliencePipelineTests.cs
Original file line number Diff line number Diff line change
@@ -11,7 +11,7 @@ public partial class ResiliencePipelineTests
#pragma warning disable IDE0028
public static TheoryData<ResilienceContextPool?> ResilienceContextPools = new()
{
null,
null as ResilienceContextPool,
ResilienceContextPool.Shared,
};
#pragma warning restore IDE0028
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Retry/OnRetryArgumentsTests.cs
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnRetryArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new OnRetryArguments<int>(context, Outcome.FromResult(1), 2, TimeSpan.FromSeconds(3), TimeSpan.MaxValue);
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class RetryDelayGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new RetryDelayGeneratorArguments<int>(context, Outcome.FromResult(1), 2);
8 changes: 4 additions & 4 deletions test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs
Original file line number Diff line number Diff line change
@@ -82,7 +82,7 @@ public void ExecuteAsync_MultipleRetries_EnsureDiscardedResultsDisposed()
var r = new DisposableResult();
results.Add(r);
return r;
});
}, TestContext.Current.CancellationToken);

// assert
result.IsDisposed.Should().BeFalse();
@@ -152,7 +152,7 @@ public void RetryDelayGenerator_Respected()
return new ValueTask<TimeSpan?>(delay);
};

CreateSut(TimeProvider.System).Execute(_ => "dummy");
CreateSut(TimeProvider.System).Execute(_ => "dummy", TestContext.Current.CancellationToken);

retries.Should().Be(3);
generatedValues.Should().Be(3);
@@ -183,7 +183,7 @@ public async Task RetryDelayGenerator_ZeroDelay_NoTimeProviderCalls()
};

var sut = CreateSut(provider);
await sut.ExecuteAsync(_ => new ValueTask<string>("dummy"));
await sut.ExecuteAsync(_ => new ValueTask<string>("dummy"), TestContext.Current.CancellationToken);

retries.Should().Be(3);
generatedValues.Should().Be(3);
@@ -286,7 +286,7 @@ await sut.ExecuteAsync(_ =>
{
_timeProvider.Advance(TimeSpan.FromMinutes(1));
return new ValueTask<int>(0);
}).AsTask();
}, TestContext.Current.CancellationToken).AsTask();
}

[Fact]
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs
Original file line number Diff line number Diff line change
@@ -28,7 +28,7 @@ public void Ctor_Ok()
public async Task ShouldHandle_EnsureDefaults()
{
var options = new RetryStrategyOptions<int>();
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

(await options.ShouldHandle(new RetryPredicateArguments<int>(context, Outcome.FromResult(0), 0))).Should().Be(false);
(await options.ShouldHandle(new RetryPredicateArguments<int>(context, Outcome.FromException<int>(new OperationCanceledException()), 0))).Should().Be(false);
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Retry/ShouldRetryArgumentsTests.cs
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class ShouldRetryArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new RetryPredicateArguments<int>(context, Outcome.FromResult(1), 2);
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class BehaviorGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new BehaviorGeneratorArguments(context);
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ public class ChaosBehaviorPipelineBuilderExtensionsTests
{
public static IEnumerable<object[]> AddBehavior_Ok_Data()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
Func<CancellationToken, ValueTask> behavior = _ => default;
yield return new object[]
{
Original file line number Diff line number Diff line change
@@ -44,7 +44,7 @@ public async Task Given_enabled_and_randomly_within_threshold_should_inject_beha
_options.BehaviorGenerator = (_) => { _behaviorGeneratorExecuted = true; return default; };

var sut = CreateSut();
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; });
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; }, TestContext.Current.CancellationToken);

_userDelegateExecuted.Should().BeTrue();
_behaviorGeneratorExecuted.Should().BeTrue();
@@ -66,7 +66,7 @@ public async Task Given_enabled_and_randomly_within_threshold_ensure_on_behavior
};

var sut = CreateSut();
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; });
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; }, TestContext.Current.CancellationToken);

_onBehaviorInjectedExecuted.Should().BeTrue();
_userDelegateExecuted.Should().BeTrue();
@@ -84,7 +84,7 @@ public async Task Given_enabled_and_randomly_not_within_threshold_should_not_inj
_options.BehaviorGenerator = (_) => { _behaviorGeneratorExecuted = true; return default; };

var sut = CreateSut();
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; });
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; }, TestContext.Current.CancellationToken);

_userDelegateExecuted.Should().BeTrue();
_behaviorGeneratorExecuted.Should().BeFalse();
@@ -104,7 +104,7 @@ public async Task Should_inject_behavior_before_executing_user_delegate()
};

var sut = CreateSut();
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; });
await sut.ExecuteAsync((_) => { _userDelegateExecuted = true; return default; }, TestContext.Current.CancellationToken);

_userDelegateExecuted.Should().BeTrue();
_behaviorGeneratorExecuted.Should().BeTrue();
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnBehaviorInjectedArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new OnBehaviorInjectedArguments(context);
6 changes: 3 additions & 3 deletions test/Polly.Core.Tests/Simmy/ChaosStrategyTTests.cs
Original file line number Diff line number Diff line change
@@ -34,7 +34,7 @@ public void InvalidCtor()
[Fact]
public async Task Ctor_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
_options.EnabledGenerator = (_) => new ValueTask<bool>(true);
_options.InjectionRate = 0.5;

@@ -66,7 +66,7 @@ public async Task Should_coerce_injection_rate_generator_result_is_not_valid(dou
var sut = CreateSut();
sut.OnExecute = (_, _) => { _wasChaosUnleashed = true; return Task.CompletedTask; };

await sut.AsPipeline().ExecuteAsync<int>((_) => { return default; });
await sut.AsPipeline().ExecuteAsync<int>((_) => { return default; }, TestContext.Current.CancellationToken);

_wasChaosUnleashed.Should().Be(shouldBeInjected);
_enableGeneratorExecuted.Should().BeFalse();
@@ -167,7 +167,7 @@ public async Task Should_inject_chaos()
var sut = CreateSut();
sut.OnExecute = (_, _) => { _wasChaosUnleashed = true; return Task.CompletedTask; };

await sut.AsPipeline().ExecuteAsync<int>((_) => { return default; });
await sut.AsPipeline().ExecuteAsync<int>((_) => { return default; }, TestContext.Current.CancellationToken);

_wasChaosUnleashed.Should().BeTrue();
_enableGeneratorExecuted.Should().BeFalse();
6 changes: 3 additions & 3 deletions test/Polly.Core.Tests/Simmy/ChaosStrategyTests.cs
Original file line number Diff line number Diff line change
@@ -35,7 +35,7 @@ public void InvalidCtor()
[Fact]
public async Task Ctor_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
_options.EnabledGenerator = (_) => new ValueTask<bool>(true);
_options.InjectionRate = 0.5;

@@ -67,7 +67,7 @@ public async Task Should_coerce_injection_rate_generator_result_is_not_valid(dou
var sut = CreateSut();
sut.OnExecute = (_, _) => { _wasChaosUnleashed = true; return Task.CompletedTask; };

await sut.AsPipeline().ExecuteAsync((_) => { return default; });
await sut.AsPipeline().ExecuteAsync((_) => { return default; }, TestContext.Current.CancellationToken);

_wasChaosUnleashed.Should().Be(shouldBeInjected);
_enableGeneratorExecuted.Should().BeFalse();
@@ -168,7 +168,7 @@ public async Task Should_inject_chaos()
var sut = CreateSut();
sut.OnExecute = (_, _) => { _wasChaosUnleashed = true; return Task.CompletedTask; };

await sut.AsPipeline().ExecuteAsync((_) => { return default; });
await sut.AsPipeline().ExecuteAsync((_) => { return default; }, TestContext.Current.CancellationToken);

_wasChaosUnleashed.Should().BeTrue();
_enableGeneratorExecuted.Should().BeFalse();
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class EnabledGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new EnabledGeneratorArguments(context);
Original file line number Diff line number Diff line change
@@ -27,7 +27,7 @@ public class ChaosFaultPipelineBuilderExtensionsTests
private static void AssertFaultStrategy<T, TException>(ResiliencePipelineBuilder<T> builder, bool enabled, double injectionRate)
where TException : Exception
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var strategy = builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.Should().BeOfType<ChaosFaultStrategy>().Subject;

strategy.EnabledGenerator.Invoke(new(context)).Preserve().GetAwaiter().GetResult().Should().Be(enabled);
@@ -38,7 +38,7 @@ private static void AssertFaultStrategy<T, TException>(ResiliencePipelineBuilder
private static ChaosFaultStrategy AssertFaultStrategy<TException>(ResiliencePipelineBuilder builder, bool enabled, double injectionRate)
where TException : Exception
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var strategy = builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.Should().BeOfType<ChaosFaultStrategy>().Subject;

strategy.EnabledGenerator.Invoke(new(context)).Preserve().GetAwaiter().GetResult().Should().Be(enabled);
6 changes: 3 additions & 3 deletions test/Polly.Core.Tests/Simmy/Fault/ChaosFaultStrategyTests.cs
Original file line number Diff line number Diff line change
@@ -91,7 +91,7 @@ public async Task Given_not_enabled_should_not_inject_fault_and_return_outcome()
{
_userDelegateExecuted = true;
return await Task.FromResult(HttpStatusCode.OK);
});
}, TestContext.Current.CancellationToken);

response.Should().Be(HttpStatusCode.OK);
_userDelegateExecuted.Should().BeTrue();
@@ -186,7 +186,7 @@ public void Given_enabled_and_randomly_not_within_threshold_should_not_inject_fa
{
_userDelegateExecuted = true;
return 200;
});
}, TestContext.Current.CancellationToken);

result.Should().Be(200);
_userDelegateExecuted.Should().BeTrue();
@@ -207,7 +207,7 @@ public void Given_enabled_and_randomly_within_threshold_should_not_inject_fault_
sut.Execute(_ =>
{
_userDelegateExecuted = true;
});
}, TestContext.Current.CancellationToken);

_userDelegateExecuted.Should().BeTrue();
_onFaultInjectedExecuted.Should().BeFalse();
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class FaultGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new FaultGeneratorArguments(context);
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Simmy/Fault/FaultGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -45,6 +45,6 @@ public void AddException_FactoryWithResilienceContext_Ok()

return func(
new FaultGeneratorArguments(
ResilienceContextPool.Shared.Get())).AsTask().Result;
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken))).AsTask().Result;
}
}
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnFaultInjectedArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var fault = new InvalidCastException();

// Act
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class InjectionRateGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new InjectionRateGeneratorArguments(context);
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public class ChaosLatencyPipelineBuilderExtensionsTests
{
public static IEnumerable<object[]> AddLatency_Ok_Data()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
Func<ValueTask> behavior = () => new ValueTask(Task.CompletedTask);
yield return new object[]
{
Original file line number Diff line number Diff line change
@@ -42,7 +42,7 @@ public async Task Given_enabled_and_randomly_within_threshold_should_inject_late

var before = _timeProvider.GetUtcNow();
var sut = CreateSut();
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; });
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; }, TestContext.Current.CancellationToken);
_timeProvider.Advance(_delay);
await task;

@@ -65,7 +65,7 @@ public async Task Given_not_enabled_should_not_inject_latency()

var before = _timeProvider.GetUtcNow();
var sut = CreateSut();
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; });
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; }, TestContext.Current.CancellationToken);
_timeProvider.Advance(_delay);
await task;

@@ -85,7 +85,7 @@ public async Task Given_enabled_and_randomly_not_within_threshold_should_not_inj

var before = _timeProvider.GetUtcNow();
var sut = CreateSut();
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; });
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; }, TestContext.Current.CancellationToken);
_timeProvider.Advance(_delay);
await task;

@@ -114,7 +114,7 @@ public async Task Given_latency_is_negative_should_not_inject_latency(double lat

var before = _timeProvider.GetUtcNow();
var sut = CreateSut();
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; });
var task = sut.ExecuteAsync(async _ => { _userDelegateExecuted = true; await Task.CompletedTask; }, TestContext.Current.CancellationToken);
_timeProvider.Advance(_delay);
await task;

Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class LatencyGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new LatencyGeneratorArguments(context);
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnLatencyInjectedArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new OnLatencyInjectedArguments(context, TimeSpan.FromSeconds(10));
Original file line number Diff line number Diff line change
@@ -27,7 +27,7 @@ public class ChaosOutcomePipelineBuilderExtensionsTests

private static void AssertResultStrategy<T>(ResiliencePipelineBuilder<T> builder, ChaosOutcomeStrategyOptions<T> options, bool enabled, double injectionRate, Outcome<T> outcome)
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var strategy = builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.Should().BeOfType<ChaosOutcomeStrategy<T>>().Subject;

strategy.EnabledGenerator.Invoke(new(context)).Preserve().GetAwaiter().GetResult().Should().Be(enabled);
Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ public ChaosOutcomeStrategyTests()
],
];

private static CancellationToken CancellationToken => CancellationToken.None;
private static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

[Theory]
#pragma warning disable xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OnOutcomeInjectedArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new OnOutcomeInjectedArguments<int>(context, new(200));
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public static class OutcomeGeneratorArgumentsTests
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// Act
var args = new OutcomeGeneratorArguments(context);
Original file line number Diff line number Diff line change
@@ -73,6 +73,6 @@ public void AddResult_FactoryWithResilienceContext_Ok()

return func(
new OutcomeGeneratorArguments(
ResilienceContextPool.Shared.Get())).AsTask().Result;
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken))).AsTask().Result;
}
}
6 changes: 3 additions & 3 deletions test/Polly.Core.Tests/Simmy/Utils/GeneratorHelperTests.cs
Original file line number Diff line number Diff line change
@@ -9,15 +9,15 @@ public void CreateGenerator_NoGenerators_Ok()
{
var helper = new GeneratorHelper<int>(_ => 10);

helper.CreateGenerator()(ResilienceContextPool.Shared.Get()).Should().BeNull();
helper.CreateGenerator()(ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken)).Should().BeNull();
}

[Fact]
public void AddOutcome_EnsureWeightRespected()
{
int weight = 0;
int maxWeight = 0;
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

var helper = new GeneratorHelper<int>(max =>
{
@@ -44,7 +44,7 @@ public void AddOutcome_EnsureWeightRespected()
[Fact]
public void Generator_OutsideRange_ReturnsNull()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var helper = new GeneratorHelper<int>(_ => 1000);

helper.AddOutcome(_ => Outcome.FromResult(1), 40);
Original file line number Diff line number Diff line change
@@ -29,7 +29,7 @@ public void Enabled_Ok()
[Fact]
public void Report_NoOutcome_OK()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

_sut.Report(new(ResilienceEventSeverity.Warning, "dummy-event"), context, new TestArguments());

@@ -49,7 +49,7 @@ public void ResiliencePipelineTelemetry_NoDiagnosticSource_Ok()
{
var source = new ResilienceTelemetrySource("builder", "instance", "strategy_name");
var sut = new ResilienceStrategyTelemetry(source, null);
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

sut.Invoking(s => s.Report(new(ResilienceEventSeverity.Warning, "dummy"), context, new TestArguments())).Should().NotThrow();
sut.Invoking(s => s.Report(new(ResilienceEventSeverity.Warning, "dummy"), context, Outcome.FromResult(1), new TestArguments())).Should().NotThrow();
@@ -58,7 +58,7 @@ public void ResiliencePipelineTelemetry_NoDiagnosticSource_Ok()
[Fact]
public void Report_Outcome_OK()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
_sut.Report(new(ResilienceEventSeverity.Warning, "dummy-event"), context, Outcome.FromResult(99), new TestArguments());

_args.Should().HaveCount(1);
@@ -75,7 +75,7 @@ public void Report_Outcome_OK()
[Fact]
public void Report_SeverityNone_Skipped()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
_sut.Report(new(ResilienceEventSeverity.None, "dummy-event"), context, Outcome.FromResult(99), new TestArguments());
_sut.Report(new(ResilienceEventSeverity.None, "dummy-event"), context, new TestArguments());

@@ -87,7 +87,7 @@ public void Report_NoListener_ShouldNotThrow()
{
var sut = new ResilienceStrategyTelemetry(_source, null);

var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

sut.Invoking(s => s.Report(new(ResilienceEventSeverity.None, "dummy-event"), context, Outcome.FromResult(99), new TestArguments()))
.Should()
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ public class TelemetryEventArgumentsTests
[Fact]
public void Ctor_Ok()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var args = new TelemetryEventArguments<string, string>(_source, new ResilienceEvent(ResilienceEventSeverity.Warning, "ev"), context, "arg", Outcome.FromResult("dummy"));

args.Outcome!.Value.Result.Should().Be("dummy");
4 changes: 2 additions & 2 deletions test/Polly.Core.Tests/Telemetry/TelemetryUtilTests.cs
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@ public static class TelemetryUtilTests
public static void ReportExecutionAttempt_Ok(bool handled, ResilienceEventSeverity severity)
{
var asserted = false;
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var listener = TestUtilities.CreateResilienceTelemetry(args =>
{
args.Event.Severity.Should().Be(severity);
@@ -27,7 +27,7 @@ public static void ReportExecutionAttempt_Ok(bool handled, ResilienceEventSeveri
public static void ReportFinalExecutionAttempt_Ok(bool handled, ResilienceEventSeverity severity)
{
var asserted = false;
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var listener = TestUtilities.CreateResilienceTelemetry(args =>
{
args.Event.Severity.Should().Be(severity);
Original file line number Diff line number Diff line change
@@ -64,6 +64,6 @@ private static TimeSpan GetTimeout(TimeoutResilienceStrategy strategy)

return strategy.TimeoutGenerator(
new TimeoutGeneratorArguments(
ResilienceContextPool.Shared.Get())).Preserve().GetAwaiter().GetResult();
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken))).Preserve().GetAwaiter().GetResult();
}
}
Original file line number Diff line number Diff line change
@@ -46,7 +46,7 @@ public void Execute_EnsureTimeoutGeneratorCalled()

var sut = CreateSut();

sut.Execute(_ => { });
sut.Execute(_ => { }, TestContext.Current.CancellationToken);

called.Should().BeTrue();
}
@@ -89,7 +89,7 @@ public void Execute_NoTimeout(Func<TimeSpan> timeout)
var called = false;
SetTimeout(timeout());
var sut = CreateSut();
sut.Execute(_ => { });
sut.Execute(_ => { }, TestContext.Current.CancellationToken);

called.Should().BeFalse();
}
4 changes: 2 additions & 2 deletions test/Polly.Core.Tests/Timeout/TimeoutTestUtils.cs
Original file line number Diff line number Diff line change
@@ -5,10 +5,10 @@ namespace Polly.Core.Tests.Timeout;
public static class TimeoutTestUtils
{
public static OnTimeoutArguments OnTimeoutArguments()
=> new(ResilienceContextPool.Shared.Get(), TimeSpan.FromSeconds(1));
=> new(ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken), TimeSpan.FromSeconds(1));

public static TimeoutGeneratorArguments TimeoutGeneratorArguments()
=> new(ResilienceContextPool.Shared.Get());
=> new(ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken));

#pragma warning disable IDE0028
public static readonly TheoryData<TimeSpan> InvalidTimeouts = new()
Original file line number Diff line number Diff line change
@@ -81,7 +81,7 @@ public async Task Rent_Cancellable_EnsureCancelled(object timeProvider)
fakeTimeProvider.Advance(TimeSpan.FromSeconds(1));
}

await Task.Delay(100);
await Task.Delay(100, TestContext.Current.CancellationToken);

await TestUtilities.AssertWithTimeoutAsync(() => cts.IsCancellationRequested.Should().BeTrue());
}
@@ -95,7 +95,7 @@ public async Task Rent_NotCancellable_EnsureNotCancelled(object timeProvider)
var pool = CancellationTokenSourcePool.Create(GetTimeProvider(timeProvider));
var cts = pool.Get(System.Threading.Timeout.InfiniteTimeSpan);

await Task.Delay(20);
await Task.Delay(20, TestContext.Current.CancellationToken);

cts.IsCancellationRequested.Should().BeFalse();
}
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ public void Ctor_Ok() =>
[Fact]
public void Execute_NonGeneric_Ok()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var values = new List<object?>();

var pipeline = new ResiliencePipeline(PipelineComponentFactory.FromStrategy(new Strategy<object>(outcome =>
@@ -42,7 +42,7 @@ public void Execute_Generic_Ok()
values.Add(outcome.Result);
})), DisposeBehavior.Allow, null);

pipeline.Execute(args => "dummy");
pipeline.Execute(args => "dummy", TestContext.Current.CancellationToken);

values.Should().HaveCount(1);
values[0].Should().Be("dummy");
Original file line number Diff line number Diff line change
@@ -40,7 +40,7 @@ public void Create_EnsureOriginalStrategiesPreserved()
[Fact]
public async Task Create_EnsureExceptionsNotWrapped()
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var components = new[]
{
PipelineComponentFactory.FromStrategy(new TestResilienceStrategy { Before = (_, _) => throw new NotSupportedException() }),
@@ -86,7 +86,7 @@ public async Task Create_Cancelled_EnsureNoExecution()
};

var pipeline = new ResiliencePipeline(CreateSut(strategies, new FakeTimeProvider()), DisposeBehavior.Allow, null);
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
context.CancellationToken = cancellation.Token;

var result = await pipeline.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("result"), context, "state");
@@ -104,7 +104,7 @@ public async Task Create_CancelledLater_EnsureNoExecution()
PipelineComponentFactory.FromStrategy(new TestResilienceStrategy()),
};
var pipeline = new ResiliencePipeline(CreateSut(strategies, new FakeTimeProvider()), DisposeBehavior.Allow, null);
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
context.CancellationToken = cancellation.Token;

var result = await pipeline.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("result"), context, "state");
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ public static async Task ExecuteComponent_ReturnsCorrectResult()
{
await using var component = new CallbackComponent();
var next = new CallbackComponent();
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var state = 1;

await using var delegating = new DelegatingComponent(component) { Next = next };
@@ -29,7 +29,7 @@ public static async Task ExecuteComponentAot_ReturnsCorrectResult()
{
await using var component = new CallbackComponent();
var next = new CallbackComponent();
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
var state = 1;

await using var delegating = new DelegatingComponent(component) { Next = next };
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@ public async Task DisposeAsync_PendingOperations_Delayed()
};

var component = new ExecutionTrackingComponent(inner, _timeProvider);
var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow, null).Execute(() => { }));
var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow, null).Execute(() => { }), TestContext.Current.CancellationToken);
executing.WaitOne();

var disposeTask = component.DisposeAsync().AsTask();
@@ -56,7 +56,7 @@ public async Task HasPendingExecutions_Ok()
};

await using var component = new ExecutionTrackingComponent(inner, _timeProvider);
var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow, null).Execute(() => { }));
var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow, null).Execute(() => { }), TestContext.Current.CancellationToken);
executing.WaitOne();

component.HasPendingExecutions.Should().BeTrue();
@@ -82,7 +82,7 @@ public async Task DisposeAsync_Timeout_Ok()
};

var component = new ExecutionTrackingComponent(inner, _timeProvider);
var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow, null).Execute(() => { }));
var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow, null).Execute(() => { }), TestContext.Current.CancellationToken);
executing.WaitOne();

var disposeTask = component.DisposeAsync().AsTask();
@@ -117,12 +117,12 @@ public async Task DisposeAsync_WhenRunningMultipleTasks_Ok()

for (int i = 0; i < 10; i++)
{
_ = Task.Run(() => pipeline.Execute(() => { }));
_ = Task.Run(() => pipeline.Execute(() => { }), TestContext.Current.CancellationToken);
}

while (tasks.Count != 10)
{
await Task.Delay(1);
await Task.Delay(1, TestContext.Current.CancellationToken);
}

var disposeTask = component.DisposeAsync().AsTask();
@@ -132,7 +132,7 @@ public async Task DisposeAsync_WhenRunningMultipleTasks_Ok()
tasks.TryDequeue(out var ev).Should().BeTrue();
ev!.Set();
ev.Dispose();
disposeTask.Wait(1).Should().BeFalse();
disposeTask.Wait(1, TestContext.Current.CancellationToken).Should().BeFalse();
inner.Disposed.Should().BeFalse();
}

Original file line number Diff line number Diff line change
@@ -8,17 +8,17 @@ public class PipelineComponentFactoryTests
#pragma warning disable IDE0028
public static TheoryData<IEnumerable<Action>> EmptyCallbacks = new()
{
Array.Empty<Action>(),
Array.Empty<Action>() as IEnumerable<Action>,
Enumerable.Empty<Action>(),
new List<Action>(),
new EmptyActionEnumerable(), // Explicitly does not provide TryGetNonEnumeratedCount()
new List<Action>() as IEnumerable<Action>,
new EmptyActionEnumerable() as IEnumerable<Action>, // Explicitly does not provide TryGetNonEnumeratedCount()
};

public static TheoryData<IEnumerable<Action>> NonEmptyCallbacks = new()
{
new[] { () => { } },
new[] { () => { } } as IEnumerable<Action>,
Enumerable.TakeWhile(Enumerable.Repeat(() => { }, 50), (_, i) => i < 1), // Defeat optimisation for TryGetNonEnumeratedCount()
new List<Action> { () => { } },
new List<Action> { () => { } } as IEnumerable<Action>,
};
#pragma warning restore IDE0028

4 changes: 2 additions & 2 deletions test/Polly.Core.Tests/Utils/StrategyHelperTests.cs
Original file line number Diff line number Diff line change
@@ -34,7 +34,7 @@ await TestUtilities.AssertWithTimeoutAsync(async () =>

throw new InvalidOperationException();
},
ResilienceContextPool.Shared.Get(),
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken),
"dummy");

outcome.Exception.Should().BeOfType<InvalidOperationException>();
@@ -56,7 +56,7 @@ await TestUtilities.AssertWithTimeoutAsync(async () =>

return Outcome.FromResult("success");
},
ResilienceContextPool.Shared.Get(),
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken),
"dummy");

outcomeTask.IsCompleted.Should().Be(!isAsync);
2 changes: 1 addition & 1 deletion test/Polly.Core.Tests/Utils/TimeProviderExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ await TestUtilities.AssertWithTimeoutAsync(async () =>
public async Task DelayAsync_SystemSynchronous_Ok()
{
var delay = TimeSpan.FromMilliseconds(5);
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
context.Initialize<VoidResult>(isSynchronous: true);

await TestUtilities.AssertWithTimeoutAsync(async () =>
Original file line number Diff line number Diff line change
@@ -363,7 +363,7 @@ public void AddResiliencePipeline_CustomInstanceName_EnsureReported(bool usingBu
// arrange
using var loggerFactory = new FakeLoggerFactory();

var context = ResilienceContextPool.Shared.Get("my-operation_key");
var context = ResilienceContextPool.Shared.Get("my-operation_key", TestContext.Current.CancellationToken);
var services = new ServiceCollection();
var listener = new FakeTelemetryListener();
var registry = services
Original file line number Diff line number Diff line change
@@ -60,7 +60,7 @@ public async Task DynamicContextPool_1687()

var pipeline = provider.GetPipeline(key);

await pipeline.ExecuteAsync(async ct => await default(ValueTask));
await pipeline.ExecuteAsync(async ct => await default(ValueTask), TestContext.Current.CancellationToken);

strategy.HitCount.Should().BeGreaterThan(0);
}
Original file line number Diff line number Diff line change
@@ -46,7 +46,7 @@ public async Task OnCircuitBreakWithServiceProvider_796()
// now trigger the circuit breaker by evaluating multiple result types
for (int i = 0; i < 10; i++)
{
await pipeline.ExecuteAsync(_ => new ValueTask<string>("error"));
await pipeline.ExecuteAsync(_ => new ValueTask<string>("error"), TestContext.Current.CancellationToken);
}

// now the circuit breaker should be open
Original file line number Diff line number Diff line change
@@ -51,7 +51,7 @@ public async Task PartitionedRateLimiter_EnsureUserLimited_1365()
// assert admin is not limited
using var adminAsserted = new ManualResetEvent(false);
var task = ExecuteBatch("admin", adminAsserted);
task.Wait(100).Should().BeFalse();
task.Wait(100, TestContext.Current.CancellationToken).Should().BeFalse();
adminAsserted.Set();
await task;

@@ -61,7 +61,7 @@ async Task ExecuteBatch(string user, ManualResetEvent waitAsserted)
{
return Task.Run(async () =>
{
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
context.Properties.Set(userKey, user);

await pipeline.ExecuteAsync(async _ =>
1 change: 1 addition & 0 deletions test/Polly.Extensions.Tests/Polly.Extensions.Tests.csproj
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@
<Nullable>enable</Nullable>
<Threshold>100</Threshold>
<NoWarn>$(NoWarn);SA1600;SA1204</NoWarn>
<OutputType>Exe</OutputType>
<Include>[Polly.Extensions]*</Include>
</PropertyGroup>

Original file line number Diff line number Diff line change
@@ -60,7 +60,7 @@ public void AddResiliencePipeline_EnsureReloadable(string? name)

var serviceProvider = services.BuildServiceProvider();
var pipeline = serviceProvider.GetRequiredService<ResiliencePipelineProvider<string>>().GetPipeline("my-pipeline");
var context = ResilienceContextPool.Shared.Get();
var context = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);

// initial
pipeline.Execute(_ => "dummy", context);
Original file line number Diff line number Diff line change
@@ -185,7 +185,7 @@ public void WriteEvent_MeteringWithoutEnrichers_Ok(bool noOutcome, bool exceptio
true when exception => Outcome.FromException<object>(new InvalidOperationException("Dummy message.")),
_ => Outcome.FromResult<object>(true)
};
ReportEvent(telemetry, outcome, context: ResilienceContextPool.Shared.Get("op-key").WithResultType<bool>());
ReportEvent(telemetry, outcome, context: ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithResultType<bool>());

var events = GetEvents("resilience.polly.strategy.events");
events.Should().HaveCount(1);
@@ -233,7 +233,7 @@ public void WriteExecutionAttemptEvent_Metering_Ok(bool noOutcome, bool exceptio
true when exception => Outcome.FromException<object>(new InvalidOperationException("Dummy message.")),
_ => Outcome.FromResult<object>(true)
};
ReportEvent(telemetry, outcome, context: ResilienceContextPool.Shared.Get("op-key").WithResultType<bool>(), arg: attemptArg);
ReportEvent(telemetry, outcome, context: ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithResultType<bool>(), arg: attemptArg);

var events = GetEvents("resilience.polly.strategy.attempt.duration");
events.Should().HaveCount(1);
@@ -276,7 +276,7 @@ public void WriteExecutionAttemptEvent_ShouldBeSkipped()

var telemetry = Create();
var attemptArg = new ExecutionAttemptArguments(5, TimeSpan.FromSeconds(50), true);
ReportEvent(telemetry, Outcome.FromResult<object>(true), context: ResilienceContextPool.Shared.Get("op-key").WithResultType<bool>(), arg: attemptArg);
ReportEvent(telemetry, Outcome.FromResult<object>(true), context: ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithResultType<bool>(), arg: attemptArg);

var events = GetEvents("resilience.polly.strategy.attempt.duration");
events.Should().HaveCount(0);
@@ -352,7 +352,7 @@ public void OnTelemetryEvent_Ok(bool hasCallback)
[Theory]
public void PipelineExecution_Logged(bool exception)
{
var context = ResilienceContextPool.Shared.Get("op-key").WithResultType<int>();
var context = ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithResultType<int>();
var telemetry = Create();
var outcome = exception ? Outcome.FromException<object>(new InvalidOperationException("dummy message")) : Outcome.FromResult((object)10);
var result = exception ? "dummy message" : "10";
@@ -372,7 +372,7 @@ public void PipelineExecution_Logged(bool exception)
[Fact]
public void PipelineExecution_VoidResult_Ok()
{
var context = ResilienceContextPool.Shared.Get("op-key").WithVoidResultType();
var context = ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithVoidResultType();
var telemetry = Create();
ReportEvent(telemetry, outcome: null, arg: default(PipelineExecutingArguments), context: context);

@@ -384,7 +384,7 @@ public void PipelineExecution_VoidResult_Ok()
[Fact]
public void PipelineExecution_NoOutcome_Logged()
{
var context = ResilienceContextPool.Shared.Get("op-key").WithResultType<int>();
var context = ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithResultType<int>();
var telemetry = Create();

ReportEvent(telemetry, outcome: null, arg: new PipelineExecutedArguments(TimeSpan.FromSeconds(10)), context: context);
@@ -400,7 +400,7 @@ public void PipelineExecution_Metered(bool exception)
{
using var metering = TestUtilities.EnablePollyMetering(_events);

var context = ResilienceContextPool.Shared.Get("op-key").WithResultType<int>();
var context = ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithResultType<int>();
var outcome = exception ? Outcome.FromException<object>(new InvalidOperationException("dummy message")) : Outcome.FromResult((object)10);
var result = exception ? "dummy message" : "10";

@@ -447,7 +447,7 @@ public void PipelineExecuted_ShouldBeSkipped()

var telemetry = Create();
var attemptArg = new PipelineExecutedArguments(TimeSpan.FromSeconds(50));
ReportEvent(telemetry, Outcome.FromResult<object>(true), context: ResilienceContextPool.Shared.Get("op-key").WithResultType<bool>(), arg: attemptArg);
ReportEvent(telemetry, Outcome.FromResult<object>(true), context: ResilienceContextPool.Shared.Get("op-key", TestContext.Current.CancellationToken).WithResultType<bool>(), arg: attemptArg);

var events = GetEvents("resilience.polly.pipeline.duration");
events.Should().HaveCount(0);
Original file line number Diff line number Diff line change
@@ -16,7 +16,7 @@ public void Ctor_EnsureDefaults()

options.MeteringEnrichers.Should().BeEmpty();
options.LoggerFactory.Should().Be(NullLoggerFactory.Instance);
var resilienceContext = ResilienceContextPool.Shared.Get();
var resilienceContext = ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken);
options.ResultFormatter(resilienceContext, null).Should().BeNull();
options.ResultFormatter(resilienceContext, "dummy").Should().Be("dummy");

Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@ public void ConfigureTelemetry_EnsureLogging()
using var factory = TestUtilities.CreateLoggerFactory(out var fakeLogger);

_builder.ConfigureTelemetry(factory);
_builder.AddStrategy(new TestResilienceStrategy()).Build().Execute(_ => { });
_builder.AddStrategy(new TestResilienceStrategy()).Build().Execute(_ => { }, TestContext.Current.CancellationToken);

fakeLogger.GetRecords().Should().NotBeEmpty();
fakeLogger.GetRecords().Should().HaveCount(2);
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ public static class OnRateLimiterRejectedArgumentsTests
public static void Ctor_Ok()
{
var args = new OnRateLimiterRejectedArguments(
ResilienceContextPool.Shared.Get(CancellationToken.None),
ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken),
Substitute.For<RateLimitLease>());

args.Context.Should().NotBeNull();
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@
<Nullable>enable</Nullable>
<Threshold>100</Threshold>
<NoWarn>$(NoWarn);SA1600;SA1204</NoWarn>
<OutputType>Exe</OutputType>
<Include>[Polly.RateLimiting]*</Include>
</PropertyGroup>
<ItemGroup>
Original file line number Diff line number Diff line change
@@ -169,7 +169,7 @@ private static void AssertRateLimiterStrategy(ResiliencePipelineBuilder builder,
{
limiterStrategy.OnLeaseRejected.Should().NotBeNull();
limiterStrategy
.OnLeaseRejected!(new OnRateLimiterRejectedArguments(ResilienceContextPool.Shared.Get(), Substitute.For<RateLimitLease>()))
.OnLeaseRejected!(new OnRateLimiterRejectedArguments(ResilienceContextPool.Shared.Get(TestContext.Current.CancellationToken), Substitute.For<RateLimitLease>()))
.Preserve().GetAwaiter().GetResult();
}
else
Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ public async Task Execute_HappyPath()

strategy.Execute(_ => { }, cts.Token);

await _limiter.ReceivedWithAnyArgs().AcquireAsync(default, default);
await _limiter.ReceivedWithAnyArgs().AcquireAsync(default, TestContext.Current.CancellationToken);
_lease.Received().Dispose();
}

@@ -80,7 +80,7 @@ public async Task Execute_LeaseRejected(bool hasEvents, bool hasRetryAfter)

eventCalled.Should().Be(hasEvents);

await _limiter.ReceivedWithAnyArgs().AcquireAsync(default, default);
await _limiter.ReceivedWithAnyArgs().AcquireAsync(default, TestContext.Current.CancellationToken);
_lease.Received().Dispose();

_listener.GetArgs<OnRateLimiterRejectedArguments>().Should().HaveCount(1);
2 changes: 1 addition & 1 deletion test/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs
Original file line number Diff line number Diff line change
@@ -16,7 +16,7 @@ public abstract class BulkheadSpecsBase : IDisposable

#endregion

protected static CancellationToken CancellationToken => CancellationToken.None;
protected static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

protected BulkheadSpecsBase(ITestOutputHelper testOutputHelper)
{
4 changes: 2 additions & 2 deletions test/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs
Original file line number Diff line number Diff line change
@@ -101,7 +101,7 @@ public void Should_call_onBulkheadRejected_with_passed_context()
tcs.Task.Wait();
return 0;
});
}, CancellationToken.None);
}, TestContext.Current.CancellationToken);

Within(CohesionTimeLimit, () => Expect(0, () => bulkhead.BulkheadAvailableCount, nameof(bulkhead.BulkheadAvailableCount)));

@@ -110,7 +110,7 @@ public void Should_call_onBulkheadRejected_with_passed_context()
cancellationSource.Cancel();

#if NET
tcs.SetCanceled(CancellationToken.None);
tcs.SetCanceled(TestContext.Current.CancellationToken);
#else
tcs.SetCanceled();
#endif
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ public class AsyncSerializingCacheProviderSpecs
{
#region Object-to-TSerialized serializer

private static CancellationToken CancellationToken => CancellationToken.None;
private static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

[Fact]
public void Single_generic_constructor_should_throw_on_no_wrapped_cache_provider()
2 changes: 1 addition & 1 deletion test/Polly.Specs/Caching/CacheAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ public class CacheAsyncSpecs : IDisposable
{
#region Configuration

private static CancellationToken CancellationToken => CancellationToken.None;
private static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

[Fact]
public void Should_throw_when_action_is_null()
2 changes: 1 addition & 1 deletion test/Polly.Specs/Caching/CacheSpecs.cs
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ public class CacheSpecs : IDisposable
[Fact]
public void Should_throw_when_action_is_null()
{
var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
Func<Context, CancellationToken, EmptyStruct> action = null!;
Action<Context, CancellationToken> actionVoid = null!;
4 changes: 2 additions & 2 deletions test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ public class CacheTResultAsyncSpecs : IDisposable
{
#region Configuration

private static CancellationToken CancellationToken => CancellationToken.None;
private static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

[Fact]
public void Should_throw_when_action_is_null()
@@ -163,7 +163,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac

IAsyncCacheProvider stubCacheProvider = new StubCacheProvider();
var cache = Policy.CacheAsync<string>(stubCacheProvider, TimeSpan.MaxValue);
await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false);
await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken, false);

bool delegateExecuted = false;

2 changes: 1 addition & 1 deletion test/Polly.Specs/Caching/CacheTResultSpecs.cs
Original file line number Diff line number Diff line change
@@ -36,7 +36,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "EmptyStruct" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
4 changes: 2 additions & 2 deletions test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache
IAsyncCacheProvider stubCacheProvider = new StubCacheProvider();
var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError);

(bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false);
(bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, TestContext.Current.CancellationToken, false);
cacheHit.Should().BeFalse();
fromCache.Should().BeNull();

@@ -33,7 +33,7 @@ public async Task Should_execute_delegate_and_put_value_in_cache_for_non_nullabl
const ResultPrimitive ValueToReturn = ResultPrimitive.Substitute;
const string OperationKey = "SomeOperationKey";

var cancellationToken = CancellationToken.None;
var cancellationToken = TestContext.Current.CancellationToken;
IAsyncCacheProvider stubCacheProvider = new StubCacheProvider();
var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue);

Original file line number Diff line number Diff line change
@@ -2041,7 +2041,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync<DivideByZeroException>())

// Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes.
#if NET
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue();
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, TestContext.Current.CancellationToken).Should().BeTrue();
#else
longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue();
#endif
Original file line number Diff line number Diff line change
@@ -2043,7 +2043,7 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub
// Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes.
#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
#if NET
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue();
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, TestContext.Current.CancellationToken).Should().BeTrue();
#else
longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue();
#endif
Original file line number Diff line number Diff line change
@@ -833,7 +833,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync<DivideByZeroException>())

// Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes.
#if NET
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue();
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, TestContext.Current.CancellationToken).Should().BeTrue();
#else
longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue();
#endif
2 changes: 1 addition & 1 deletion test/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs
Original file line number Diff line number Diff line change
@@ -824,7 +824,7 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub

// Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes.
#if NET
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue();
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, TestContext.Current.CancellationToken).Should().BeTrue();
#else
longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue();
#endif
Original file line number Diff line number Diff line change
@@ -36,7 +36,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken, false]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
@@ -950,7 +950,7 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f
#pragma warning disable xUnit1031
// Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes.
#if NET
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue();
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, TestContext.Current.CancellationToken).Should().BeTrue();
#else
longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue();
#endif
4 changes: 2 additions & 2 deletions test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs
Original file line number Diff line number Diff line change
@@ -36,7 +36,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "EmptyStruct" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
@@ -933,7 +933,7 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub

// Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes.
#if NET
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue();
longRunningExecution.Wait(testTimeoutToExposeDeadlocks, TestContext.Current.CancellationToken).Should().BeTrue();
#else
longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue();
#endif
2 changes: 1 addition & 1 deletion test/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken, false]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/Fallback/FallbackTResultSpecs.cs
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "EmptyStruct" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 2 additions & 0 deletions test/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs
Original file line number Diff line number Diff line change
@@ -29,6 +29,8 @@ public Item(string format, object[] args)

private readonly ITestOutputHelper _innerOutputHelper;

public string Output => _innerOutputHelper.Output;

public AnnotatedOutputHelper(ITestOutputHelper innerOutputHelper) =>
_innerOutputHelper = innerOutputHelper ?? throw new ArgumentNullException(nameof(innerOutputHelper));

12 changes: 12 additions & 0 deletions test/Polly.Specs/Helpers/Bulkhead/SilentOutputHelper.cs
Original file line number Diff line number Diff line change
@@ -2,6 +2,18 @@

public class SilentOutputHelper : ITestOutputHelper
{
public string Output => string.Empty;

public void Write(string message)
{
// Do nothing: intentionally silent.
}

public void Write(string format, params object[] args)
{
// Do nothing: intentionally silent.
}

public void WriteLine(string message)
{
// Do nothing: intentionally silent.
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ public static class ContextualPolicyTResultExtensionsAsync
public static Task<TResult> RaiseResultSequenceAsync<TResult>(this AsyncPolicy<TResult> policy,
IDictionary<string, object> contextData,
params TResult[] resultsToRaise) =>
policy.RaiseResultSequenceAsync(contextData, CancellationToken.None, resultsToRaise.ToList());
policy.RaiseResultSequenceAsync(contextData, TestContext.Current.CancellationToken, resultsToRaise.ToList());

public static Task<TResult> RaiseResultSequenceAsync<TResult>(this AsyncPolicy<TResult> policy, IDictionary<string, object> contextData, CancellationToken cancellationToken, IEnumerable<TResult> resultsToRaise)
{
2 changes: 1 addition & 1 deletion test/Polly.Specs/Helpers/PolicyTResultExtensionsAsync.cs
Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ public static Task<TResult> RaiseResultAndOrExceptionSequenceAsync<TResult>(this

public static Task<TResult> RaiseResultAndOrExceptionSequenceAsync<TResult>(this AsyncPolicy<TResult> policy,
IEnumerable<object> resultsOrExceptionsToRaise) =>
policy.RaiseResultAndOrExceptionSequenceAsync(CancellationToken.None, resultsOrExceptionsToRaise);
policy.RaiseResultAndOrExceptionSequenceAsync(TestContext.Current.CancellationToken, resultsOrExceptionsToRaise);

public static async Task<TResult> RaiseResultAndOrExceptionSequenceAsync<TResult>(this AsyncPolicy<TResult> policy,
CancellationToken cancellationToken, IEnumerable<object> resultsOrExceptionsToRaise)
2 changes: 1 addition & 1 deletion test/Polly.Specs/NoOp/NoOpAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ public void Should_throw_when_action_is_null()
var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" });
var generic = methodInfo.MakeGenericMethod(typeof(EmptyStruct));

var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None, false]);
var func = () => generic.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken, false]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/NoOp/NoOpSpecs.cs
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ public void Should_throw_when_action_is_null()

var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "TResult" });
var generic = methodInfo.MakeGenericMethod(typeof(EmptyStruct));
var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => generic.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken, false]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/NoOp/NoOpTResultSpecs.cs
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ public void Should_throw_when_action_is_null()
var instanceType = instance.GetType();
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "EmptyStruct" });
var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/Polly.Specs.csproj
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('Windows'))">$(TargetFrameworks);net481</TargetFrameworks>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
<ProjectType>Test</ProjectType>
<Threshold>75,60,70</Threshold>
<Include>[Polly]*</Include>
@@ -26,7 +27,6 @@
<Using Include="Polly.Specs.Helpers.Custom.PreExecute" />
<Using Include="Polly.Specs.Helpers.RateLimit" />
<Using Include="Xunit" />
<Using Include="Xunit.Abstractions" />
<Using Include="Xunit.Sdk" />
</ItemGroup>

2 changes: 1 addition & 1 deletion test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@

public abstract class RateLimitPolicySpecsBase : RateLimitSpecsBase
{
protected static CancellationToken CancellationToken => CancellationToken.None;
protected static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

protected abstract IRateLimitPolicy GetPolicyViaSyntax(
int numberOfExecutions,
2 changes: 1 addition & 1 deletion test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs
Original file line number Diff line number Diff line change
@@ -66,7 +66,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "EmptyStruct" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/RateLimit/RateLimitSpecsBase.cs
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ protected static void Within(TimeSpan timeSpan, Action actionContainingAssertion
TimeSpan retryInterval = TimeSpan.FromSeconds(0.2);

Stopwatch watch = Stopwatch.StartNew();
var token = CancellationToken.None;
var token = TestContext.Current.CancellationToken;

while (!token.IsCancellationRequested)
{
12 changes: 8 additions & 4 deletions test/Polly.Specs/Retry/RetryAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -26,7 +26,7 @@ public void Should_throw_when_action_is_null()
var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" });
var generic = methodInfo.MakeGenericMethod(typeof(EmptyStruct));

var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None, false]);
var func = () => generic.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken, false]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
@@ -296,7 +296,8 @@ public void Should_call_onretry_with_the_passed_context()
.RetryAsync((_, _, context) => contextData = context);

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key1", "value1", "key2", "value2"));
CreateDictionary("key1", "value1", "key2", "value2"),
cancellationToken: TestContext.Current.CancellationToken);

contextData.Should()
.ContainKeys("key1", "key2").And
@@ -339,19 +340,22 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_data()
[Fact]
public void Should_create_new_context_for_each_call_to_execute()
{
var cancellationToken = TestContext.Current.CancellationToken;
string? contextValue = null;

var policy = Policy
.Handle<DivideByZeroException>()
.RetryAsync((_, _, context) => contextValue = context["key"].ToString());

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "original_value"));
CreateDictionary("key", "original_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("original_value");

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "new_value"));
CreateDictionary("key", "new_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("new_value");
}
10 changes: 7 additions & 3 deletions test/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -162,7 +162,8 @@ public void Should_call_onretry_on_each_retry_with_the_passed_context()
.RetryForeverAsync((_, context) => contextData = context);

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key1", "value1", "key2", "value2"));
CreateDictionary("key1", "value1", "key2", "value2"),
cancellationToken: TestContext.Current.CancellationToken);

contextData.Should()
.ContainKeys("key1", "key2").And
@@ -203,19 +204,22 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_data()
[Fact]
public void Should_create_new_context_for_each_call_to_execute()
{
var cancellationToken = TestContext.Current.CancellationToken;
string? contextValue = null;

var policy = Policy
.Handle<DivideByZeroException>()
.RetryForeverAsync((_, context) => contextValue = context["key"].ToString());

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "original_value"));
CreateDictionary("key", "original_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("original_value");

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "new_value"));
CreateDictionary("key", "new_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("new_value");
}
2 changes: 1 addition & 1 deletion test/Polly.Specs/Retry/RetrySpecs.cs
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ public void Should_throw_when_action_is_null()
var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "TResult" });
var generic = methodInfo.MakeGenericMethod(typeof(EmptyStruct));

var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => generic.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/Retry/RetryTResultAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken, false]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
2 changes: 1 addition & 1 deletion test/Polly.Specs/Retry/RetryTResultSpecs.cs
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@ public void Should_throw_when_action_is_null()
var methods = instanceType.GetMethods(flags);
var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "EmptyStruct" });

var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]);
var func = () => methodInfo.Invoke(instance, [action, new Context(), TestContext.Current.CancellationToken]);

var exceptionAssertions = func.Should().Throw<TargetInvocationException>();
exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation.");
12 changes: 8 additions & 4 deletions test/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -487,7 +487,8 @@ public async Task Should_call_onretry_with_the_passed_context()
}, (_, _, context) => contextData = context);

await policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key1", "value1", "key2", "value2"));
CreateDictionary("key1", "value1", "key2", "value2"),
cancellationToken: TestContext.Current.CancellationToken);

contextData.Should()
.ContainKeys("key1", "key2").And
@@ -516,6 +517,7 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_data()
[Fact]
public async Task Should_create_new_context_for_each_call_to_execute()
{
var cancellationToken = TestContext.Current.CancellationToken;
string? contextValue = null;

var policy = Policy
@@ -527,12 +529,14 @@ public async Task Should_create_new_context_for_each_call_to_execute()
(_, _, context) => contextValue = context["key"].ToString());

await policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "original_value"));
CreateDictionary("key", "original_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("original_value");

await policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "new_value"));
CreateDictionary("key", "new_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("new_value");
}
@@ -682,7 +686,7 @@ await policy.ExecuteAsync(async (context, _) =>
}
},
CreateDictionary("RetryAfter", defaultRetryAfter), // Can also set an initial value for RetryAfter, in the Context passed into the call.
CancellationToken.None);
TestContext.Current.CancellationToken);

actualRetryDuration.Should().Be(expectedRetryDuration);
}
9 changes: 6 additions & 3 deletions test/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs
Original file line number Diff line number Diff line change
@@ -314,6 +314,7 @@ public void Should_create_new_context_for_each_call_to_policy()
{
Func<int, Context, TimeSpan> provider = (_, _) => 1.Seconds();

var cancellationToken = TestContext.Current.CancellationToken;
string? contextValue = null;

var policy = Policy
@@ -323,12 +324,14 @@ public void Should_create_new_context_for_each_call_to_policy()
(_, _, context) => contextValue = context["key"].ToString());

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "original_value"));
CreateDictionary("key", "original_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("original_value");

policy.RaiseExceptionAsync<DivideByZeroException>(
CreateDictionary("key", "new_value"));
CreateDictionary("key", "new_value"),
cancellationToken: cancellationToken);

contextValue.Should().Be("new_value");
}
@@ -423,7 +426,7 @@ await policy.ExecuteAsync(async (context, _) =>
}
},
CreateDictionary("RetryAfter", defaultRetryAfter), // Can also set an initial value for RetryAfter, in the Context passed into the call.
CancellationToken.None);
TestContext.Current.CancellationToken);

actualRetryDuration.Should().Be(expectedRetryDuration);
}
2 changes: 1 addition & 1 deletion test/Polly.Specs/Timeout/TimeoutSpecsBase.cs
Original file line number Diff line number Diff line change
@@ -19,7 +19,7 @@ public abstract class TimeoutSpecsBase : IDisposable
private DateTimeOffset _offsetUtcNow = DateTimeOffset.UtcNow;
private DateTime _utcNow = DateTime.UtcNow;

protected static CancellationToken CancellationToken => CancellationToken.None;
protected static CancellationToken CancellationToken => TestContext.Current.CancellationToken;

protected TimeoutSpecsBase()
{
1 change: 1 addition & 0 deletions test/Polly.Testing.Tests/Polly.Testing.Tests.csproj
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@
<Nullable>enable</Nullable>
<Threshold>100</Threshold>
<NoWarn>$(NoWarn);SA1600;SA1204</NoWarn>
<OutputType>Exe</OutputType>
<Include>[Polly.Testing]*</Include>
</PropertyGroup>