Skip to content

fix: handle case-sensitive file overwrite on Windows and add tests #1259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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
45 changes: 31 additions & 14 deletions src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public override void AppendAllBytes(string path, ReadOnlySpan<byte> bytes)
AppendAllBytes(path, bytes.ToArray());
}
#endif

/// <inheritdoc />
public override void AppendAllLines(string path, IEnumerable<string> contents)
{
Expand Down Expand Up @@ -163,6 +163,11 @@ public override void Copy(string sourceFileName, string destFileName, bool overw
throw CommonExceptions.FileAlreadyExists(destFileName);
}

if (string.Equals(sourceFileName, destFileName, StringComparison.OrdinalIgnoreCase) && XFS.IsWindowsPlatform())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in all the other cases we use
mockFileDataAccessor.StringOperations.Equals(sourceFileName, destinationFileName) instead of relying on
string.Equals(..., ..., StringComparison.OrdinalIgnoreCase)

Is intentional or an oversight?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be an oversight.
We had one case here where we used string.Equals on purpose, as it should compare case-sensitive in all operating systems, but here it seems I overlooked it.

{
throw CommonExceptions.ProcessCannotAccessFileInUse(destFileName);
}

mockFileDataAccessor.RemoveFile(destFileName);
}

Expand Down Expand Up @@ -522,30 +527,37 @@ public override void Move(string sourceFileName, string destFileName)
mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName));
mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName));

if (mockFileDataAccessor.GetFile(destFileName) != null)
{
if (mockFileDataAccessor.StringOperations.Equals(destFileName, sourceFileName))
{
return;
}
else
{
throw new IOException("A file can not be created if it already exists.");
}
}

var sourceFile = mockFileDataAccessor.GetFile(sourceFileName);

if (sourceFile == null)
{
throw CommonExceptions.FileNotFound(sourceFileName);
}

if (!sourceFile.AllowedFileShare.HasFlag(FileShare.Delete))
{
throw CommonExceptions.ProcessCannotAccessFileInUse();
}

VerifyDirectoryExists(destFileName);

if (mockFileDataAccessor.GetFile(destFileName) != null)
{
if (mockFileDataAccessor.StringOperations.Equals(destFileName, sourceFileName))
{
if (XFS.IsWindowsPlatform())
{
mockFileDataAccessor.RemoveFile(sourceFileName);
mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime), false);
}
return;
}
else
{
throw new IOException("A file can not be created if it already exists.");
}
}

mockFileDataAccessor.RemoveFile(sourceFileName, false);
mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime), false);
}
Expand Down Expand Up @@ -822,6 +834,11 @@ public override void Replace(string sourceFileName, string destinationFileName,
throw CommonExceptions.FileNotFound(destinationFileName);
}

if (mockFileDataAccessor.StringOperations.Equals(sourceFileName, destinationFileName) && XFS.IsWindowsPlatform())
{
throw CommonExceptions.ProcessCannotAccessFileInUse();
}

if (destinationBackupFileName != null)
{
Copy(destinationFileName, destinationBackupFileName, overwrite: true);
Expand Down Expand Up @@ -1066,7 +1083,7 @@ public override void WriteAllBytes(string path, byte[] bytes)

mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(bytes.ToArray()), TimeAdjustments.All));
}

#if FEATURE_FILE_SPAN
/// <inheritdoc cref="IFile.WriteAllBytes(string,ReadOnlySpan{byte})"/>
public override void WriteAllBytes(string path, ReadOnlySpan<byte> bytes)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,22 @@ public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathCo
await That(action).Throws<NotSupportedException>();
}

[Test]
[WindowsOnly(WindowsSpecifics.Drives)]
public async Task MockFile_Copy_ShouldThrowIOExceptionWhenOverwritingWithSameNameDifferentCase()
{
var fileSystem = new MockFileSystem();
string path = @"C:\Temp\file.txt";
string pathUpper = @"C:\Temp\FILE.TXT";

fileSystem.File.WriteAllText(path, "Hello");

void Act() => fileSystem.File.Copy(path, pathUpper, true);

await That(Act).Throws<IOException>()
.WithMessage($"The process cannot access the file '{pathUpper}' because it is being used by another process.");
}

[Test]
[WindowsOnly(WindowsSpecifics.Drives)]
public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidDriveLetter()
Expand Down Expand Up @@ -417,4 +433,4 @@ public async Task MockFile_Copy_ShouldThrowIOExceptionForInvalidFileShare()

await That(action).Throws<IOException>();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,22 @@ public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenDestinationP
await That(action).Throws<NotSupportedException>();
}

[Test]
[WindowsOnly(WindowsSpecifics.Drives)]
public async Task MockFile_Move_CaseOnlyRename_ShouldChangeCase()
{
var fileSystem = new MockFileSystem();
string sourceFilePath = @"c:\temp\demo.txt";
string destFilePath = @"c:\temp\DEMO.TXT";
string sourceFileContent = "content";
fileSystem.File.WriteAllText(sourceFilePath, sourceFileContent);

fileSystem.File.Move(sourceFilePath, destFilePath);

await That(fileSystem.File.Exists(destFilePath)).IsTrue();
await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent);
}

[Test]
public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ public async Task MockFile_AppendText_CreatesNewFileForAppendToNonExistingFile()
await That(file.TextContents).IsEqualTo("New too!");
await That(filesystem.FileExists(filepath)).IsTrue();
}

#if !NET9_0_OR_GREATER
[Test]
public void Serializable_works()
Expand All @@ -567,7 +567,7 @@ public void Serializable_works()
Assert.Pass();
}
#endif

#if !NET9_0_OR_GREATER
[Test]
public async Task Serializable_can_deserialize()
Expand Down Expand Up @@ -670,7 +670,7 @@ public async Task MockFile_Replace_ShouldCreateBackup()
fileSystem.File.Replace(path1, path2, path3);

await That(fileSystem.File.ReadAllText(path3)).IsEqualTo("2");
}
}

[Test]
public async Task MockFile_Replace_ShouldThrowIfDirectoryOfBackupPathDoesNotExist()
Expand Down Expand Up @@ -730,4 +730,20 @@ public async Task MockFile_OpenRead_ShouldReturnReadOnlyStream()
await That(stream.CanWrite).IsFalse();
await That(() => stream.WriteByte(0)).Throws<NotSupportedException>();
}

[Test]
[WindowsOnly(WindowsSpecifics.Drives)]
public async Task MockFile_Replace_SourceAndDestinationDifferOnlyInCasing_ShouldThrowIOException()
{
var fileSystem = new MockFileSystem();
string sourceFilePath = @"c:\temp\demo.txt";
string destFilePath = @"c:\temp\DEMO.txt";
string fileContent = "content";
fileSystem.File.WriteAllText(sourceFilePath, fileContent);

void Act() => fileSystem.File.Replace(sourceFilePath, destFilePath, null, true);

await That(Act).Throws<IOException>()
.HasMessage("The process cannot access the file because it is being used by another process.");
}
}