Skip to content
Open
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
Expand Up @@ -40,6 +40,37 @@ public void RemoveHandle(string path, Guid guid)
}
}

/// <summary>
/// Returns <see langword="true" /> when an open handle prevents deleting the file at <paramref name="path" />.
/// On Windows, a file cannot be deleted while a handle opened without <see cref="FileShare.Delete" /> is open.
/// Unix allows deleting a file that is still open.
/// </summary>
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
32 changes: 21 additions & 11 deletions src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,9 @@ public override FileSystemStream Create(string path, int bufferSize) =>

/// <inheritdoc />
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)
{
Expand All @@ -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
Expand Down Expand Up @@ -271,6 +271,11 @@ public override void Decrypt(string path)
}
/// <inheritdoc />
public override void Delete(string path)
{
DeleteInternal(path, checkOpenHandles: true);
}

private void DeleteInternal(string path, bool checkOpenHandles)
{
mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path");

Expand All @@ -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);
}
Expand Down Expand Up @@ -635,13 +643,13 @@ public override FileSystemStream Open(string path, FileMode mode, FileAccess acc

/// <inheritdoc />
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
/// <inheritdoc />
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

Expand All @@ -667,6 +675,7 @@ private FileSystemStream OpenInternal(
string path,
FileMode mode,
FileAccess access,
FileShare share,
FileOptions options)
{
mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path");
Expand All @@ -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);
Expand All @@ -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);
}

/// <inheritdoc />
Expand All @@ -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);
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<IOException>();

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<IOException>();
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<IOException>();
}

[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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, MockFileData>
{
{ openFilePath, new MockFileData("I'm here") }
});
using var stream = filesystem.File.OpenRead(openFilePath);

var exception = await That(() => filesystem.Directory.Delete(directoryPath, true)).Throws<IOException>();
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<string, MockFileData>
{
{ 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<IOException>().And.Property("HResult").EqualTo(unchecked((int)0x80070020));
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, MockFileData>
{
{ filePath, new MockFileData("content") }
});
using var stream = fileSystem.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None);

await That(() => fileSystem.File.OpenRead(filePath)).Throws<IOException>();
}

[Test]
public async Task MockFile_Open_ShouldTruncateFileThatIsOpenWithSharedWriteAccess()
{
var filePath = XFS.Path(@"c:\something\file.txt");
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ 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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}