Skip to content

Commit

Permalink
fix: throw IOException when creating a directory with a conflicting f…
Browse files Browse the repository at this point in the history
…ile (#969)

Fixes #968:
When creating a directory, check if a file with the same name already exists. If so, throw an IOException.
  • Loading branch information
vbreuss authored Apr 18, 2023
1 parent 941f487 commit 659f7b4
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions System.IO.Abstractions.sln
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_", "_", "{BBF7AD8D-5522-48C0-A906-00CBB72308A0}"
ProjectSection(SolutionItems) = preProject
Directory.Build.props = Directory.Build.props
global.json = global.json
EndProjectSection
EndProject
Global
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,15 @@ private IDirectoryInfo CreateDirectoryInternal(string path)
path = path.TrimEnd(' ');
}

if (!Exists(path))
var existingFile = mockFileDataAccessor.GetFile(path);
if (existingFile == null)
{
mockFileDataAccessor.AddDirectory(path);
}
else if (!existingFile.IsDirectory)
{
throw CommonExceptions.FileAlreadyExists("path");
}

var created = new MockDirectoryInfo(mockFileDataAccessor, path);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,20 @@ public void MockDirectoryInfo_LastWriteTimeUtc_ShouldReturnDefaultTimeForNonExis
Assert.That(result, Is.EqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime));
}

[Test]
public void MockDirectoryInfo_Create_WithConflictingFile_ShouldThrowIOException()
{
var fileSystem = new MockFileSystem();
fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content"));
var sut = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\foo\bar.txt"));

// Act
TestDelegate action = () => sut.Create();

// Assert
Assert.Throws<IOException>(action);
}

public void MockDirectoryInfo_CreationTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory()
{
var newTime = new DateTime(2022, 04, 06);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,19 @@ public void MockDirectory_Exists_ShouldReturnFalseForIllegalPath(string path)
Assert.IsFalse(result);
}

[Test]
public void MockDirectory_CreateDirectory_WithConflictingFile_ShouldThrowIOException()
{
var fileSystem = new MockFileSystem();
fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content"));

// Act
TestDelegate action = () => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\bar.txt"));

// Assert
Assert.Throws<IOException>(action);
}

[Test]
public void MockDirectory_Exists_ShouldReturnFalseForFiles()
{
Expand Down

0 comments on commit 659f7b4

Please sign in to comment.