Skip to content

Commit

Permalink
refactor: avoid unnecessary allocations from using callbacks in `Exec…
Browse files Browse the repository at this point in the history
…uteExtensions` (#601)

Avoid allocations from anonymous functions from using the `ExecuteExtensions`.
Add explicit if-conditions instead.
  • Loading branch information
vbreuss committed May 13, 2024
1 parent 3a18916 commit fc4df09
Show file tree
Hide file tree
Showing 20 changed files with 482 additions and 758 deletions.
45 changes: 20 additions & 25 deletions Source/Testably.Abstractions.Testing/FileSystem/DirectoryMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ public IDirectoryInfo CreateTempSubdirectory(string? prefix = null)
_fileSystem.Execute.Path.GetTempPath(),
(prefix ?? "") + _fileSystem.Execute.Path.GetFileNameWithoutExtension(
_fileSystem.Execute.Path.GetRandomFileName()));
_fileSystem.Execute.OnMac(() => localBasePath = "/private" + localBasePath);
if (_fileSystem.Execute.IsMac)
{
localBasePath = "/private" + localBasePath;
}
basePath = localBasePath;
} while (_fileSystem.Directory.Exists(basePath));

Expand Down Expand Up @@ -689,39 +692,31 @@ private IDisposable RegisterMethod<T1>(string name, T1 parameter1)
private static void ThrowMissingFileCreatedTimeException(MockFileSystem fileSystem, string path)
{
#if NET7_0_OR_GREATER
fileSystem.Execute.OnMac(
() =>
throw ExceptionFactory.DirectoryNotFound(
fileSystem.Execute.Path.GetFullPath(path)),
() =>
throw ExceptionFactory.FileNotFound(
fileSystem.Execute.Path.GetFullPath(path)));
if (!fileSystem.Execute.IsMac)
#else
fileSystem.Execute.OnWindows(
() =>
throw ExceptionFactory.FileNotFound(
fileSystem.Execute.Path.GetFullPath(path)),
() =>
throw ExceptionFactory.DirectoryNotFound(
fileSystem.Execute.Path.GetFullPath(path)));
if (fileSystem.Execute.IsWindows)
#endif
{
throw ExceptionFactory.FileNotFound(
fileSystem.Execute.Path.GetFullPath(path));
}

throw ExceptionFactory.DirectoryNotFound(
fileSystem.Execute.Path.GetFullPath(path));
}

private static void ThrowMissingFileLastAccessOrLastWriteTimeException(
MockFileSystem fileSystem,
string path)
{
#if NET7_0_OR_GREATER
#if !NET7_0_OR_GREATER
if (!fileSystem.Execute.IsWindows)
{
throw ExceptionFactory.DirectoryNotFound(
fileSystem.Execute.Path.GetFullPath(path));
}
#endif
throw ExceptionFactory.FileNotFound(
fileSystem.Execute.Path.GetFullPath(path));
#else
fileSystem.Execute.OnWindows(
() =>
throw ExceptionFactory.FileNotFound(
fileSystem.Execute.Path.GetFullPath(path)),
() =>
throw ExceptionFactory.DirectoryNotFound(
fileSystem.Execute.Path.GetFullPath(path)));
#endif
}
}
19 changes: 11 additions & 8 deletions Source/Testably.Abstractions.Testing/FileSystem/DriveInfoMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,10 @@ public string VolumeLabel

// ReSharper disable once ConstantNullCoalescingCondition
_volumeLabel = value ?? _volumeLabel;
_fileSystem.Execute.NotOnWindows(
() => throw ExceptionFactory.OperationNotSupportedOnThisPlatform());
if (!_fileSystem.Execute.IsWindows)
{
throw ExceptionFactory.OperationNotSupportedOnThisPlatform();
}
}
}

Expand Down Expand Up @@ -286,12 +288,13 @@ private IDisposable RegisterProperty(string name, PropertyAccess access)

if (fileSystem.Execute.Path.IsPathRooted(driveName))
{
return fileSystem.Execute.OnWindows(() =>
{
string rootedPath = fileSystem.Execute.Path.GetPathRoot(driveName)!;
return $"{rootedPath.TrimEnd('\\')}\\";
},
() => fileSystem.Execute.Path.GetPathRoot(driveName)!);
if (fileSystem.Execute.IsWindows)
{
string rootedPath = fileSystem.Execute.Path.GetPathRoot(driveName)!;
return $"{rootedPath.TrimEnd('\\')}\\";
}

return fileSystem.Execute.Path.GetPathRoot(driveName)!;
}

throw ExceptionFactory.InvalidDriveName();
Expand Down
18 changes: 12 additions & 6 deletions Source/Testably.Abstractions.Testing/FileSystem/FileInfoMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ public long Length
Container.Type != FileSystemTypes.File)
{
throw ExceptionFactory.FileNotFound(
_fileSystem.Execute.OnNetFramework(
() => Location.FriendlyName,
() => Location.FullPath));
_fileSystem.Execute.IsNetFramework
? Location.FriendlyName
: Location.FullPath);
}

return Container.GetBytes().Length;
Expand Down Expand Up @@ -165,7 +165,11 @@ public FileSystemStream Create()
{
using IDisposable registration = RegisterMethod(nameof(Create));

_fileSystem.Execute.NotOnNetFramework(Refresh);
if (!_fileSystem.Execute.IsNetFramework)
{
Refresh();
}

return _fileSystem.File.Create(FullName);
}

Expand Down Expand Up @@ -234,8 +238,10 @@ public FileSystemStream Open(FileMode mode)
using IDisposable registration = RegisterMethod(nameof(Open),
mode);

_fileSystem.Execute.OnNetFrameworkIf(mode == FileMode.Append,
() => throw ExceptionFactory.AppendAccessOnlyInWriteOnlyMode());
if (_fileSystem.Execute.IsNetFramework && mode == FileMode.Append)
{
throw ExceptionFactory.AppendAccessOnlyInWriteOnlyMode();
}

return new FileStreamMock(
_fileSystem,
Expand Down
142 changes: 84 additions & 58 deletions Source/Testably.Abstractions.Testing/FileSystem/FileMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#if FEATURE_FILESYSTEM_ASYNC
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
#endif

// ReSharper disable PossibleMultipleEnumeration
Expand Down Expand Up @@ -179,12 +180,9 @@ public void Copy(string sourceFileName, string destFileName)
.New(sourceFileName)
.CopyTo(destFileName);
}
catch (UnauthorizedAccessException)
catch (UnauthorizedAccessException) when (_fileSystem.Execute.IsNetFramework)
{
_fileSystem.Execute.OnNetFramework(()
=> throw ExceptionFactory.AccessToPathDenied(sourceFileName));

throw;
throw ExceptionFactory.AccessToPathDenied(sourceFileName);
}
}

Expand All @@ -194,29 +192,28 @@ public void Copy(string sourceFileName, string destFileName, bool overwrite)
using IDisposable registration = RegisterMethod(nameof(Copy),
sourceFileName, destFileName, overwrite);

_fileSystem.Execute.OnNetFramework(
() =>
{
try
{
_fileSystem.FileInfo.New(sourceFileName
.EnsureValidFormat(_fileSystem, nameof(sourceFileName)))
.CopyTo(destFileName
.EnsureValidFormat(_fileSystem, nameof(destFileName)),
overwrite);
}
catch (UnauthorizedAccessException)
{
throw ExceptionFactory.AccessToPathDenied(sourceFileName);
}
},
() =>
if (_fileSystem.Execute.IsNetFramework)
{
try
{
_fileSystem.FileInfo.New(sourceFileName
.EnsureValidFormat(_fileSystem, nameof(sourceFileName)))
.CopyTo(destFileName
.EnsureValidFormat(_fileSystem, nameof(destFileName)), overwrite);
});
.EnsureValidFormat(_fileSystem, nameof(destFileName)),
overwrite);
}
catch (UnauthorizedAccessException)
{
throw ExceptionFactory.AccessToPathDenied(sourceFileName);
}
}
else
{
_fileSystem.FileInfo.New(sourceFileName
.EnsureValidFormat(_fileSystem, nameof(sourceFileName)))
.CopyTo(destFileName
.EnsureValidFormat(_fileSystem, nameof(destFileName)), overwrite);
}
}

/// <inheritdoc cref="IFile.Create(string)" />
Expand Down Expand Up @@ -517,15 +514,18 @@ public DateTime GetLastWriteTimeUtc(SafeFileHandle fileHandle)
public UnixFileMode GetUnixFileMode(string path)
{
using IDisposable registration = RegisterMethod(nameof(GetUnixFileMode),
path);
path);

if (_fileSystem.Execute.IsWindows)
{
throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform();
}

return _fileSystem.Execute.OnWindows(
() => throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform(),
() => _fileSystem.Storage.GetContainer(
_fileSystem.Storage.GetLocation(
path.EnsureValidFormat(_fileSystem))
.ThrowExceptionIfNotFound(_fileSystem))
.UnixFileMode);
return _fileSystem.Storage.GetContainer(
_fileSystem.Storage.GetLocation(
path.EnsureValidFormat(_fileSystem))
.ThrowExceptionIfNotFound(_fileSystem))
.UnixFileMode;
}
#endif

Expand All @@ -537,10 +537,12 @@ public UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle)
using IDisposable registration = RegisterMethod(nameof(GetUnixFileMode),
fileHandle);

return _fileSystem.Execute.OnWindows(
() => throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform(),
() => GetContainerFromSafeFileHandle(fileHandle)
.UnixFileMode);
if (_fileSystem.Execute.IsWindows)
{
throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform();
}

return GetContainerFromSafeFileHandle(fileHandle).UnixFileMode;
}
#endif

Expand Down Expand Up @@ -683,8 +685,10 @@ public byte[] ReadAllBytes(string path)
FileAccess.Read,
FileStreamFactoryMock.DefaultShare))
{
_fileSystem.Execute.NotOnWindows(() =>
container.AdjustTimes(TimeAdjustments.LastAccessTime));
if (!_fileSystem.Execute.IsWindows)
{
container.AdjustTimes(TimeAdjustments.LastAccessTime);
}

return container.GetBytes().ToArray();
}
Expand Down Expand Up @@ -769,8 +773,10 @@ public string ReadAllText(string path, Encoding encoding)
FileAccess.Read,
FileStreamFactoryMock.DefaultShare))
{
_fileSystem.Execute.NotOnWindows(() =>
container.AdjustTimes(TimeAdjustments.LastAccessTime));
if (!_fileSystem.Execute.IsWindows)
{
container.AdjustTimes(TimeAdjustments.LastAccessTime);
}

using (MemoryStream ms = new(container.GetBytes()))
using (StreamReader sr = new(ms, encoding))
Expand Down Expand Up @@ -895,10 +901,16 @@ public IEnumerable<string> ReadLines(string path, Encoding encoding)
IStorageLocation location =
_fileSystem.Storage.GetLocation(linkPath
.EnsureValidFormat(_fileSystem, nameof(linkPath)));
_fileSystem.Execute.OnWindows(
() => location.ThrowExceptionIfNotFound(_fileSystem),
() => location.ThrowExceptionIfNotFound(_fileSystem,
onDirectoryNotFound: ExceptionFactory.FileNotFound));
if (_fileSystem.Execute.IsWindows)
{
location.ThrowExceptionIfNotFound(_fileSystem);
}
else
{
location.ThrowExceptionIfNotFound(_fileSystem,
onDirectoryNotFound: ExceptionFactory.FileNotFound);
}

try
{
IStorageLocation? targetLocation =
Expand Down Expand Up @@ -1087,8 +1099,10 @@ public void SetUnixFileMode(string path, UnixFileMode mode)
using IDisposable registration = RegisterMethod(nameof(SetUnixFileMode),
path, mode);

_fileSystem.Execute.OnWindows(
() => throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform());
if (_fileSystem.Execute.IsWindows)
{
throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform();
}

IStorageContainer container = GetContainerFromPath(path);
container.UnixFileMode = mode;
Expand All @@ -1103,8 +1117,10 @@ public void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mode)
using IDisposable registration = RegisterMethod(nameof(SetUnixFileMode),
fileHandle, mode);

_fileSystem.Execute.OnWindows(
() => throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform());
if (_fileSystem.Execute.IsWindows)
{
throw ExceptionFactory.UnixFileModeNotSupportedOnThisPlatform();
}

IStorageContainer container = GetContainerFromSafeFileHandle(fileHandle);
container.UnixFileMode = mode;
Expand Down Expand Up @@ -1134,9 +1150,11 @@ public void WriteAllBytes(string path, byte[] bytes)
throw ExceptionFactory.AccessToPathDenied(path);
}

_fileSystem.Execute.OnWindowsIf(
container.Attributes.HasFlag(FileAttributes.Hidden),
() => throw ExceptionFactory.AccessToPathDenied());
if (_fileSystem.Execute.IsWindows && container.Attributes.HasFlag(FileAttributes.Hidden))
{
throw ExceptionFactory.AccessToPathDenied();
}

using (container.RequestAccess(
FileAccess.Write,
FileStreamFactoryMock.DefaultShare))
Expand Down Expand Up @@ -1267,9 +1285,12 @@ public void WriteAllText(string path, string? contents, Encoding encoding)

if (contents != null)
{
_fileSystem.Execute.OnWindowsIf(
container.Attributes.HasFlag(FileAttributes.Hidden),
() => throw ExceptionFactory.AccessToPathDenied());

if (_fileSystem.Execute.IsWindows && container.Attributes.HasFlag(FileAttributes.Hidden))
{
throw ExceptionFactory.AccessToPathDenied();
}

using (container.RequestAccess(
FileAccess.Write,
FileStreamFactoryMock.DefaultShare))
Expand Down Expand Up @@ -1326,10 +1347,15 @@ private static IEnumerable<string> EnumerateLines(string contents)
IStorageLocation location = _fileSystem.Storage.GetLocation(path);
if (exceptionMode == ExceptionMode.FileNotFoundExceptionOnLinuxAndMac)
{
_fileSystem.Execute.OnWindows(
() => location.ThrowExceptionIfNotFound(_fileSystem),
() => location.ThrowExceptionIfNotFound(_fileSystem,
onDirectoryNotFound: ExceptionFactory.FileNotFound));
if (_fileSystem.Execute.IsWindows)
{
location.ThrowExceptionIfNotFound(_fileSystem);
}
else
{
location.ThrowExceptionIfNotFound(_fileSystem,
onDirectoryNotFound: ExceptionFactory.FileNotFound);
}
}

if (exceptionMode == ExceptionMode.Default)
Expand Down

0 comments on commit fc4df09

Please sign in to comment.