Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,11 @@ private TestAgentProviderProxy StartServer(string extensionDirectory = "fake")
_server.Start();
_stdout = _server.StandardOutput.ReadToEndAsync();
_stderr = _server.StandardError.ReadToEndAsync();
Assert.That(SpinWait.SpinUntil(() => File.Exists(ready) || _server.HasExited, 15000), Is.True, "Server readiness deadline exceeded.");
XElement? receipt = null;
Assert.That(SpinWait.SpinUntil(() => _server.HasExited ||
(receipt = ProviderServerReadiness.ReadIfAvailable(ready)) is not null, 15000), Is.True, "Server readiness deadline exceeded.");
Assert.That(_server.HasExited, Is.False, _server.HasExited ? Output() : string.Empty);
var record = XElement.Load(ready);
var record = receipt ?? throw new InvalidOperationException("Server readiness completed without a readable receipt.");
Assert.That((int)record.Attribute("pid")!, Is.EqualTo(_server.Id));
_endpoint = new IPEndPoint(IPAddress.Loopback, (int)record.Attribute("port")!);
return new TestAgentProviderProxy(_endpoint);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt

using System.IO;
using System.Xml.Linq;

namespace NUnit.Engine.TestHelpers
{
/// <summary>
/// Reads a published readiness receipt without treating a temporary file lock as readiness.
/// </summary>
internal static class ProviderServerReadiness
{
private const int SharingViolation = unchecked((int)0x80070020);
private const int LockViolation = unchecked((int)0x80070021);

/// <summary>
/// Returns a complete receipt once it can be read. The caller retains its original
/// readiness deadline and continues to check whether the child process has exited.
/// </summary>
/// <param name="path">The published receipt filename.</param>
/// <returns>The receipt, or null while the file is absent or temporarily locked.</returns>
/// <remarks>
/// Malformed XML and other I/O failures propagate. A readable receipt still needs
/// the caller's process-identity and endpoint validation.
/// </remarks>
internal static XElement? ReadIfAvailable(string path)
{
if (!File.Exists(path))
return null;

try
{
return XElement.Load(path);
}
catch (IOException exception) when (exception.HResult == SharingViolation || exception.HResult == LockViolation)
{
return null;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt

using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using NUnit.Framework;

namespace NUnit.Engine.TestHelpers
{
/// <summary>
/// Exercises real file-sharing failures without depending on machine speed or a child process race.
/// </summary>
[TestFixture]
public sealed class ProviderServerReadinessTests
{
private string _directory = null!;
private string _path = null!;

/// <summary>Creates an isolated receipt directory.</summary>
[SetUp]
public void CreateDirectory()
{
_directory = Path.Combine(TestContext.CurrentContext.WorkDirectory, "readiness-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_directory);
_path = Path.Combine(_directory, "ready.xml");
}

/// <summary>Removes the receipt after all owned handles have been disposed.</summary>
[TearDown]
public void RemoveDirectory()
{
Directory.Delete(_directory, true);
}

/// <summary>A missing receipt has not been published yet.</summary>
[Test]
public void MissingReceiptIsNotReady()
{
Assert.That(ProviderServerReadiness.ReadIfAvailable(_path), Is.Null);
}

/// <summary>A readable receipt retains its actual contents.</summary>
[Test]
public void ReadableReceiptIsReturned()
{
var expected = WriteReceipt();
Assert.That(XNode.DeepEquals(ProviderServerReadiness.ReadIfAvailable(_path), expected), Is.True);
}

/// <summary>
/// An existing file may still be unreadable. Real Windows sharing and range locks
/// must delay readiness rather than fail the fixture or bypass the lock.
/// </summary>
/// <param name="rangeLock">Whether a byte-range lock is used instead of exclusive sharing.</param>
/// <param name="expectedError">The native Windows error wrapped by IOException.</param>
[TestCase(false, unchecked((int)0x80070020))]
[TestCase(true, unchecked((int)0x80070021))]
[Platform("Win")]
#if NETCOREAPP
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
#endif
public void LockedReceiptBecomesReadyAfterHandleRelease(bool rangeLock, int expectedError)
{
var expected = WriteReceipt();
using (var holder = new FileStream(
_path,
FileMode.Open,
rangeLock ? FileAccess.Read : FileAccess.ReadWrite,
rangeLock ? FileShare.ReadWrite : FileShare.None))
{
if (rangeLock)
holder.Lock(0, holder.Length);
try
{
Assert.That(File.Exists(_path), Is.True);
Assert.That(() => XElement.Load(_path),
Throws.TypeOf<IOException>().With.Property(nameof(Exception.HResult)).EqualTo(expectedError));
Assert.That(ProviderServerReadiness.ReadIfAvailable(_path), Is.Null);
}
finally
{
if (rangeLock)
holder.Unlock(0, holder.Length);
}
}

Assert.That(XNode.DeepEquals(ProviderServerReadiness.ReadIfAvailable(_path), expected), Is.True);
}

/// <summary>A malformed published receipt is a real failure, not temporary unreadiness.</summary>
[Test]
public void MalformedReceiptFailsImmediately()
{
File.WriteAllText(_path, "<ready");
Assert.That(() => ProviderServerReadiness.ReadIfAvailable(_path), Throws.TypeOf<XmlException>());
}

/// <summary>Publishes complete XML before a controlled lock is acquired.</summary>
private XElement WriteReceipt()
{
var receipt = new XElement("ready", new XAttribute("pid", 123), new XAttribute("port", 4567));
receipt.Save(_path);
return receipt;
}
}
}
Loading