Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
2739e85
fix: added correct handling of file share in file stream constructor/…
HarrisonTCodes Oct 18, 2025
ec701cf
fix: added stateful tracking of unshared file streams and prevented m…
HarrisonTCodes Oct 18, 2025
2a70ae1
refactor: changed fileshare none streams state to use concurrent dict…
HarrisonTCodes Oct 30, 2025
18716e4
refactor: used existing common exception for file-in-use error in fil…
HarrisonTCodes Oct 30, 2025
c660094
feat: added handling of failed addition of exclusive file stream to t…
HarrisonTCodes Oct 30, 2025
d648b5e
chore: explicit API acceptance test changes
HarrisonTCodes Oct 31, 2025
9952eab
test: added exclusive mock file stream handling unit tests
HarrisonTCodes Oct 31, 2025
4e724f5
feat: added path normalization to mock file stream
HarrisonTCodes Oct 31, 2025
c9e04a2
fix: improved path normalization in mock file stream for relative paths
HarrisonTCodes Oct 31, 2025
f241cc2
fix: added improved handling of file stream options in factory method
HarrisonTCodes Nov 9, 2025
eabc64e
refactor: de-duplicated normalize/fix path logic moving method to pat…
HarrisonTCodes Nov 9, 2025
2db45c1
chore: explicit API acceptance test changes to cover path verifier ch…
HarrisonTCodes Nov 9, 2025
611907b
feat: added more rigorous tracking of open file streams and shares/ac…
HarrisonTCodes Nov 13, 2025
cd2a151
feat: moved open file handles state to mock file system and ran API a…
HarrisonTCodes Nov 14, 2025
fd3062a
feat: added proper checking of access and share on file stream constr…
HarrisonTCodes Nov 14, 2025
543acdb
test: added unit tests to cover simultaneous file stream opening with…
HarrisonTCodes Nov 14, 2025
795891b
fix: used explicit GUID call instead of target-typed new for clarity …
HarrisonTCodes Nov 14, 2025
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;

namespace System.IO.Abstractions.TestingHelpers;
Expand Down Expand Up @@ -110,4 +111,9 @@ public interface IMockFileDataAccessor : IFileSystem
/// Gets a reference to the underlying file system.
/// </summary>
IFileSystem FileSystem { get; }

/// <summary>
/// Gets a reference to the open file handles.
/// </summary>
ConcurrentDictionary<string, ConcurrentDictionary<Guid, (FileAccess, FileShare)>> FileHandles { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,7 @@ private FileSystemStream OpenInternal(
}
mockFileDataAccessor.AdjustTimes(mockFileData, timeAdjustments);

return new MockFileStream(mockFileDataAccessor, path, mode, access, options);
return new MockFileStream(mockFileDataAccessor, path, mode, access, FileShare.Read, options);
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Threading;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Collections.Concurrent;

namespace System.IO.Abstractions.TestingHelpers;

Expand Down Expand Up @@ -31,7 +32,9 @@ public NullFileSystemStream() : base(Null, ".", true)

private readonly IMockFileDataAccessor mockFileDataAccessor;
private readonly string path;
private readonly Guid guid = Guid.NewGuid();
private readonly FileAccess access = FileAccess.ReadWrite;
private readonly FileShare share = FileShare.Read;
private readonly FileOptions options;
private readonly MockFileData fileData;
private bool disposed;
Expand All @@ -42,6 +45,7 @@ public MockFileStream(
string path,
FileMode mode,
FileAccess access = FileAccess.ReadWrite,
FileShare share = FileShare.Read,
FileOptions options = FileOptions.None)
: base(new MemoryStream(),
path == null ? null : Path.GetFullPath(path),
Expand All @@ -51,6 +55,7 @@ public MockFileStream(
ThrowIfInvalidModeAccess(mode, access);

this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor));
path = mockFileDataAccessor.PathVerifier.FixPath(path);
this.path = path;
this.options = options;

Expand Down Expand Up @@ -97,7 +102,39 @@ public MockFileStream(
mockFileDataAccessor.AddFile(path, fileData);
}

var fileHandlesEntry = mockFileDataAccessor.FileHandles.GetOrAdd(
path,
_ => new ConcurrentDictionary<Guid, (FileAccess access, FileShare share)>());

var requiredShare = AccessToShare(access);
foreach (var (existingAccess, existingShare) in fileHandlesEntry.Values)
{
var existingRequiredShare = AccessToShare(existingAccess);
var existingBlocksNew = (existingShare & requiredShare) != requiredShare;
var newBlocksExisting = (share & existingRequiredShare) != existingRequiredShare;
if (existingBlocksNew || newBlocksExisting)
{
throw CommonExceptions.ProcessCannotAccessFileInUse(path);
}
}

fileHandlesEntry[guid] = (access, share);
this.access = access;
this.share = share;
}

private static FileShare AccessToShare(FileAccess access)
{
var share = FileShare.None;
if (access.HasFlag(FileAccess.Read))
{
share |= FileShare.Read;
}
if (access.HasFlag(FileAccess.Write))
{
share |= FileShare.Write;
}
return share;
}

private static void ThrowIfInvalidModeAccess(FileMode mode, FileAccess access)
Expand Down Expand Up @@ -144,6 +181,14 @@ protected override void Dispose(bool disposing)
{
return;
}
if (mockFileDataAccessor.FileHandles.TryGetValue(path, out var fileHandlesEntry))
{
fileHandlesEntry.TryRemove(guid, out _);
if (fileHandlesEntry.IsEmpty)
{
mockFileDataAccessor.FileHandles.TryRemove(path, out _);
}
}
InternalFlush();
base.Dispose(disposing);
OnClose();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,25 @@ public FileSystemStream New(string path, FileMode mode, FileAccess access)

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share)
=> new MockFileStream(mockFileSystem, path, mode, access);
=> new MockFileStream(mockFileSystem, path, mode, access, share);

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
=> new MockFileStream(mockFileSystem, path, mode, access);
=> new MockFileStream(mockFileSystem, path, mode, access, share);

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
=> new MockFileStream(mockFileSystem, path, mode, access);
=> new MockFileStream(mockFileSystem, path, mode, access, share);

/// <inheritdoc />
public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize,
FileOptions options)
=> new MockFileStream(mockFileSystem, path, mode, access, options);
=> new MockFileStream(mockFileSystem, path, mode, access, share, options);

#if FEATURE_FILESTREAM_OPTIONS
/// <inheritdoc />
public FileSystemStream New(string path, FileStreamOptions options)
=> new MockFileStream(mockFileSystem, path, options.Mode, options.Access, options.Options);
=> new MockFileStream(mockFileSystem, path, options.Mode, options.Access, options.Share, options.Options);
#endif

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
Expand All @@ -21,6 +22,10 @@ public class MockFileSystem : FileSystemBase, IMockFileDataAccessor
private readonly PathVerifier pathVerifier;
#if FEATURE_SERIALIZABLE
[NonSerialized]
#endif
private readonly ConcurrentDictionary<string, ConcurrentDictionary<Guid, (FileAccess access, FileShare share)>> fileHandles = new();
#if FEATURE_SERIALIZABLE
[NonSerialized]
#endif
private Func<DateTime> dateTimeProvider = defaultDateTimeProvider;
private static Func<DateTime> defaultDateTimeProvider = () => DateTime.UtcNow;
Expand Down Expand Up @@ -114,6 +119,9 @@ public MockFileSystem(IDictionary<string, MockFileData> files, MockFileSystemOpt
public IFileSystem FileSystem => this;
/// <inheritdoc />
public PathVerifier PathVerifier => pathVerifier;
/// <inheritdoc />
public ConcurrentDictionary<string, ConcurrentDictionary<Guid, (FileAccess, FileShare)>> FileHandles
=> fileHandles;

/// <summary>
/// Replaces the time provider with a mocked instance. This allows to influence the used time in tests.
Expand All @@ -128,19 +136,6 @@ public MockFileSystem MockTime(Func<DateTime> dateTimeProvider)
return this;
}

private string FixPath(string path, bool checkCaps = false)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL"));
}

var pathSeparatorFixed = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
var fullPath = Path.GetFullPath(pathSeparatorFixed);

return checkCaps ? GetPathWithCorrectDirectoryCapitalization(fullPath) : fullPath;
}

//If C:\foo exists, ensures that trying to save a file to "C:\FOO\file.txt" instead saves it to "C:\foo\file.txt".
private string GetPathWithCorrectDirectoryCapitalization(string fullPath)
{
Expand Down Expand Up @@ -194,7 +189,7 @@ public MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjus
/// <inheritdoc />
public MockFileData GetFile(string path)
{
path = FixPath(path).TrimSlashes();
path = pathVerifier.FixPath(path).TrimSlashes();
return GetFileWithoutFixingPath(path);
}

Expand All @@ -210,7 +205,9 @@ public MockDriveData GetDrive(string name)

private void SetEntry(string path, MockFileData mockFile)
{
path = FixPath(path, true).TrimSlashes();
path = GetPathWithCorrectDirectoryCapitalization(
pathVerifier.FixPath(path)
).TrimSlashes();

lock (files)
{
Expand All @@ -232,7 +229,9 @@ private void SetEntry(string path, MockFileData mockFile)
/// <inheritdoc />
public void AddFile(string path, MockFileData mockFile, bool verifyAccess = true)
{
var fixedPath = FixPath(path, true);
var fixedPath = GetPathWithCorrectDirectoryCapitalization(
pathVerifier.FixPath(path)
);

mockFile ??= new MockFileData(string.Empty);
var file = GetFile(fixedPath);
Expand Down Expand Up @@ -319,7 +318,9 @@ public MockFileData GetFile(IFileInfo path)
/// <inheritdoc />
public void AddDirectory(string path)
{
var fixedPath = FixPath(path, true);
var fixedPath = GetPathWithCorrectDirectoryCapitalization(
pathVerifier.FixPath(path)
);
var separator = Path.DirectorySeparatorChar.ToString();

if (FileExists(fixedPath) && FileIsReadOnly(fixedPath))
Expand Down Expand Up @@ -408,8 +409,8 @@ public void AddDrive(string name, MockDriveData mockDrive)
/// <inheritdoc />
public void MoveDirectory(string sourcePath, string destPath)
{
sourcePath = FixPath(sourcePath);
destPath = FixPath(destPath);
sourcePath = pathVerifier.FixPath(sourcePath);
destPath = pathVerifier.FixPath(destPath);

var sourcePathSequence = sourcePath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);

Expand Down Expand Up @@ -452,7 +453,7 @@ bool PathStartsWith(string path, string[] minMatch)
/// <inheritdoc />
public void RemoveFile(string path, bool verifyAccess = true)
{
path = FixPath(path);
path = pathVerifier.FixPath(path);

lock (files)
{
Expand All @@ -473,7 +474,7 @@ public bool FileExists(string path)
return false;
}

path = FixPath(path).TrimSlashes();
path = pathVerifier.FixPath(path).TrimSlashes();

lock (files)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,23 @@ public bool TryNormalizeDriveName(string name, out string result)
result = name;
return true;
}

/// <summary>
/// Resolves and normalizes a path.
/// </summary>
public string FixPath(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL"));
}

var pathSeparatorFixed = path.Replace(
_mockFileDataAccessor.Path.AltDirectorySeparatorChar,
_mockFileDataAccessor.Path.DirectorySeparatorChar
);
var fullPath = _mockFileDataAccessor.Path.GetFullPath(pathSeparatorFixed);

return fullPath;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace System.IO.Abstractions.TestingHelpers
System.Collections.Generic.IEnumerable<string> AllDrives { get; }
System.Collections.Generic.IEnumerable<string> AllFiles { get; }
System.Collections.Generic.IEnumerable<string> AllPaths { get; }
System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Concurrent.ConcurrentDictionary<System.Guid, System.ValueTuple<System.IO.FileAccess, System.IO.FileShare>>> FileHandles { get; }
System.IO.Abstractions.IFileSystem FileSystem { get; }
System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; }
System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; }
Expand Down Expand Up @@ -297,7 +298,7 @@ namespace System.IO.Abstractions.TestingHelpers
[System.Serializable]
public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport
{
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileOptions options = 0) { }
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { }
public override bool CanRead { get; }
public override bool CanWrite { get; }
public static System.IO.Abstractions.FileSystemStream Null { get; }
Expand Down Expand Up @@ -347,6 +348,7 @@ namespace System.IO.Abstractions.TestingHelpers
public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; }
public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; }
public override System.IO.Abstractions.IFile File { get; }
public System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Concurrent.ConcurrentDictionary<System.Guid, System.ValueTuple<System.IO.FileAccess, System.IO.FileShare>>> FileHandles { get; }
public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; }
public override System.IO.Abstractions.IFileStreamFactory FileStream { get; }
public System.IO.Abstractions.IFileSystem FileSystem { get; }
Expand Down Expand Up @@ -468,6 +470,7 @@ namespace System.IO.Abstractions.TestingHelpers
{
public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { }
public void CheckInvalidPathChars(string path, bool checkAdditional = false) { }
public string FixPath(string path) { }
public bool HasIllegalCharacters(string path, bool checkAdditional) { }
public void IsLegalAbsoluteOrRelative(string path, string paramName) { }
public string NormalizeDriveName(string name) { }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace System.IO.Abstractions.TestingHelpers
System.Collections.Generic.IEnumerable<string> AllDrives { get; }
System.Collections.Generic.IEnumerable<string> AllFiles { get; }
System.Collections.Generic.IEnumerable<string> AllPaths { get; }
System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Concurrent.ConcurrentDictionary<System.Guid, System.ValueTuple<System.IO.FileAccess, System.IO.FileShare>>> FileHandles { get; }
System.IO.Abstractions.IFileSystem FileSystem { get; }
System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; }
System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; }
Expand Down Expand Up @@ -346,7 +347,7 @@ namespace System.IO.Abstractions.TestingHelpers
[System.Serializable]
public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport
{
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileOptions options = 0) { }
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { }
public override bool CanRead { get; }
public override bool CanWrite { get; }
public static System.IO.Abstractions.FileSystemStream Null { get; }
Expand Down Expand Up @@ -402,6 +403,7 @@ namespace System.IO.Abstractions.TestingHelpers
public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; }
public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; }
public override System.IO.Abstractions.IFile File { get; }
public System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Concurrent.ConcurrentDictionary<System.Guid, System.ValueTuple<System.IO.FileAccess, System.IO.FileShare>>> FileHandles { get; }
public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; }
public override System.IO.Abstractions.IFileStreamFactory FileStream { get; }
public System.IO.Abstractions.IFileSystem FileSystem { get; }
Expand Down Expand Up @@ -524,6 +526,7 @@ namespace System.IO.Abstractions.TestingHelpers
{
public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { }
public void CheckInvalidPathChars(string path, bool checkAdditional = false) { }
public string FixPath(string path) { }
public bool HasIllegalCharacters(string path, bool checkAdditional) { }
public void IsLegalAbsoluteOrRelative(string path, string paramName) { }
public string NormalizeDriveName(string name) { }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace System.IO.Abstractions.TestingHelpers
System.Collections.Generic.IEnumerable<string> AllDrives { get; }
System.Collections.Generic.IEnumerable<string> AllFiles { get; }
System.Collections.Generic.IEnumerable<string> AllPaths { get; }
System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Concurrent.ConcurrentDictionary<System.Guid, System.ValueTuple<System.IO.FileAccess, System.IO.FileShare>>> FileHandles { get; }
System.IO.Abstractions.IFileSystem FileSystem { get; }
System.IO.Abstractions.TestingHelpers.PathVerifier PathVerifier { get; }
System.IO.Abstractions.TestingHelpers.StringOperations StringOperations { get; }
Expand Down Expand Up @@ -370,7 +371,7 @@ namespace System.IO.Abstractions.TestingHelpers
[System.Serializable]
public class MockFileStream : System.IO.Abstractions.FileSystemStream, System.IO.Abstractions.IFileSystemAclSupport
{
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileOptions options = 0) { }
public MockFileStream(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor, string path, System.IO.FileMode mode, System.IO.FileAccess access = 3, System.IO.FileShare share = 1, System.IO.FileOptions options = 0) { }
public override bool CanRead { get; }
public override bool CanWrite { get; }
public static System.IO.Abstractions.FileSystemStream Null { get; }
Expand Down Expand Up @@ -426,6 +427,7 @@ namespace System.IO.Abstractions.TestingHelpers
public override System.IO.Abstractions.IDirectoryInfoFactory DirectoryInfo { get; }
public override System.IO.Abstractions.IDriveInfoFactory DriveInfo { get; }
public override System.IO.Abstractions.IFile File { get; }
public System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Concurrent.ConcurrentDictionary<System.Guid, System.ValueTuple<System.IO.FileAccess, System.IO.FileShare>>> FileHandles { get; }
public override System.IO.Abstractions.IFileInfoFactory FileInfo { get; }
public override System.IO.Abstractions.IFileStreamFactory FileStream { get; }
public System.IO.Abstractions.IFileSystem FileSystem { get; }
Expand Down Expand Up @@ -549,6 +551,7 @@ namespace System.IO.Abstractions.TestingHelpers
{
public PathVerifier(System.IO.Abstractions.TestingHelpers.IMockFileDataAccessor mockFileDataAccessor) { }
public void CheckInvalidPathChars(string path, bool checkAdditional = false) { }
public string FixPath(string path) { }
public bool HasIllegalCharacters(string path, bool checkAdditional) { }
public void IsLegalAbsoluteOrRelative(string path, string paramName) { }
public string NormalizeDriveName(string name) { }
Expand Down
Loading
Loading