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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NSubstitute;
using NUnit.Common;
using NUnit.Framework;

namespace NUnit.Engine.Services
{
/// <summary>
/// Exercises provider callbacks during return using only registered substitutes.
/// No remote implementation, process or agent-exit reporting is required.
/// </summary>
public class TestAgentServiceReturnCallbackTests
{
/// <summary>
/// A callback must be able to observe a rejected overlapping return before
/// the original return completes, including when that return subsequently fails.
/// </summary>
[TestCase(false)]
[TestCase(true)]
public void OverlappingReturnIsRejectedWithoutBlockingProviderCallback(bool failFirstReturn)
{
var agent = Substitute.For<ITestAgent>();
agent.Id.Returns(Guid.NewGuid());
var provider = Substitute.For<ITestAgentProvider, IService>();
provider.IsAgentAvailable(Arg.Any<TestPackage>()).Returns(true);
provider.GetAgent(Arg.Any<TestPackage>()).Returns(agent);
var services = new ServiceContext();
services.Add((IService)provider);
using var agency = new TestAgentService();
services.Add(agency);
services.ServiceManager.StartServices();
Task<Exception?>? overlapping = null;
bool completedInsideCallback = false;
int returns = 0;
try
{
var package = new TestPackage("offline.dll");
package.AddSetting(SettingDefinitions.TargetFrameworkName.WithValue(".NETCoreApp,Version=v10.0"), true);
agency.GetAgent(package);
provider.When(value => value.ReturnAgent(agent)).Do(_ =>
{
if (Interlocked.Increment(ref returns) != 1)
return;
overlapping = Task.Run(() => Capture(() => agency.ReturnAgent(agent)));
completedInsideCallback = overlapping.Wait(TimeSpan.FromSeconds(5));
if (failFirstReturn)
throw new IOException("Controlled provider return failure");
});

Exception? firstFailure = Capture(() => agency.ReturnAgent(agent));

Assert.That(overlapping, Is.Not.Null);
Assert.That(overlapping!.Wait(TimeSpan.FromSeconds(5)), Is.True,
"The overlapping return must finish before the fixture releases its services.");
Assert.That(completedInsideCallback, Is.True,
"Provider callbacks must not wait on a coordinator ownership lock.");
Assert.That(overlapping.Result, Is.TypeOf<InvalidOperationException>());
provider.Received(1).ReturnAgent(agent);
if (failFirstReturn)
{
Assert.That(firstFailure, Is.TypeOf<IOException>());
Assert.That(agency.IsAgentActive(agent.Id), Is.True);
agency.ReturnAgent(agent);
provider.Received(2).ReturnAgent(agent);
}
else
Assert.That(firstFailure, Is.Null);
Assert.That(agency.IsAgentActive(agent.Id), Is.False);
}
finally
{
// The old locking implementation completes only after the callback
// returns; join that bounded control even when an assertion fails.
overlapping?.Wait(TimeSpan.FromSeconds(5));
services.ServiceManager.Dispose();
}
}

private static Exception? Capture(Action action)
{
try
{
action();
return null;
}
catch (Exception exception)
{
return exception;
}
}
}
}
25 changes: 14 additions & 11 deletions src/NUnitEngine/nunit.engine/Services/TestAgentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,33 +117,36 @@ public virtual ITestAgent GetAgent(TestPackage package)
/// </summary>
/// <param name="agent">An agent previously provided by a call to GetAgent.</param>
/// <exception cref="InvalidOperationException">
/// If agent was never provided by the factory or was previously released.
/// If the agent was never acquired, was already released, or another return is in progress.
/// </exception>
/// <remarks>
/// Ownership is removed only after the provider confirms release. A failed
/// release may be retried through the same agency. Requests for one agent
/// are serialized without holding the ownership index lock during provider I/O.
/// release may be retried through the same agency. An overlapping return is
/// rejected without holding bookkeeping locks during provider I/O or callbacks.
/// Virtual to allow substitution of agents and providers in runner tests.
/// </remarks>
public virtual void ReturnAgent(ITestAgent agent)
{
AgentOwnership ownership;
lock (_agentOwners)
{
if (!_agentOwners.TryGetValue(agent.Id, out ownership!) || !ReferenceEquals(ownership.Agent, agent))
throw new InvalidOperationException("The agent was not acquired from this agency or was already released.");
if (!_agentOwners.TryGetValue(agent.Id, out ownership!) || !ReferenceEquals(ownership.Agent, agent)
|| ownership.Returning)
throw new InvalidOperationException("The agent is not owned or a return is already in progress.");
ownership.Returning = true;
}

lock (ownership)
try
{
if (ownership.Released)
throw new InvalidOperationException("The agent was already released.");

ownership.Provider.ReturnAgent(agent);
ownership.Released = true;
lock (_agentOwners)
_agentOwners.Remove(agent.Id);
}
finally
{
lock (_agentOwners)
ownership.Returning = false;
}
}

/// <summary>
Expand Down Expand Up @@ -228,7 +231,7 @@ internal AgentOwnership(ITestAgent agent, ITestAgentProvider provider)

internal ITestAgent Agent { get; }
internal ITestAgentProvider Provider { get; }
internal bool Released { get; set; }
internal bool Returning { get; set; }
internal string? ExitMessage { get; set; }
}

Expand Down