TestableIO / System.IO.Abstractions

Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access!
http://www.nuget.org/packages/System.IO.Abstractions
MIT License
1.51k stars 254 forks source link

The mock FileStream class does not handle shared file contents correctly. #1131

Open BillArmstrong opened 2 months ago

BillArmstrong commented 2 months ago

The source code below should write the values 0-9 to the console. Instead it writes the value 0 to the console ten times.

The code behaves as expected when using the real file system.

using System.IO.Abstractions;
using System.IO.Abstractions.TestingHelpers;

//var fileSystem = new FileSystem();
var fileSystem = new MockFileSystem();

var filename = fileSystem.Path.GetTempFileName();
try
{
    using var file1 = fileSystem.FileStream.New(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
    using var file2 = fileSystem.FileStream.New(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
    var buffer = new byte[4];

    for (int ix = 0; ix < 10; ix++)
    {
        file1.Position = 0;
        file1.Write(BitConverter.GetBytes(ix));
        file1.Flush();

        file2.Position = 0;
        file2.Flush();
        file2.Read(buffer);
        Console.WriteLine(BitConverter.ToInt32(buffer));
    }
}
finally
{
    fileSystem.File.Delete(filename);
}
vbreuss commented 2 months ago

Thanks for reporting this issue. The root cause, seems to be, that the underlying MemoryStream is not updated when accessed from a parallel file handle.