Skip to content

Commit 86b8bb5

Browse files
pianomanjhfgreinacher
authored andcommitted
Fix unreported bug: FileStream created with FileMode.Open or Truncate should throw an exception if the file is missing
1 parent 9222647 commit 86b8bb5

3 files changed

Lines changed: 20 additions & 2 deletions

File tree

System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,22 @@ public void MockFileStreamFactory_CreateInNonExistingDirectory_ShouldThrowDirect
8484
Assert.Throws<DirectoryNotFoundException>(() => fileStreamFactory.Create(XFS.Path(@"C:\Test\NonExistingDirectory\some_random_file.txt"), fileMode));
8585
}
8686

87+
[Test]
88+
[TestCase(FileMode.Open)]
89+
[TestCase(FileMode.Truncate)]
90+
public void MockFileStreamFactory_OpenNonExistingFile_ShouldThrowFileNotFoundException(FileMode fileMode)
91+
{
92+
// Arrange
93+
var fileSystem = new MockFileSystem();
94+
fileSystem.AddDirectory(XFS.Path(@"C:\Test"));
95+
96+
// Act
97+
var fileStreamFactory = new MockFileStreamFactory(fileSystem);
98+
99+
// Assert
100+
Assert.Throws<FileNotFoundException>(() => fileStreamFactory.Create(XFS.Path(@"C:\Test\some_random_file.txt"), fileMode));
101+
}
102+
87103
[Test]
88104
[TestCase(FileMode.CreateNew)]
89105
public void MockFileStreamFactory_CreateExistingFile_Should_Throw_IOException(FileMode fileMode)

System.IO.Abstractions.TestingHelpers/MockFile.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,7 @@ private Stream OpenInternal(
417417
else if (mode == FileMode.Append)
418418
streamType = MockFileStream.StreamType.APPEND;
419419

420-
return new MockFileStream(mockFileDataAccessor, path, streamType, options);
420+
return new MockFileStream(mockFileDataAccessor, path, streamType, options, mode);
421421
}
422422

423423
public override Stream OpenRead(string path)

System.IO.Abstractions.TestingHelpers/MockFileStream.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,9 @@ public MockFileStream(
7373
throw CommonExceptions.CouldNotFindPartOfPath(path);
7474
}
7575

76-
if (StreamType.READ.Equals(streamType))
76+
if (StreamType.READ.Equals(streamType)
77+
|| fileMode.Equals(FileMode.Open)
78+
|| fileMode.Equals(FileMode.Truncate))
7779
{
7880
throw CommonExceptions.FileNotFound(path);
7981
}

0 commit comments

Comments
 (0)