diff --git a/test/Microsoft.NET.Build.Extensions.Tasks.Tests/GivenAGetDependsOnNETStandardTask.cs b/test/Microsoft.NET.Build.Extensions.Tasks.Tests/GivenAGetDependsOnNETStandardTask.cs index 905c89ef6e87..d481acca8199 100644 --- a/test/Microsoft.NET.Build.Extensions.Tasks.Tests/GivenAGetDependsOnNETStandardTask.cs +++ b/test/Microsoft.NET.Build.Extensions.Tasks.Tests/GivenAGetDependsOnNETStandardTask.cs @@ -4,10 +4,11 @@ #nullable disable using System.Reflection; +using Microsoft.Build.Framework; namespace Microsoft.NET.Build.Tasks.UnitTests { - public class GivenAGetDependsOnNETStandardTask + public class GivenAGetDependsOnNETStandardTask(ITestOutputHelper log) : SdkTest(log) { [Fact] public void CanCheckThisAssembly() @@ -121,28 +122,38 @@ public void SucceedsOnMissingFileReturnsFalse() [Fact] public void SucceedsWithWarningOnLockedFile() { - var lockedFile = $"{nameof(SucceedsWithWarningOnLockedFile)}.dll"; + var testDir = TestAssetsManager.CreateTestDirectory(); + var lockedFileName = $"{nameof(SucceedsWithWarningOnLockedFile)}.dll"; + var lockedFilePath = Path.Combine(testDir.Path, lockedFileName); - try + // Create file with exclusive lock (no sharing) + using (var fileHandle = new FileStream(lockedFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { + // Verify the lock is actually held before running the task. + // On some CI machines, antimalware or file system filters can + // interfere with file locking, causing the test to be unreliable. + try + { + using var probe = new FileStream(lockedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); + Assert.Fail( + "File lock is not being enforced — the probe open should have thrown IOException. " + + "This may indicate antimalware or file system filter interference on this machine."); + } + catch (IOException) + { + // Expected — the lock is working correctly + } + var task = new GetDependsOnNETStandard() { BuildEngine = new MockBuildEngine(), - TaskEnvironment = TaskEnvironmentHelper.CreateForTest(), - References = new[] { new MockTaskItem() { ItemSpec = lockedFile } } + TaskEnvironment = TaskEnvironment.CreateWithProjectDirectoryAndEnvironment(testDir.Path), + References = new[] { new MockTaskItem() { ItemSpec = lockedFileName } } }; - // create file with no sharing - using (var fileHandle = new FileStream(lockedFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) - { - task.Execute().Should().BeTrue(); - task.DependsOnNETStandard.Should().BeFalse(); - ((MockBuildEngine)task.BuildEngine).Warnings.Count.Should().BeGreaterThan(0); - } - } - finally - { - File.Delete(lockedFile); + task.Execute().Should().BeTrue(); + task.DependsOnNETStandard.Should().BeFalse(); + ((MockBuildEngine)task.BuildEngine).Warnings.Count.Should().BeGreaterThan(0); } } }