Skip to content

Commit

Permalink
fix: MockFile - clone the bytes in read/write allbytes methods (#856)
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesmoore committed Jun 9, 2022
1 parent ae9fb3a commit de8dd8e
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/System.IO.Abstractions.TestingHelpers/MockFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ public override byte[] ReadAllBytes(string path)
throw CommonExceptions.FileNotFound(path);
}
mockFileDataAccessor.GetFile(path).CheckFileAccess(path, FileAccess.Read);
return mockFileDataAccessor.GetFile(path).Contents;
return mockFileDataAccessor.GetFile(path).Contents.ToArray();
}

/// <inheritdoc />
Expand Down Expand Up @@ -784,7 +784,7 @@ public override void WriteAllBytes(string path, byte[] bytes)
mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path");
VerifyDirectoryExists(path);

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

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,28 @@ public void MockFile_ReadAllBytes_ShouldTolerateAltDirectorySeparatorInPath()

Assert.AreEqual(data, fileSystem.File.ReadAllBytes(altPath));
}

[Test]
public void MockFile_ReadAllBytes_ShouldReturnANewCopyOfTheFileContents()
{
var path = XFS.Path(@"c:\something\demo.bin");
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ path, new MockFileData(new byte[] { 1, 2, 3, 4 }) }
});

var firstRead = fileSystem.File.ReadAllBytes(path);

var secondRead = fileSystem.File.ReadAllBytes(path);

for (int i = 0; i < firstRead.Length; i++)
{
firstRead[i] += 1;
}

Assert.AreNotEqual(firstRead, secondRead);
}

#if FEATURE_ASYNC_FILE
[Test]
public async Task MockFile_ReadAllBytesAsync_ShouldReturnOriginalByteData()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,27 @@ public void MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfBytesAreN
Assert.That(exception.ParamName, Is.EqualTo("bytes"));
}

[Test]
public void MockFile_WriteAllBytes_ShouldWriteASeparateCopyToTheFileSystem()
{
var fileSystem = new MockFileSystem();
string path = XFS.Path(@"c:\something\file.bin");
fileSystem.AddDirectory(XFS.Path(@"c:\something"));
var fileContent = new byte[] { 1, 2, 3, 4 };

fileSystem.File.WriteAllBytes(path, fileContent);

for(int i = 0; i < fileContent.Length; i++)
{
fileContent[i] += 1;
}

var readAgain = fileSystem.File.ReadAllBytes(path);

Assert.AreNotEqual(fileContent, readAgain);
}


#if FEATURE_ASYNC_FILE
[Test]
public void MockFile_WriteAllBytesAsync_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists()
Expand Down

0 comments on commit de8dd8e

Please sign in to comment.