diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/FileHandles.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/FileHandles.cs index 06923b6b1..162615f4c 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/FileHandles.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/FileHandles.cs @@ -40,6 +40,37 @@ public void RemoveHandle(string path, Guid guid) } } + /// + /// Returns when an open handle prevents deleting the file at . + /// On Windows, a file cannot be deleted while a handle opened without is open. + /// Unix allows deleting a file that is still open. + /// + internal bool PreventsDeletion(string path, StringOperations stringOperations) + { + if (!MockUnixSupport.IsWindowsPlatform()) + { + return false; + } + + foreach (var pathHandles in handles) + { + if (!stringOperations.Equals(pathHandles.Key, path)) + { + continue; + } + + foreach (var (_, share) in pathHandles.Value.Values) + { + if (!share.HasFlag(FileShare.Delete)) + { + return true; + } + } + } + + return false; + } + private static FileShare AccessToShare(FileAccess access) { var share = FileShare.None; diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs index 6d8bc2718..ed1e77ebb 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs @@ -167,7 +167,9 @@ public override void Delete(string path, bool recursive) foreach (var affectedPath in affectedPaths) { var file = mockFileDataAccessor.GetFile(affectedPath); - if (file != null && !file.IsDirectory && !file.AllowedFileShare.HasFlag(FileShare.Delete)) + if (file != null && !file.IsDirectory && + (!file.AllowedFileShare.HasFlag(FileShare.Delete) || + mockFileDataAccessor.FileHandles.PreventsDeletion(affectedPath, mockFileDataAccessor.StringOperations))) { throw CommonExceptions.ProcessCannotAccessFileInUse(affectedPath); } diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs index ecded9cc8..08f755cd5 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs @@ -188,9 +188,9 @@ public override FileSystemStream Create(string path, int bufferSize) => /// public override FileSystemStream Create(string path, int bufferSize, FileOptions options) => - CreateInternal(path, FileAccess.ReadWrite, options); + CreateInternal(path, FileAccess.ReadWrite, FileShare.Read, options); - private FileSystemStream CreateInternal(string path, FileAccess access, FileOptions options) + private FileSystemStream CreateInternal(string path, FileAccess access, FileShare share, FileOptions options) { if (path == null) { @@ -203,7 +203,7 @@ private FileSystemStream CreateInternal(string path, FileAccess access, FileOpti var mockFileData = new MockFileData(new byte[0]); mockFileDataAccessor.AdjustTimes(mockFileData, TimeAdjustments.All); mockFileDataAccessor.AddFile(path, mockFileData); - return OpenInternal(path, FileMode.Open, access, options); + return OpenInternal(path, FileMode.Open, access, share, options); } #if FEATURE_CREATE_HARD_LINK @@ -271,6 +271,11 @@ public override void Decrypt(string path) } /// public override void Delete(string path) + { + DeleteInternal(path, checkOpenHandles: true); + } + + private void DeleteInternal(string path, bool checkOpenHandles) { mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); @@ -280,7 +285,10 @@ public override void Delete(string path) VerifyDirectoryExists(path); var file = mockFileDataAccessor.GetFile(path); - if (file != null && !file.AllowedFileShare.HasFlag(FileShare.Delete)) + if (file != null && (!file.AllowedFileShare.HasFlag(FileShare.Delete) || + checkOpenHandles && mockFileDataAccessor.FileHandles.PreventsDeletion( + mockFileDataAccessor.PathVerifier.FixPath(path), + mockFileDataAccessor.StringOperations))) { throw CommonExceptions.ProcessCannotAccessFileInUse(path); } @@ -635,13 +643,13 @@ public override FileSystemStream Open(string path, FileMode mode, FileAccess acc /// public override FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share) => - OpenInternal(path, mode, access, FileOptions.None); + OpenInternal(path, mode, access, share, FileOptions.None); #if FEATURE_FILESTREAM_OPTIONS /// public override FileSystemStream Open(string path, FileStreamOptions options) { - return OpenInternal(path, options.Mode, options.Access, options.Options); + return OpenInternal(path, options.Mode, options.Access, options.Share, options.Options); } #endif @@ -667,6 +675,7 @@ private FileSystemStream OpenInternal( string path, FileMode mode, FileAccess access, + FileShare share, FileOptions options) { mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); @@ -685,13 +694,14 @@ private FileSystemStream OpenInternal( if (!exists || mode == FileMode.CreateNew) { - return CreateInternal(path, access, options); + return CreateInternal(path, access, share, options); } if (mode == FileMode.Create || mode == FileMode.Truncate) { - Delete(path); - return CreateInternal(path, access, options); + // Truncating an open file is governed by the sharing check of the new stream, not by FileShare.Delete. + DeleteInternal(path, checkOpenHandles: false); + return CreateInternal(path, access, share, options); } var mockFileData = mockFileDataAccessor.GetFile(path); @@ -703,7 +713,7 @@ private FileSystemStream OpenInternal( } mockFileDataAccessor.AdjustTimes(mockFileData, timeAdjustments); - return new MockFileStream(mockFileDataAccessor, path, mode, access, FileShare.Read, options); + return new MockFileStream(mockFileDataAccessor, path, mode, access, share, options); } /// @@ -728,7 +738,7 @@ public override StreamReader OpenText(string path) private FileSystemStream OpenWriteInternal(string path, FileOptions options) { mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return OpenInternal(path, FileMode.OpenOrCreate, FileAccess.Write, options); + return OpenInternal(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, options); } /// diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs index 0f474bfcf..6a87ef344 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs @@ -60,4 +60,85 @@ public async Task MockFile_Delete_ShouldSilentlyReturnIfNonExistingFileInExistin // Delete() returns void, so there is nothing to check here beside absense of an exception await That(() => fileSystem.File.Delete(filePath)).DoesNotThrow(); } + + [Test] + [WindowsOnly(WindowsSpecifics.OpenFileDeletion)] + public async Task MockFile_Delete_ShouldThrowIOExceptionIfFileIsOpen() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\some_folder\test.txt"); + fileSystem.AddFile(path, new MockFileData("Bla")); + using var stream = fileSystem.File.OpenRead(path); + + var exception = await That(() => fileSystem.File.Delete(path)).Throws(); + + await That(exception.Message).IsEqualTo($"The process cannot access the file '{path}' because it is being used by another process."); + await That(fileSystem.File.Exists(path)).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.OpenFileDeletion)] + public async Task MockFileInfo_Delete_ShouldThrowIOExceptionIfFileIsOpen() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\some_folder\test.txt"); + fileSystem.AddFile(path, new MockFileData("Bla")); + var fileInfo = fileSystem.FileInfo.New(path); + using var stream = fileInfo.OpenWrite(); + + await That(() => fileInfo.Delete()).Throws(); + await That(fileSystem.File.Exists(path)).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.OpenFileDeletion)] + public async Task MockFile_Delete_ShouldThrowIOExceptionIfFileIsOpenWithDifferentCasing() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\some_folder\test.txt"); + fileSystem.AddFile(path, new MockFileData("Bla")); + using var stream = fileSystem.File.OpenRead(path.ToUpperInvariant()); + + await That(() => fileSystem.File.Delete(path)).Throws(); + } + + [Test] + public async Task MockFile_Delete_ShouldDeleteFileIfOpenedWithFileShareDelete() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\some_folder\test.txt"); + fileSystem.AddFile(path, new MockFileData("Bla")); + using var stream = fileSystem.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + + fileSystem.File.Delete(path); + + await That(fileSystem.File.Exists(path)).IsFalse(); + } + + [Test] + public async Task MockFile_Delete_ShouldDeleteFileAfterStreamIsDisposed() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\some_folder\test.txt"); + fileSystem.AddFile(path, new MockFileData("Bla")); + fileSystem.File.OpenRead(path).Dispose(); + + fileSystem.File.Delete(path); + + await That(fileSystem.File.Exists(path)).IsFalse(); + } + + [Test] + [UnixOnly(UnixSpecifics.OpenFileDeletion)] + public async Task MockFile_Delete_ShouldDeleteOpenFileOnUnix() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\some_folder\test.txt"); + fileSystem.AddFile(path, new MockFileData("Bla")); + using var stream = fileSystem.File.OpenRead(path); + + fileSystem.File.Delete(path); + + await That(fileSystem.File.Exists(path)).IsFalse(); + } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs index f0f9a6bbc..9791c2613 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs @@ -229,6 +229,36 @@ public async Task MockFile_Lock_FileShareDeleteDoesNotThrowRecursiveDirectoryDel await That(() => filesystem.Directory.Delete(directoryPath, true)).DoesNotThrow(); await That(filesystem.Directory.Exists(directoryPath)).IsFalse(); } + [Test] + [WindowsOnly(WindowsSpecifics.OpenFileDeletion)] + public async Task MockFile_Lock_OpenFileThrowsRecursiveDirectoryDelete() + { + string directoryPath = XFS.Path(@"c:\something\does"); + string openFilePath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { openFilePath, new MockFileData("I'm here") } + }); + using var stream = filesystem.File.OpenRead(openFilePath); + + var exception = await That(() => filesystem.Directory.Delete(directoryPath, true)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{openFilePath}' because it is being used by another process."); + await That(filesystem.File.Exists(openFilePath)).IsTrue(); + } + [Test] + public async Task MockFile_Lock_FileOpenedWithFileShareDeleteDoesNotThrowRecursiveDirectoryDelete() + { + string directoryPath = XFS.Path(@"c:\something\does"); + string openFilePath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { openFilePath, new MockFileData("I'm here") } + }); + using var stream = filesystem.File.Open(openFilePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + + await That(() => filesystem.Directory.Delete(directoryPath, true)).DoesNotThrow(); + await That(filesystem.Directory.Exists(directoryPath)).IsFalse(); + } private static IResolveConstraint IOException() => Is.TypeOf().And.Property("HResult").EqualTo(unchecked((int)0x80070020)); } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs index c5c280f4c..0096d9d80 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs @@ -378,4 +378,32 @@ public async Task MockFile_OpenWrite_ShouldWorkWithRelativePath() await That(fileSystem.File.Exists(file)).IsTrue(); } + + [Test] + public async Task MockFile_Open_ShouldUseRequestedFileShare() + { + var filePath = XFS.Path(@"c:\something\file.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("content") } + }); + using var stream = fileSystem.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None); + + await That(() => fileSystem.File.OpenRead(filePath)).Throws(); + } + + [Test] + public async Task MockFile_Open_ShouldTruncateFileThatIsOpenWithSharedWriteAccess() + { + var filePath = XFS.Path(@"c:\something\file.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { filePath, new MockFileData("content") } + }); + using var stream = fileSystem.File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); + + fileSystem.File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite).Dispose(); + + await That(fileSystem.File.ReadAllText(filePath)).IsEmpty(); + } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs index cd421f1c2..abcfa7aa2 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs @@ -7,4 +7,6 @@ internal static class UnixSpecifics public const string CaseSensitivity = "Paths are case-sensitive on Unix"; public const string WhitespaceOnlyNames = "Whitespace-only names are legal on Unix"; + + public const string OpenFileDeletion = "Unix allows deleting a file that is still open"; } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs index 1dcf4bf59..172282261 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs @@ -11,4 +11,6 @@ internal static class WindowsSpecifics public const string StrictPathRules = "Windows has stricter path rules than other platforms"; public const string CaseInsensitivity = "Paths are case-insensitive on Windows"; + + public const string OpenFileDeletion = "Windows does not delete a file that is open without FileShare.Delete"; } \ No newline at end of file