From 2fc6ec1af007daf7dedec699072e1bb63a7cea78 Mon Sep 17 00:00:00 2001 From: Valentin Date: Sat, 1 Mar 2025 16:45:25 +0100 Subject: [PATCH] refactor: use file-scoped namespaces --- .../FileSystemAbstractionBenchmarks.cs | 73 +- .../MockFileSystemBenchmarks.cs | 35 +- .../Program.cs | 19 +- .../Support/DirectorySupport.cs | 133 +- .../Support/DirectorySupportStatic.cs | 105 +- .../Support/FileSupport.cs | 71 +- .../Support/FileSupportStatic.cs | 39 +- .../CommonExceptions.cs | 189 +- .../IMockFileDataAccessor.cs | 207 +- .../MockDirectory.cs | 995 +++-- .../MockDirectoryData.cs | 45 +- .../MockDirectoryInfo.cs | 713 ++-- .../MockDirectoryInfoFactory.cs | 53 +- .../MockDriveData.cs | 121 +- .../MockDriveInfo.cs | 175 +- .../MockDriveInfoFactory.cs | 149 +- .../MockFile.cs | 1693 ++++---- .../MockFileData.cs | 383 +- .../MockFileInfo.cs | 667 ++- .../MockFileInfoFactory.cs | 53 +- .../MockFileStream.cs | 465 ++- .../MockFileStreamFactory.cs | 95 +- .../MockFileSystem.cs | 851 ++-- .../MockFileSystemOptions.cs | 27 +- .../MockFileSystemWatcherFactory.cs | 61 +- .../MockFileVersionInfo.cs | 273 +- .../MockFileVersionInfoFactory.cs | 47 +- .../MockPath.cs | 279 +- .../MockUnixSupport.cs | 43 +- .../PathVerifier.cs | 249 +- .../ProductVersionParser.cs | 143 +- .../StringExtensions.cs | 175 +- .../StringOperations.cs | 140 +- .../StringResources.cs | 15 +- .../TimeAdjustments.cs | 53 +- .../Converters.cs | 89 +- .../DirectoryAclExtensions.cs | 85 +- .../DirectoryBase.cs | 199 +- .../DirectoryInfoAclExtensions.cs | 109 +- .../DirectoryInfoBase.cs | 165 +- .../DirectoryInfoFactory.cs | 60 +- .../DirectoryInfoWrapper.cs | 475 ++- .../DirectoryWrapper.cs | 435 +- .../DriveInfoBase.cs | 93 +- .../DriveInfoFactory.cs | 80 +- .../DriveInfoWrapper.cs | 299 +- .../FileAclExtensions.cs | 67 +- .../FileBase.cs | 267 +- .../FileInfoAclExtensions.cs | 85 +- .../FileInfoBase.cs | 135 +- .../FileInfoFactory.cs | 60 +- .../FileInfoWrapper.cs | 485 ++- .../FileStreamAclExtensions.cs | 57 +- .../FileStreamFactory.cs | 94 +- .../FileStreamWrapper.cs | 69 +- .../FileSystem.cs | 91 +- .../FileSystemBase.cs | 51 +- .../FileSystemInfoBase.cs | 103 +- .../FileSystemWatcherBase.cs | 209 +- .../FileSystemWatcherFactory.cs | 63 +- .../FileSystemWatcherWrapper.cs | 329 +- .../FileVersionInfoBase.cs | 145 +- .../FileVersionInfoFactory.cs | 42 +- .../FileVersionInfoWrapper.cs | 365 +- .../FileWrapper.cs | 1007 +++-- .../PathBase.cs | 235 +- .../PathWrapper.cs | 571 ++- .../ApiParityTests.cs | 217 +- .../MockDirectoryArgumentPathTests.cs | 61 +- .../MockDirectoryGetAccessControlTests.cs | 99 +- .../MockDirectoryInfoAccessControlTests.cs | 89 +- .../MockDirectoryInfoFactoryTests.cs | 39 +- .../MockDirectoryInfoSymlinkTests.cs | 93 +- .../MockDirectoryInfoTests.cs | 1075 +++-- .../MockDirectorySetAccessControlTests.cs | 105 +- .../MockDirectorySymlinkTests.cs | 483 ++- .../MockDirectoryTests.cs | 3675 ++++++++--------- .../MockDriveInfoFactoryTests.cs | 205 +- .../MockDriveInfoTests.cs | 429 +- .../MockFileAdjustTimesTest.cs | 587 ++- .../MockFileAppendAllLinesTests.cs | 181 +- .../MockFileAppendAllTextTests.cs | 531 ++- .../MockFileArgumentPathTests.cs | 119 +- .../MockFileCopyTests.cs | 649 ++- .../MockFileCreateTests.cs | 457 +- .../MockFileDeleteTests.cs | 97 +- .../MockFileExistsTests.cs | 221 +- .../MockFileGetAccessControlTests.cs | 99 +- .../MockFileGetCreationTimeTests.cs | 89 +- .../MockFileGetCreationTimeUtcTests.cs | 89 +- .../MockFileGetLastAccessTimeTests.cs | 89 +- .../MockFileGetLastAccessTimeUtcTests.cs | 89 +- .../MockFileGetLastWriteTimeTests.cs | 89 +- .../MockFileGetLastWriteTimeUtcTests.cs | 85 +- .../MockFileInfoAccessControlTests.cs | 89 +- .../MockFileInfoFactoryTests.cs | 93 +- .../MockFileInfoSymlinkTests.cs | 93 +- .../MockFileInfoTests.cs | 1523 ++++--- .../MockFileLockTests.cs | 337 +- .../MockFileMoveTests.cs | 699 ++-- .../MockFileOpenTests.cs | 621 ++- .../MockFileReadAllBytesTests.cs | 213 +- .../MockFileReadAllLinesTests.cs | 239 +- .../MockFileReadLinesTests.cs | 79 +- .../MockFileSetAccessControlTests.cs | 99 +- .../MockFileSetAttributesTests.cs | 93 +- .../MockFileStreamFactoryTests.cs | 275 +- .../MockFileStreamTests.cs | 653 ++- .../MockFileSymlinkTests.cs | 543 ++- .../MockFileSystemOptionTests.cs | 53 +- .../MockFileSystemTests.cs | 931 +++-- .../MockFileSystemWatcherFactoryTests.cs | 89 +- .../MockFileTests.cs | 1221 +++--- .../MockFileVersionInfoFactoryTests.cs | 59 +- .../MockFileVersionInfoTests.cs | 123 +- .../MockFileWriteAllBytesTests.cs | 151 +- .../MockFileWriteAllLinesTests.cs | 971 +++-- .../MockFileWriteAllTextTests.cs | 709 ++-- .../MockPathTests.cs | 901 ++-- .../MockUnixSupportTests.cs | 35 +- .../ProductVersionParserTests.cs | 179 +- .../Shared.cs | 35 +- .../UnixOnlyAttribute.cs | 33 +- .../UnixSpecifics.cs | 13 +- .../WindowsOnlyAttribute.cs | 33 +- .../WindowsSpecifics.cs | 19 +- .../DirectoryInfoFactoryTests.cs | 21 +- .../DirectoryInfoTests.cs | 25 +- .../DirectoryWrapperTests.cs | 95 +- .../DriveInfoFactoryTests.cs | 21 +- .../FileInfoBaseConversionTests.cs | 33 +- .../FileInfoFactoryTests.cs | 21 +- .../FileSystemTests.cs | 187 +- .../FileSystemWatcherFactoryTests.cs | 21 +- .../FileVersionInfoBaseConversionTests.cs | 33 +- 135 files changed, 18507 insertions(+), 18648 deletions(-) diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/FileSystemAbstractionBenchmarks.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/FileSystemAbstractionBenchmarks.cs index 1fe771572..e5babe4dd 100644 --- a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/FileSystemAbstractionBenchmarks.cs +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/FileSystemAbstractionBenchmarks.cs @@ -4,46 +4,45 @@ using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Order; -namespace System.IO.Abstractions.Benchmarks +namespace System.IO.Abstractions.Benchmarks; + +//[SimpleJob(launchCount: 3, warmupCount: 10, targetCount: 30)] +[RPlotExporter] +[MemoryDiagnoser] +[Orderer(summaryOrderPolicy: SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +public class FileSystemAbstractionBenchmarks { - //[SimpleJob(launchCount: 3, warmupCount: 10, targetCount: 30)] - [RPlotExporter] - [MemoryDiagnoser] - [Orderer(summaryOrderPolicy: SummaryOrderPolicy.FastestToSlowest)] - [RankColumn] - public class FileSystemAbstractionBenchmarks - { - #region Members - /// - /// FileSupport type to avoid counting object initialisation on the benchmark - /// - private FileSupport _fileSupport; - private DirectorySupport _directorySupport; - #endregion + #region Members + /// + /// FileSupport type to avoid counting object initialisation on the benchmark + /// + private FileSupport _fileSupport; + private DirectorySupport _directorySupport; + #endregion - #region CTOR's - public FileSystemAbstractionBenchmarks() - { - // Initialize file support - _fileSupport = new FileSupport(); - _directorySupport = new DirectorySupport(); - } - #endregion + #region CTOR's + public FileSystemAbstractionBenchmarks() + { + // Initialize file support + _fileSupport = new FileSupport(); + _directorySupport = new DirectorySupport(); + } + #endregion - #region File IsFile - [Benchmark] - public void FileExists_DotNet() => FileSupportStatic.IsFile(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); + #region File IsFile + [Benchmark] + public void FileExists_DotNet() => FileSupportStatic.IsFile(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); - [Benchmark] - public void FileExists_Abstraction() => _fileSupport.IsFile(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); - #endregion + [Benchmark] + public void FileExists_Abstraction() => _fileSupport.IsFile(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); + #endregion - #region Directory Exists - [Benchmark] - public void DirectoryExists_DotNet() => DirectorySupportStatic.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); + #region Directory Exists + [Benchmark] + public void DirectoryExists_DotNet() => DirectorySupportStatic.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); - [Benchmark] - public void DirectoryExists_Abstraction() => _directorySupport.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); - #endregion - } -} + [Benchmark] + public void DirectoryExists_Abstraction() => _directorySupport.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); + #endregion +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/MockFileSystemBenchmarks.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/MockFileSystemBenchmarks.cs index a6e8a0f5c..8dce631fe 100644 --- a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/MockFileSystemBenchmarks.cs +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/MockFileSystemBenchmarks.cs @@ -4,24 +4,23 @@ using System.Linq; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.Benchmarks -{ - [RPlotExporter] - [MemoryDiagnoser] - public class MockFileSystemBenchmarks - { - private readonly Dictionary testData = CreateTestData(); +namespace System.IO.Abstractions.Benchmarks; - private static Dictionary CreateTestData() - { - var filesCount = 100000; - var maxDirectoryDepth = 8; - return Enumerable.Range(0, filesCount).ToDictionary( - i => XFS.Path(@$"C:\{string.Join(@"\", Enumerable.Range(0, i % maxDirectoryDepth + 1).Select(i => i.ToString()))}\{i}.bin"), - i => new MockFileData(i.ToString())); - } +[RPlotExporter] +[MemoryDiagnoser] +public class MockFileSystemBenchmarks +{ + private readonly Dictionary testData = CreateTestData(); - [Benchmark] - public MockFileSystem MockFileSystem_Constructor() => new MockFileSystem(testData); + private static Dictionary CreateTestData() + { + var filesCount = 100000; + var maxDirectoryDepth = 8; + return Enumerable.Range(0, filesCount).ToDictionary( + i => XFS.Path(@$"C:\{string.Join(@"\", Enumerable.Range(0, i % maxDirectoryDepth + 1).Select(i => i.ToString()))}\{i}.bin"), + i => new MockFileData(i.ToString())); } -} + + [Benchmark] + public MockFileSystem MockFileSystem_Constructor() => new MockFileSystem(testData); +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Program.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Program.cs index 491b08679..bb1b65c50 100644 --- a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Program.cs +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Program.cs @@ -1,13 +1,12 @@ -namespace System.IO.Abstractions.Benchmarks -{ - using BenchmarkDotNet.Running; - using System.Reflection; +namespace System.IO.Abstractions.Benchmarks; + +using BenchmarkDotNet.Running; +using System.Reflection; - class Program +class Program +{ + public static void Main(string[] args) { - public static void Main(string[] args) - { - BenchmarkRunner.Run(typeof(Program).Assembly); - } + BenchmarkRunner.Run(typeof(Program).Assembly); } -} +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupport.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupport.cs index 640bd44a0..02ca8d8ec 100644 --- a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupport.cs +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupport.cs @@ -2,93 +2,92 @@ using System.Collections.Generic; using System.Text; -namespace System.IO.Abstractions.Benchmarks.Support +namespace System.IO.Abstractions.Benchmarks.Support; + +public class DirectorySupport { - public class DirectorySupport + #region Members + private IFileSystem _fileSystem; + #endregion + + #region CTOR's + public DirectorySupport(IFileSystem fileSystem) { - #region Members - private IFileSystem _fileSystem; - #endregion + _fileSystem = fileSystem; + } - #region CTOR's - public DirectorySupport(IFileSystem fileSystem) - { - _fileSystem = fileSystem; - } + public DirectorySupport() : this(new FileSystem()) + { + // Default implementation for FileSystem + } + #endregion - public DirectorySupport() : this(new FileSystem()) - { - // Default implementation for FileSystem - } - #endregion + #region Methods + public bool IsDirectory(string path) + { + return _fileSystem.Directory.Exists(path); + } - #region Methods - public bool IsDirectory(string path) - { - return _fileSystem.Directory.Exists(path); - } + private string GetRandomTempDirectory() + { + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } + + public string CreateRandomDirectory() + { + var randomPath = this.GetRandomTempDirectory(); + _fileSystem.Directory.CreateDirectory(randomPath); + return randomPath; + } - private string GetRandomTempDirectory() + private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true, bool overwrite = true) + { + // Get the subdirectories for the specified directory. + var dir = _fileSystem.DirectoryInfo.New(sourceDirName); + if (!dir.Exists) { - return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + throw new DirectoryNotFoundException( + "Source directory does not exist or could not be found: " + + sourceDirName); } - public string CreateRandomDirectory() + var dirs = dir.GetDirectories(); + // If the destination directory doesn't exist, create it. + if (!_fileSystem.Directory.Exists(destDirName)) { - var randomPath = this.GetRandomTempDirectory(); - _fileSystem.Directory.CreateDirectory(randomPath); - return randomPath; + _fileSystem.Directory.CreateDirectory(destDirName); } - private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true, bool overwrite = true) + // Get the files in the directory and copy them to the new location. + var files = dir.GetFiles(); + foreach (var file in files) { - // Get the subdirectories for the specified directory. - var dir = _fileSystem.DirectoryInfo.New(sourceDirName); - if (!dir.Exists) - { - throw new DirectoryNotFoundException( - "Source directory does not exist or could not be found: " - + sourceDirName); - } - - var dirs = dir.GetDirectories(); - // If the destination directory doesn't exist, create it. - if (!_fileSystem.Directory.Exists(destDirName)) - { - _fileSystem.Directory.CreateDirectory(destDirName); - } - - // Get the files in the directory and copy them to the new location. - var files = dir.GetFiles(); - foreach (var file in files) - { - string temppath = Path.Combine(destDirName, file.Name); - file.CopyTo(temppath, overwrite); - } - - // If copying subdirectories, copy them and their contents to new location. - if (copySubDirs) - { - foreach (var subdir in dirs) - { - string temppath = Path.Combine(destDirName, subdir.Name); - DirectoryCopy(subdir.FullName, temppath, copySubDirs); - } - } + string temppath = Path.Combine(destDirName, file.Name); + file.CopyTo(temppath, overwrite); } - public void CreateIfNotExists(string directory) + // If copying subdirectories, copy them and their contents to new location. + if (copySubDirs) { - if (!_fileSystem.Directory.Exists(directory)) + foreach (var subdir in dirs) { - _fileSystem.Directory.CreateDirectory(directory); + string temppath = Path.Combine(destDirName, subdir.Name); + DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } + } - public bool Exists(string directory) + public void CreateIfNotExists(string directory) + { + if (!_fileSystem.Directory.Exists(directory)) { - return _fileSystem.Directory.Exists(directory); + _fileSystem.Directory.CreateDirectory(directory); } - #endregion } -} + + public bool Exists(string directory) + { + return _fileSystem.Directory.Exists(directory); + } + #endregion +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupportStatic.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupportStatic.cs index e623ec7d9..a0c1fcdfe 100644 --- a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupportStatic.cs +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/DirectorySupportStatic.cs @@ -1,72 +1,71 @@ -namespace System.IO.Abstractions.Benchmarks.Support +namespace System.IO.Abstractions.Benchmarks.Support; + +public static class DirectorySupportStatic { - public static class DirectorySupportStatic + #region Methods + public static bool IsDirectory(string path) + { + return Directory.Exists(path); + } + + private static string GetRandomTempDirectory() + { + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } + + public static string CreateDirectory() { - #region Methods - public static bool IsDirectory(string path) + var randomPath = GetRandomTempDirectory(); + Directory.CreateDirectory(randomPath); + return randomPath; + } + + private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true, bool overwrite = true) + { + // Get the subdirectories for the specified directory. + DirectoryInfo dir = new DirectoryInfo(sourceDirName); + + if (!dir.Exists) { - return Directory.Exists(path); + throw new DirectoryNotFoundException( + "Source directory does not exist or could not be found: " + + sourceDirName); } - private static string GetRandomTempDirectory() + DirectoryInfo[] dirs = dir.GetDirectories(); + // If the destination directory doesn't exist, create it. + if (!Directory.Exists(destDirName)) { - return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + Directory.CreateDirectory(destDirName); } - public static string CreateDirectory() + // Get the files in the directory and copy them to the new location. + FileInfo[] files = dir.GetFiles(); + foreach (FileInfo file in files) { - var randomPath = GetRandomTempDirectory(); - Directory.CreateDirectory(randomPath); - return randomPath; + string temppath = Path.Combine(destDirName, file.Name); + file.CopyTo(temppath, overwrite); } - private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true, bool overwrite = true) + // If copying subdirectories, copy them and their contents to new location. + if (copySubDirs) { - // Get the subdirectories for the specified directory. - DirectoryInfo dir = new DirectoryInfo(sourceDirName); - - if (!dir.Exists) + foreach (DirectoryInfo subdir in dirs) { - throw new DirectoryNotFoundException( - "Source directory does not exist or could not be found: " - + sourceDirName); - } - - DirectoryInfo[] dirs = dir.GetDirectories(); - // If the destination directory doesn't exist, create it. - if (!Directory.Exists(destDirName)) - { - Directory.CreateDirectory(destDirName); - } - - // Get the files in the directory and copy them to the new location. - FileInfo[] files = dir.GetFiles(); - foreach (FileInfo file in files) - { - string temppath = Path.Combine(destDirName, file.Name); - file.CopyTo(temppath, overwrite); - } - - // If copying subdirectories, copy them and their contents to new location. - if (copySubDirs) - { - foreach (DirectoryInfo subdir in dirs) - { - string temppath = Path.Combine(destDirName, subdir.Name); - DirectoryCopy(subdir.FullName, temppath, copySubDirs); - } + string temppath = Path.Combine(destDirName, subdir.Name); + DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } + } - public static void CreateIfNotExists(string directory) + public static void CreateIfNotExists(string directory) + { + if (!Directory.Exists(directory)) { - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } + Directory.CreateDirectory(directory); } - - public static bool Exists(string directory) => Directory.Exists(directory); - #endregion } -} + + public static bool Exists(string directory) => Directory.Exists(directory); + #endregion +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupport.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupport.cs index b4240f45d..1bece8d0b 100644 --- a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupport.cs +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupport.cs @@ -2,48 +2,47 @@ using System.Collections.Generic; using System.Text; -namespace System.IO.Abstractions.Benchmarks.Support +namespace System.IO.Abstractions.Benchmarks.Support; + +public class FileSupport { - public class FileSupport - { - #region Members - private IFileSystem _fileSystem; - #endregion + #region Members + private IFileSystem _fileSystem; + #endregion - #region CTOR's - public FileSupport(IFileSystem fileSystem) - { - _fileSystem = fileSystem; - } + #region CTOR's + public FileSupport(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } - public FileSupport() : this(new FileSystem()) - { - // Default implementation for FileSystem - } - #endregion + public FileSupport() : this(new FileSystem()) + { + // Default implementation for FileSystem + } + #endregion - #region Methods - public string GetRandomTempFile() - { - return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - } + #region Methods + public string GetRandomTempFile() + { + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } - public bool IsFile(string path) - { - return _fileSystem.File.Exists(path); - } + public bool IsFile(string path) + { + return _fileSystem.File.Exists(path); + } - /// - /// Checks and deletes given file if it does exists. - /// - /// Path of the file - public void DeleteIfExists(string filePath) + /// + /// Checks and deletes given file if it does exists. + /// + /// Path of the file + public void DeleteIfExists(string filePath) + { + if (_fileSystem.File.Exists(filePath)) { - if (_fileSystem.File.Exists(filePath)) - { - _fileSystem.File.Delete(filePath); - } + _fileSystem.File.Delete(filePath); } - #endregion } -} + #endregion +} \ No newline at end of file diff --git a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupportStatic.cs b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupportStatic.cs index feb3ebac4..83b44c4d2 100644 --- a/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupportStatic.cs +++ b/benchmarks/TestableIO.System.IO.Abstractions.Benchmarks/Support/FileSupportStatic.cs @@ -1,29 +1,28 @@ using System.IO; -namespace System.IO.Abstractions.Benchmarks.Support +namespace System.IO.Abstractions.Benchmarks.Support; + +public static class FileSupportStatic { - public static class FileSupportStatic + public static string GetRandomTempFile() { - public static string GetRandomTempFile() - { - return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - } + return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + } - public static bool IsFile(string path) - { - return File.Exists(path); - } + public static bool IsFile(string path) + { + return File.Exists(path); + } - /// - /// Checks and deletes given file if it does exists. - /// - /// Path of the file - public static void DeleteIfExists(string filePath) + /// + /// Checks and deletes given file if it does exists. + /// + /// Path of the file + public static void DeleteIfExists(string filePath) + { + if (File.Exists(filePath)) { - if (File.Exists(filePath)) - { - File.Delete(filePath); - } + File.Delete(filePath); } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/CommonExceptions.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/CommonExceptions.cs index 44837a40d..0f219e41d 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/CommonExceptions.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/CommonExceptions.cs @@ -1,104 +1,103 @@ using System.Globalization; -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +internal static class CommonExceptions { - internal static class CommonExceptions - { - private const int _fileLockHResult = unchecked((int)0x80070020); + private const int _fileLockHResult = unchecked((int)0x80070020); - public static FileNotFoundException FileNotFound(string path) => - new FileNotFoundException( - string.Format( - CultureInfo.InvariantCulture, - StringResources.Manager.GetString("COULD_NOT_FIND_FILE_EXCEPTION"), - path - ), + public static FileNotFoundException FileNotFound(string path) => + new FileNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("COULD_NOT_FIND_FILE_EXCEPTION"), + path + ), + path + ); + + public static DirectoryNotFoundException CouldNotFindPartOfPath(string path) => + new DirectoryNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("COULD_NOT_FIND_PART_OF_PATH_EXCEPTION"), + path + ) + ); + + public static UnauthorizedAccessException AccessDenied(string path) => + new UnauthorizedAccessException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("ACCESS_TO_THE_PATH_IS_DENIED"), path - ); - - public static DirectoryNotFoundException CouldNotFindPartOfPath(string path) => - new DirectoryNotFoundException( - string.Format( - CultureInfo.InvariantCulture, - StringResources.Manager.GetString("COULD_NOT_FIND_PART_OF_PATH_EXCEPTION"), - path - ) - ); - - public static UnauthorizedAccessException AccessDenied(string path) => - new UnauthorizedAccessException( - string.Format( - CultureInfo.InvariantCulture, - StringResources.Manager.GetString("ACCESS_TO_THE_PATH_IS_DENIED"), - path - ) - ); - - public static NotSupportedException InvalidUseOfVolumeSeparator() => - new NotSupportedException(StringResources.Manager.GetString("THE_PATH_IS_NOT_OF_A_LEGAL_FORM")); - - public static ArgumentException PathIsNotOfALegalForm(string paramName) => - new ArgumentException( - StringResources.Manager.GetString("THE_PATH_IS_NOT_OF_A_LEGAL_FORM"), - paramName - ); - - public static ArgumentNullException FilenameCannotBeNull(string paramName) => - new ArgumentNullException( - paramName, - StringResources.Manager.GetString("FILENAME_CANNOT_BE_NULL") - ); - - public static ArgumentException IllegalCharactersInPath(string paramName = null) => - paramName != null - ? new ArgumentException(StringResources.Manager.GetString("ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION"), paramName) - : new ArgumentException(StringResources.Manager.GetString("ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION")); - - public static ArgumentException InvalidUncPath(string paramName) => - new ArgumentException(@"The UNC path should be of the form \\server\share.", paramName); - - public static IOException ProcessCannotAccessFileInUse(string paramName = null) => - paramName != null + ) + ); + + public static NotSupportedException InvalidUseOfVolumeSeparator() => + new NotSupportedException(StringResources.Manager.GetString("THE_PATH_IS_NOT_OF_A_LEGAL_FORM")); + + public static ArgumentException PathIsNotOfALegalForm(string paramName) => + new ArgumentException( + StringResources.Manager.GetString("THE_PATH_IS_NOT_OF_A_LEGAL_FORM"), + paramName + ); + + public static ArgumentNullException FilenameCannotBeNull(string paramName) => + new ArgumentNullException( + paramName, + StringResources.Manager.GetString("FILENAME_CANNOT_BE_NULL") + ); + + public static ArgumentException IllegalCharactersInPath(string paramName = null) => + paramName != null + ? new ArgumentException(StringResources.Manager.GetString("ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION"), paramName) + : new ArgumentException(StringResources.Manager.GetString("ILLEGAL_CHARACTERS_IN_PATH_EXCEPTION")); + + public static ArgumentException InvalidUncPath(string paramName) => + new ArgumentException(@"The UNC path should be of the form \\server\share.", paramName); + + public static IOException ProcessCannotAccessFileInUse(string paramName = null) => + paramName != null ? new IOException(string.Format(StringResources.Manager.GetString("PROCESS_CANNOT_ACCESS_FILE_IN_USE_WITH_FILENAME"), paramName), _fileLockHResult) : new IOException(StringResources.Manager.GetString("PROCESS_CANNOT_ACCESS_FILE_IN_USE"), _fileLockHResult); - public static IOException FileAlreadyExists(string paramName) => - new IOException(string.Format(StringResources.Manager.GetString("FILE_ALREADY_EXISTS"), paramName)); - - public static ArgumentException InvalidAccessCombination(FileMode mode, FileAccess access) - => new ArgumentException(string.Format(StringResources.Manager.GetString("INVALID_ACCESS_COMBINATION"), mode, access), nameof(access)); - - public static ArgumentException AppendAccessOnlyInWriteOnlyMode() - => new ArgumentException(string.Format(StringResources.Manager.GetString("APPEND_ACCESS_ONLY_IN_WRITE_ONLY_MODE")), "access"); - - public static NotImplementedException NotImplemented() => - new NotImplementedException(StringResources.Manager.GetString("NOT_IMPLEMENTED_EXCEPTION")); - - public static IOException CannotCreateBecauseSameNameAlreadyExists(string path) => - new IOException( - string.Format( - CultureInfo.InvariantCulture, - StringResources.Manager.GetString("CANNOT_CREATE_BECAUSE_SAME_NAME_ALREADY_EXISTS"), - path - ) - ); - - public static IOException NameCannotBeResolvedByTheSystem(string path) => - new IOException( - string.Format( - CultureInfo.InvariantCulture, - StringResources.Manager.GetString("NAME_CANNOT_BE_RESOLVED_BY_THE_SYSTEM"), - path - ) - ); - - public static DirectoryNotFoundException PathDoesNotExistOrCouldNotBeFound(string path) => - new DirectoryNotFoundException( - string.Format( - CultureInfo.InvariantCulture, - StringResources.Manager.GetString("PATH_DOES_NOT_EXIST_OR_COULD_NOT_BE_FOUND"), - path - ) - ); - } + public static IOException FileAlreadyExists(string paramName) => + new IOException(string.Format(StringResources.Manager.GetString("FILE_ALREADY_EXISTS"), paramName)); + + public static ArgumentException InvalidAccessCombination(FileMode mode, FileAccess access) + => new ArgumentException(string.Format(StringResources.Manager.GetString("INVALID_ACCESS_COMBINATION"), mode, access), nameof(access)); + + public static ArgumentException AppendAccessOnlyInWriteOnlyMode() + => new ArgumentException(string.Format(StringResources.Manager.GetString("APPEND_ACCESS_ONLY_IN_WRITE_ONLY_MODE")), "access"); + + public static NotImplementedException NotImplemented() => + new NotImplementedException(StringResources.Manager.GetString("NOT_IMPLEMENTED_EXCEPTION")); + + public static IOException CannotCreateBecauseSameNameAlreadyExists(string path) => + new IOException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("CANNOT_CREATE_BECAUSE_SAME_NAME_ALREADY_EXISTS"), + path + ) + ); + + public static IOException NameCannotBeResolvedByTheSystem(string path) => + new IOException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("NAME_CANNOT_BE_RESOLVED_BY_THE_SYSTEM"), + path + ) + ); + + public static DirectoryNotFoundException PathDoesNotExistOrCouldNotBeFound(string path) => + new DirectoryNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + StringResources.Manager.GetString("PATH_DOES_NOT_EXIST_OR_COULD_NOT_BE_FOUND"), + path + ) + ); } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/IMockFileDataAccessor.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/IMockFileDataAccessor.cs index 03b2af206..69958077c 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/IMockFileDataAccessor.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/IMockFileDataAccessor.cs @@ -1,109 +1,108 @@ using System.Collections.Generic; using System.Reflection; -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides access to the file system storage. +/// +public interface IMockFileDataAccessor : IFileSystem { /// - /// Provides access to the file system storage. - /// - public interface IMockFileDataAccessor : IFileSystem - { - /// - /// Adjust the times of the . - /// - /// The for which the times should be adjusted. - /// The adjustments to make on the . - /// The adjusted file. - MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjustments); - - /// - /// Gets a file. - /// - /// The path of the file to get. - /// The file. if the file does not exist. - MockFileData GetFile(string path); - - /// - /// Gets a drive. - /// - /// The name of the drive to get. - /// The drive. if the drive does not exist. - MockDriveData GetDrive(string name); - - /// - /// - void AddFile(string path, MockFileData mockFile); - - /// - /// - void AddDirectory(string path); - - /// - /// - void AddDrive(string name, MockDriveData mockDrive); - - /// - /// - void AddFileFromEmbeddedResource(string path, Assembly resourceAssembly, string embeddedResourcePath); - - /// - /// - void AddFilesFromEmbeddedNamespace(string path, Assembly resourceAssembly, string embeddedResourcePath); - - /// - /// - void MoveDirectory(string sourcePath, string destPath); - - /// - /// Removes the file. - /// - /// The file to remove. - /// - /// The file must not exist. - /// - void RemoveFile(string path); - - /// - /// Determines whether the file exists. - /// - /// The file to check. - /// if the file exists; otherwise, . - bool FileExists(string path); - - /// - /// Gets all unique paths of all files and directories. - /// - IEnumerable AllPaths { get; } - - /// - /// Gets the paths of all files. - /// - IEnumerable AllFiles { get; } - - /// - /// Gets the paths of all directories. - /// - IEnumerable AllDirectories { get; } - - /// - /// Gets the names of all drives. - /// - IEnumerable AllDrives { get; } - - /// - /// Gets a helper for string operations. - /// - - StringOperations StringOperations { get; } - - /// - /// Gets a helper for verifying file system paths. - /// - PathVerifier PathVerifier { get; } - - /// - /// Gets a reference to the underlying file system. - /// - IFileSystem FileSystem { get; } - } -} + /// Adjust the times of the . + /// + /// The for which the times should be adjusted. + /// The adjustments to make on the . + /// The adjusted file. + MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjustments); + + /// + /// Gets a file. + /// + /// The path of the file to get. + /// The file. if the file does not exist. + MockFileData GetFile(string path); + + /// + /// Gets a drive. + /// + /// The name of the drive to get. + /// The drive. if the drive does not exist. + MockDriveData GetDrive(string name); + + /// + /// + void AddFile(string path, MockFileData mockFile); + + /// + /// + void AddDirectory(string path); + + /// + /// + void AddDrive(string name, MockDriveData mockDrive); + + /// + /// + void AddFileFromEmbeddedResource(string path, Assembly resourceAssembly, string embeddedResourcePath); + + /// + /// + void AddFilesFromEmbeddedNamespace(string path, Assembly resourceAssembly, string embeddedResourcePath); + + /// + /// + void MoveDirectory(string sourcePath, string destPath); + + /// + /// Removes the file. + /// + /// The file to remove. + /// + /// The file must not exist. + /// + void RemoveFile(string path); + + /// + /// Determines whether the file exists. + /// + /// The file to check. + /// if the file exists; otherwise, . + bool FileExists(string path); + + /// + /// Gets all unique paths of all files and directories. + /// + IEnumerable AllPaths { get; } + + /// + /// Gets the paths of all files. + /// + IEnumerable AllFiles { get; } + + /// + /// Gets the paths of all directories. + /// + IEnumerable AllDirectories { get; } + + /// + /// Gets the names of all drives. + /// + IEnumerable AllDrives { get; } + + /// + /// Gets a helper for string operations. + /// + + StringOperations StringOperations { get; } + + /// + /// Gets a helper for verifying file system paths. + /// + PathVerifier PathVerifier { get; } + + /// + /// Gets a reference to the underlying file system. + /// + IFileSystem FileSystem { get; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs index 272ba2ef4..141c01a2c 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectory.cs @@ -3,42 +3,42 @@ using System.Linq; using System.Text.RegularExpressions; -namespace System.IO.Abstractions.TestingHelpers -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers; +using XFS = MockUnixSupport; - /// + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockDirectory : DirectoryBase - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - private string currentDirectory; +public class MockDirectory : DirectoryBase +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private string currentDirectory; - /// - public MockDirectory(IMockFileDataAccessor mockFileDataAccessor, FileBase fileBase, string currentDirectory) : - this(mockFileDataAccessor, currentDirectory) - { - } + /// + public MockDirectory(IMockFileDataAccessor mockFileDataAccessor, FileBase fileBase, string currentDirectory) : + this(mockFileDataAccessor, currentDirectory) + { + } - /// - public MockDirectory(IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) : base( - mockFileDataAccessor?.FileSystem) - { - this.currentDirectory = currentDirectory; - this.mockFileDataAccessor = - mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); - } + /// + public MockDirectory(IMockFileDataAccessor mockFileDataAccessor, string currentDirectory) : base( + mockFileDataAccessor?.FileSystem) + { + this.currentDirectory = currentDirectory; + this.mockFileDataAccessor = + mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + } - /// - public override IDirectoryInfo CreateDirectory(string path) - { - return CreateDirectoryInternal(path); - } + /// + public override IDirectoryInfo CreateDirectory(string path) + { + return CreateDirectoryInternal(path); + } #if FEATURE_UNIX_FILE_MODE /// @@ -48,44 +48,44 @@ public override IDirectoryInfo CreateDirectory(string path, UnixFileMode unixCre } #endif - private IDirectoryInfo CreateDirectoryInternal(string path) + private IDirectoryInfo CreateDirectoryInternal(string path) + { + if (path == null) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + throw new ArgumentNullException(nameof(path)); + } - if (path.Length == 0) - { - throw new ArgumentException( - StringResources.Manager.GetString("PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE"), "path"); - } + if (path.Length == 0) + { + throw new ArgumentException( + StringResources.Manager.GetString("PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE"), "path"); + } - if (mockFileDataAccessor.PathVerifier.HasIllegalCharacters(path, true)) - { - throw CommonExceptions.IllegalCharactersInPath(nameof(path)); - } + if (mockFileDataAccessor.PathVerifier.HasIllegalCharacters(path, true)) + { + throw CommonExceptions.IllegalCharactersInPath(nameof(path)); + } - path = mockFileDataAccessor.Path.GetFullPath(path).TrimSlashes(); - if (XFS.IsWindowsPlatform()) - { - path = path.TrimEnd(' '); - } + path = mockFileDataAccessor.Path.GetFullPath(path).TrimSlashes(); + if (XFS.IsWindowsPlatform()) + { + path = path.TrimEnd(' '); + } - var existingFile = mockFileDataAccessor.GetFile(path); - if (existingFile == null) - { - mockFileDataAccessor.AddDirectory(path); - } - else if (!existingFile.IsDirectory) - { - throw CommonExceptions.FileAlreadyExists("path"); - } + var existingFile = mockFileDataAccessor.GetFile(path); + if (existingFile == null) + { + mockFileDataAccessor.AddDirectory(path); + } + else if (!existingFile.IsDirectory) + { + throw CommonExceptions.FileAlreadyExists("path"); + } - var created = new MockDirectoryInfo(mockFileDataAccessor, path); + var created = new MockDirectoryInfo(mockFileDataAccessor, path); - return created; - } + return created; + } #if FEATURE_CREATE_SYMBOLIC_LINK /// @@ -126,108 +126,108 @@ public override IDirectoryInfo CreateTempSubdirectory(string prefix = null) } #endif - /// - public override void Delete(string path) - { - Delete(path, false); - } - - - /// - public override void Delete(string path, bool recursive) - { - path = mockFileDataAccessor.Path.GetFullPath(path).TrimSlashes(); - - var stringOps = mockFileDataAccessor.StringOperations; - var pathWithDirectorySeparatorChar = $"{path}{Path.DirectorySeparatorChar}"; - - var affectedPaths = mockFileDataAccessor - .AllPaths - .Where(p => stringOps.Equals(p, path) || stringOps.StartsWith(p, pathWithDirectorySeparatorChar)) - .ToList(); - - if (!affectedPaths.Any()) - { - throw CommonExceptions.PathDoesNotExistOrCouldNotBeFound(path); - } + /// + public override void Delete(string path) + { + Delete(path, false); + } - if (!recursive && affectedPaths.Count > 1) - { - throw new IOException("The directory specified by " + path + - " is read-only, or recursive is false and " + path + - " is not an empty directory."); - } - bool isFile = !mockFileDataAccessor.GetFile(path).IsDirectory; - if (isFile) - { - throw new IOException("The directory name is invalid."); - } + /// + public override void Delete(string path, bool recursive) + { + path = mockFileDataAccessor.Path.GetFullPath(path).TrimSlashes(); - foreach (var affectedPath in affectedPaths) - { - mockFileDataAccessor.RemoveFile(affectedPath); - } - } + var stringOps = mockFileDataAccessor.StringOperations; + var pathWithDirectorySeparatorChar = $"{path}{Path.DirectorySeparatorChar}"; + var affectedPaths = mockFileDataAccessor + .AllPaths + .Where(p => stringOps.Equals(p, path) || stringOps.StartsWith(p, pathWithDirectorySeparatorChar)) + .ToList(); - /// - public override bool Exists(string path) + if (!affectedPaths.Any()) { - if (path == "/" && XFS.IsUnixPlatform()) - { - return true; - } - - try - { - path = path.TrimSlashes(); - path = mockFileDataAccessor.Path.GetFullPath(path); - return mockFileDataAccessor.GetFile(path)?.IsDirectory ?? false; - } - catch (Exception) - { - return false; - } + throw CommonExceptions.PathDoesNotExistOrCouldNotBeFound(path); } - - /// - public override DateTime GetCreationTime(string path) + if (!recursive && affectedPaths.Count > 1) { - return mockFileDataAccessor.File.GetCreationTime(path); + throw new IOException("The directory specified by " + path + + " is read-only, or recursive is false and " + path + + " is not an empty directory."); } - - /// - public override DateTime GetCreationTimeUtc(string path) + bool isFile = !mockFileDataAccessor.GetFile(path).IsDirectory; + if (isFile) { - return mockFileDataAccessor.File.GetCreationTimeUtc(path); + throw new IOException("The directory name is invalid."); } - /// - public override string GetCurrentDirectory() + foreach (var affectedPath in affectedPaths) { - return currentDirectory; + mockFileDataAccessor.RemoveFile(affectedPath); } + } - /// - public override string[] GetDirectories(string path) + + /// + public override bool Exists(string path) + { + if (path == "/" && XFS.IsUnixPlatform()) { - return GetDirectories(path, "*"); + return true; } - /// - public override string[] GetDirectories(string path, string searchPattern) + try { - return GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); + path = path.TrimSlashes(); + path = mockFileDataAccessor.Path.GetFullPath(path); + return mockFileDataAccessor.GetFile(path)?.IsDirectory ?? false; } - - /// - public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) + catch (Exception) { - return EnumerateDirectories(path, searchPattern, searchOption).ToArray(); + return false; } + } + + + /// + public override DateTime GetCreationTime(string path) + { + return mockFileDataAccessor.File.GetCreationTime(path); + } + + + /// + public override DateTime GetCreationTimeUtc(string path) + { + return mockFileDataAccessor.File.GetCreationTimeUtc(path); + } + + /// + public override string GetCurrentDirectory() + { + return currentDirectory; + } + + /// + public override string[] GetDirectories(string path) + { + return GetDirectories(path, "*"); + } + + /// + public override string[] GetDirectories(string path, string searchPattern) + { + return GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); + } + + /// + public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) + { + return EnumerateDirectories(path, searchPattern, searchOption).ToArray(); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -238,31 +238,31 @@ public override string[] GetDirectories(string path, string searchPattern, } #endif - /// - public override string GetDirectoryRoot(string path) - { - return Path.GetPathRoot(path); - } + /// + public override string GetDirectoryRoot(string path) + { + return Path.GetPathRoot(path); + } - /// - public override string[] GetFiles(string path) - { - // Same as what the real framework does - return GetFiles(path, "*"); - } + /// + public override string[] GetFiles(string path) + { + // Same as what the real framework does + return GetFiles(path, "*"); + } - /// - public override string[] GetFiles(string path, string searchPattern) - { - // Same as what the real framework does - return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); - } + /// + public override string[] GetFiles(string path, string searchPattern) + { + // Same as what the real framework does + return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); + } - /// - public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) - { - return GetFilesInternal(mockFileDataAccessor.AllFiles, path, searchPattern, searchOption); - } + /// + public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) + { + return GetFilesInternal(mockFileDataAccessor.AllFiles, path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -272,126 +272,126 @@ public override string[] GetFiles(string path, string searchPattern, Enumeration } #endif - private string[] GetFilesInternal( - IEnumerable files, - string path, - string searchPattern, - SearchOption searchOption) + private string[] GetFilesInternal( + IEnumerable files, + string path, + string searchPattern, + SearchOption searchOption) + { + if (path == null) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } - - if (path.Any(c => Path.GetInvalidPathChars().Contains(c))) - { - throw new ArgumentException("Invalid character(s) in path", nameof(path)); - } + throw new ArgumentNullException(nameof(path)); + } - CheckSearchPattern(searchPattern); - if (searchPattern.Equals(string.Empty, StringComparison.OrdinalIgnoreCase)) - { - searchPattern = "*"; - } + if (path.Any(c => Path.GetInvalidPathChars().Contains(c))) + { + throw new ArgumentException("Invalid character(s) in path", nameof(path)); + } - path = path.TrimSlashes(); - path = path.NormalizeSlashes(); - path = mockFileDataAccessor.Path.GetFullPath(path); + CheckSearchPattern(searchPattern); + if (searchPattern.Equals(string.Empty, StringComparison.OrdinalIgnoreCase)) + { + searchPattern = "*"; + } - if (!Exists(path)) - { - throw CommonExceptions.CouldNotFindPartOfPath(path); - } + path = path.TrimSlashes(); + path = path.NormalizeSlashes(); + path = mockFileDataAccessor.Path.GetFullPath(path); - if (!path.EndsWith(Path.DirectorySeparatorChar.ToString())) - { - path += Path.DirectorySeparatorChar; - } + if (!Exists(path)) + { + throw CommonExceptions.CouldNotFindPartOfPath(path); + } - var isUnix = XFS.IsUnixPlatform(); + if (!path.EndsWith(Path.DirectorySeparatorChar.ToString())) + { + path += Path.DirectorySeparatorChar; + } - var allDirectoriesPattern = isUnix - ? @"([^<>:""/|?*]*/)*" - : @"([^<>:""/\\|?*]*\\)*"; + var isUnix = XFS.IsUnixPlatform(); - var searchEndInStarDot = searchPattern.EndsWith(@"*."); + var allDirectoriesPattern = isUnix + ? @"([^<>:""/|?*]*/)*" + : @"([^<>:""/\\|?*]*\\)*"; - string fileNamePattern; - string pathPatternNoExtension = string.Empty; - string pathPatternEndsInDot = string.Empty; - string pathPatternSpecial = null; + var searchEndInStarDot = searchPattern.EndsWith(@"*."); - if (searchPattern == "*") - { - fileNamePattern = isUnix ? @"[^/]*?/?" : @"[^\\]*?\\?"; - } - else - { - fileNamePattern = Regex.Escape(searchPattern) - .Replace(@"\*", isUnix ? @"[^<>:""/|?*]*?" : @"[^<>:""/\\|?*]*?") - .Replace(@"\?", isUnix ? @"[^<>:""/|?*]?" : @"[^<>:""/\\|?*]?"); - - var extension = Path.GetExtension(searchPattern); - bool hasExtensionLengthOfThree = extension != null && extension.Length == 4 && - !extension.Contains("*") && !extension.Contains("?"); - if (hasExtensionLengthOfThree) - { - var fileNamePatternSpecial = - string.Format(CultureInfo.InvariantCulture, "{0}[^.]", fileNamePattern); - pathPatternSpecial = string.Format( - CultureInfo.InvariantCulture, - isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", - Regex.Escape(path), - searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, - fileNamePatternSpecial); - } - } + string fileNamePattern; + string pathPatternNoExtension = string.Empty; + string pathPatternEndsInDot = string.Empty; + string pathPatternSpecial = null; - var pathPattern = string.Format( - CultureInfo.InvariantCulture, - isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", - Regex.Escape(path), - searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, - fileNamePattern); + if (searchPattern == "*") + { + fileNamePattern = isUnix ? @"[^/]*?/?" : @"[^\\]*?\\?"; + } + else + { + fileNamePattern = Regex.Escape(searchPattern) + .Replace(@"\*", isUnix ? @"[^<>:""/|?*]*?" : @"[^<>:""/\\|?*]*?") + .Replace(@"\?", isUnix ? @"[^<>:""/|?*]?" : @"[^<>:""/\\|?*]?"); - if (searchEndInStarDot) + var extension = Path.GetExtension(searchPattern); + bool hasExtensionLengthOfThree = extension != null && extension.Length == 4 && + !extension.Contains("*") && !extension.Contains("?"); + if (hasExtensionLengthOfThree) { - pathPatternNoExtension = ReplaceLastOccurrence(pathPattern, @"]*?\.", @"\.]*?[.]*"); - pathPatternEndsInDot = ReplaceLastOccurrence(pathPattern, @"]*?\.", @"]*?[.]{1,}"); + var fileNamePatternSpecial = + string.Format(CultureInfo.InvariantCulture, "{0}[^.]", fileNamePattern); + pathPatternSpecial = string.Format( + CultureInfo.InvariantCulture, + isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", + Regex.Escape(path), + searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, + fileNamePatternSpecial); } - - return files.Where(p => - !searchEndInStarDot - ? (Regex.IsMatch(p, pathPattern) || - (pathPatternSpecial != null && Regex.IsMatch(p, pathPatternSpecial))) - : (Regex.IsMatch(p, pathPatternNoExtension) || Regex.IsMatch(p, pathPatternEndsInDot)) - ) - .ToArray(); } - /// - public override string[] GetFileSystemEntries(string path) + var pathPattern = string.Format( + CultureInfo.InvariantCulture, + isUnix ? @"(?i:^{0}{1}{2}(?:/?)$)" : @"(?i:^{0}{1}{2}(?:\\?)$)", + Regex.Escape(path), + searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty, + fileNamePattern); + + if (searchEndInStarDot) { - return GetFileSystemEntries(path, "*"); + pathPatternNoExtension = ReplaceLastOccurrence(pathPattern, @"]*?\.", @"\.]*?[.]*"); + pathPatternEndsInDot = ReplaceLastOccurrence(pathPattern, @"]*?\.", @"]*?[.]{1,}"); } - /// - public override string[] GetFileSystemEntries(string path, string searchPattern) - { - var dirs = GetDirectories(path, searchPattern); - var files = GetFiles(path, searchPattern); + return files.Where(p => + !searchEndInStarDot + ? (Regex.IsMatch(p, pathPattern) || + (pathPatternSpecial != null && Regex.IsMatch(p, pathPatternSpecial))) + : (Regex.IsMatch(p, pathPatternNoExtension) || Regex.IsMatch(p, pathPatternEndsInDot)) + ) + .ToArray(); + } - return dirs.Union(files).ToArray(); - } + /// + public override string[] GetFileSystemEntries(string path) + { + return GetFileSystemEntries(path, "*"); + } - /// - public override string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) - { - var dirs = GetDirectories(path, searchPattern, searchOption); - var files = GetFiles(path, searchPattern, searchOption); + /// + public override string[] GetFileSystemEntries(string path, string searchPattern) + { + var dirs = GetDirectories(path, searchPattern); + var files = GetFiles(path, searchPattern); - return dirs.Union(files).ToArray(); - } + return dirs.Union(files).ToArray(); + } + + /// + public override string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + var dirs = GetDirectories(path, searchPattern, searchOption); + var files = GetFiles(path, searchPattern, searchOption); + + return dirs.Union(files).ToArray(); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -402,147 +402,147 @@ public override string[] GetFileSystemEntries(string path, string searchPattern, } #endif - /// - public override DateTime GetLastAccessTime(string path) - { - return mockFileDataAccessor.File.GetLastAccessTime(path); - } + /// + public override DateTime GetLastAccessTime(string path) + { + return mockFileDataAccessor.File.GetLastAccessTime(path); + } - /// - public override DateTime GetLastAccessTimeUtc(string path) - { - return mockFileDataAccessor.File.GetLastAccessTimeUtc(path); - } + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + return mockFileDataAccessor.File.GetLastAccessTimeUtc(path); + } - /// - public override DateTime GetLastWriteTime(string path) + /// + public override DateTime GetLastWriteTime(string path) + { + return mockFileDataAccessor.File.GetLastWriteTime(path); + } + + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + return mockFileDataAccessor.File.GetLastWriteTimeUtc(path); + } + + /// + public override string[] GetLogicalDrives() + { + return mockFileDataAccessor + .AllDirectories + .Select(d => new MockDirectoryInfo(mockFileDataAccessor, d).Root.FullName) + .Select(r => mockFileDataAccessor.StringOperations.ToUpper(r)) + .Distinct() + .ToArray(); + } + + /// + public override IDirectoryInfo GetParent(string path) + { + if (path == null) { - return mockFileDataAccessor.File.GetLastWriteTime(path); + throw new ArgumentNullException(nameof(path)); } - /// - public override DateTime GetLastWriteTimeUtc(string path) + if (path.Length == 0) { - return mockFileDataAccessor.File.GetLastWriteTimeUtc(path); + throw new ArgumentException( + StringResources.Manager.GetString("PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE"), "path"); } - /// - public override string[] GetLogicalDrives() + if (mockFileDataAccessor.PathVerifier.HasIllegalCharacters(path, false)) { - return mockFileDataAccessor - .AllDirectories - .Select(d => new MockDirectoryInfo(mockFileDataAccessor, d).Root.FullName) - .Select(r => mockFileDataAccessor.StringOperations.ToUpper(r)) - .Distinct() - .ToArray(); + throw new ArgumentException("Path contains invalid path characters.", "path"); } - /// - public override IDirectoryInfo GetParent(string path) - { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + var absolutePath = mockFileDataAccessor.Path.GetFullPath(path); + var sepAsString = mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(); + var lastIndex = 0; - if (path.Length == 0) - { - throw new ArgumentException( - StringResources.Manager.GetString("PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE"), "path"); - } + if (absolutePath != sepAsString) + { + var startIndex = mockFileDataAccessor.StringOperations.EndsWith(absolutePath, sepAsString) + ? absolutePath.Length - 1 + : absolutePath.Length; + lastIndex = absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar, startIndex - 1); - if (mockFileDataAccessor.PathVerifier.HasIllegalCharacters(path, false)) + if (lastIndex < 0) { - throw new ArgumentException("Path contains invalid path characters.", "path"); + return null; } + } - var absolutePath = mockFileDataAccessor.Path.GetFullPath(path); - var sepAsString = mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(); - var lastIndex = 0; + var parentPath = absolutePath.Substring(0, lastIndex); - if (absolutePath != sepAsString) + if (string.IsNullOrEmpty(parentPath)) + { + // On the Unix platform, the parent of a path consisting of a slash followed by + // non-slashes is the root, '/'. + if (XFS.IsUnixPlatform()) { - var startIndex = mockFileDataAccessor.StringOperations.EndsWith(absolutePath, sepAsString) - ? absolutePath.Length - 1 - : absolutePath.Length; - lastIndex = absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar, startIndex - 1); + absolutePath = absolutePath.TrimSlashes(); - if (lastIndex < 0) + if (absolutePath.Length > 1 && + absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar) == 0) { - return null; + return new MockDirectoryInfo(mockFileDataAccessor, + mockFileDataAccessor.Path.DirectorySeparatorChar.ToString()); } } - var parentPath = absolutePath.Substring(0, lastIndex); - - if (string.IsNullOrEmpty(parentPath)) - { - // On the Unix platform, the parent of a path consisting of a slash followed by - // non-slashes is the root, '/'. - if (XFS.IsUnixPlatform()) - { - absolutePath = absolutePath.TrimSlashes(); + return null; + } - if (absolutePath.Length > 1 && - absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar) == 0) - { - return new MockDirectoryInfo(mockFileDataAccessor, - mockFileDataAccessor.Path.DirectorySeparatorChar.ToString()); - } - } + return new MockDirectoryInfo(mockFileDataAccessor, parentPath); + } - return null; - } + /// + public override void Move(string sourceDirName, string destDirName) + { + var fullSourcePath = mockFileDataAccessor.Path.GetFullPath(sourceDirName).TrimSlashes(); + var fullDestPath = mockFileDataAccessor.Path.GetFullPath(destDirName).TrimSlashes(); - return new MockDirectoryInfo(mockFileDataAccessor, parentPath); + if (mockFileDataAccessor.StringOperations.Equals(fullSourcePath, fullDestPath)) + { + throw new IOException("Source and destination path must be different."); } - /// - public override void Move(string sourceDirName, string destDirName) + //if we're moving a file, not a directory, call the appropriate file moving function. + var fileData = mockFileDataAccessor.GetFile(fullSourcePath); + if (fileData?.Attributes.HasFlag(FileAttributes.Directory) == false) { - var fullSourcePath = mockFileDataAccessor.Path.GetFullPath(sourceDirName).TrimSlashes(); - var fullDestPath = mockFileDataAccessor.Path.GetFullPath(destDirName).TrimSlashes(); - - if (mockFileDataAccessor.StringOperations.Equals(fullSourcePath, fullDestPath)) - { - throw new IOException("Source and destination path must be different."); - } - - //if we're moving a file, not a directory, call the appropriate file moving function. - var fileData = mockFileDataAccessor.GetFile(fullSourcePath); - if (fileData?.Attributes.HasFlag(FileAttributes.Directory) == false) - { - mockFileDataAccessor.File.Move(fullSourcePath, fullDestPath); - return; - } - - var sourceRoot = mockFileDataAccessor.Path.GetPathRoot(fullSourcePath); - var destinationRoot = mockFileDataAccessor.Path.GetPathRoot(fullDestPath); + mockFileDataAccessor.File.Move(fullSourcePath, fullDestPath); + return; + } - if (!mockFileDataAccessor.StringOperations.Equals(sourceRoot, destinationRoot)) - { - throw new IOException( - "Source and destination path must have identical roots. Move will not work across volumes."); - } + var sourceRoot = mockFileDataAccessor.Path.GetPathRoot(fullSourcePath); + var destinationRoot = mockFileDataAccessor.Path.GetPathRoot(fullDestPath); - if (!mockFileDataAccessor.Directory.Exists(fullSourcePath)) - { - throw CommonExceptions.CouldNotFindPartOfPath(sourceDirName); - } + if (!mockFileDataAccessor.StringOperations.Equals(sourceRoot, destinationRoot)) + { + throw new IOException( + "Source and destination path must have identical roots. Move will not work across volumes."); + } - if (!mockFileDataAccessor.Directory.GetParent(fullDestPath).Exists) - { - throw CommonExceptions.CouldNotFindPartOfPath(destDirName); - } + if (!mockFileDataAccessor.Directory.Exists(fullSourcePath)) + { + throw CommonExceptions.CouldNotFindPartOfPath(sourceDirName); + } - if (mockFileDataAccessor.Directory.Exists(fullDestPath) || mockFileDataAccessor.File.Exists(fullDestPath)) - { - throw CommonExceptions.CannotCreateBecauseSameNameAlreadyExists(fullDestPath); - } + if (!mockFileDataAccessor.Directory.GetParent(fullDestPath).Exists) + { + throw CommonExceptions.CouldNotFindPartOfPath(destDirName); + } - mockFileDataAccessor.MoveDirectory(fullSourcePath, fullDestPath); + if (mockFileDataAccessor.Directory.Exists(fullDestPath) || mockFileDataAccessor.File.Exists(fullDestPath)) + { + throw CommonExceptions.CannotCreateBecauseSameNameAlreadyExists(fullDestPath); } + mockFileDataAccessor.MoveDirectory(fullSourcePath, fullDestPath); + } + #if FEATURE_CREATE_SYMBOLIC_LINK /// public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) @@ -588,79 +588,79 @@ public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFi #endif - /// - public override void SetCreationTime(string path, DateTime creationTime) - { - mockFileDataAccessor.File.SetCreationTime(path, creationTime); - } + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + mockFileDataAccessor.File.SetCreationTime(path, creationTime); + } - /// - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - mockFileDataAccessor.File.SetCreationTimeUtc(path, creationTimeUtc); - } + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + mockFileDataAccessor.File.SetCreationTimeUtc(path, creationTimeUtc); + } - /// - public override void SetCurrentDirectory(string path) - { - currentDirectory = mockFileDataAccessor.Path.GetFullPath(path); - } + /// + public override void SetCurrentDirectory(string path) + { + currentDirectory = mockFileDataAccessor.Path.GetFullPath(path); + } - /// - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - mockFileDataAccessor.File.SetLastAccessTime(path, lastAccessTime); - } + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + mockFileDataAccessor.File.SetLastAccessTime(path, lastAccessTime); + } - /// - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - mockFileDataAccessor.File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); - } + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + mockFileDataAccessor.File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); + } - /// - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - mockFileDataAccessor.File.SetLastWriteTime(path, lastWriteTime); - } + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + mockFileDataAccessor.File.SetLastWriteTime(path, lastWriteTime); + } - /// - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - mockFileDataAccessor.File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); - } + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + mockFileDataAccessor.File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); + } - /// - public override IEnumerable EnumerateDirectories(string path) - { - return EnumerateDirectories(path, "*"); - } + /// + public override IEnumerable EnumerateDirectories(string path) + { + return EnumerateDirectories(path, "*"); + } - /// - public override IEnumerable EnumerateDirectories(string path, string searchPattern) - { - return EnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); - } + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern) + { + return EnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); + } - /// - public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - var originalPath = path; - path = path.TrimSlashes(); - path = mockFileDataAccessor.Path.GetFullPath(path); - return GetFilesInternal(mockFileDataAccessor.AllDirectories, path, searchPattern, searchOption) - .Where(p => !mockFileDataAccessor.StringOperations.Equals(p, path)) - .Select(p => FixPrefix(p, originalPath)); - } + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + var originalPath = path; + path = path.TrimSlashes(); + path = mockFileDataAccessor.Path.GetFullPath(path); + return GetFilesInternal(mockFileDataAccessor.AllDirectories, path, searchPattern, searchOption) + .Where(p => !mockFileDataAccessor.StringOperations.Equals(p, path)) + .Select(p => FixPrefix(p, originalPath)); + } - private string FixPrefix(string path, string originalPath) - { - var normalizedOriginalPath = mockFileDataAccessor.Path.GetFullPath(originalPath); - var pathWithoutOriginalPath = path.Substring(normalizedOriginalPath.Length) - .TrimStart(mockFileDataAccessor.Path.DirectorySeparatorChar); - return mockFileDataAccessor.Path.Combine(originalPath, pathWithoutOriginalPath); - } + private string FixPrefix(string path, string originalPath) + { + var normalizedOriginalPath = mockFileDataAccessor.Path.GetFullPath(originalPath); + var pathWithoutOriginalPath = path.Substring(normalizedOriginalPath.Length) + .TrimStart(mockFileDataAccessor.Path.DirectorySeparatorChar); + return mockFileDataAccessor.Path.Combine(originalPath, pathWithoutOriginalPath); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -671,23 +671,23 @@ public override IEnumerable EnumerateDirectories(string path, string sea } #endif - /// - public override IEnumerable EnumerateFiles(string path) - { - return GetFiles(path); - } + /// + public override IEnumerable EnumerateFiles(string path) + { + return GetFiles(path); + } - /// - public override IEnumerable EnumerateFiles(string path, string searchPattern) - { - return GetFiles(path, searchPattern); - } + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern) + { + return GetFiles(path, searchPattern); + } - /// - public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) - { - return GetFiles(path, searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) + { + return GetFiles(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -698,23 +698,23 @@ public override IEnumerable EnumerateFiles(string path, string searchPat } #endif - /// - public override IEnumerable EnumerateFileSystemEntries(string path) - { - return GetFileSystemEntries(path); - } + /// + public override IEnumerable EnumerateFileSystemEntries(string path) + { + return GetFileSystemEntries(path); + } - /// - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) - { - return GetFileSystemEntries(path, searchPattern); - } + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) + { + return GetFileSystemEntries(path, searchPattern); + } - /// - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) - { - return GetFileSystemEntries(path, searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + return GetFileSystemEntries(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -727,65 +727,65 @@ public override IEnumerable EnumerateFileSystemEntries(string path, stri } #endif - private string EnsureAbsolutePath(string path) - { - return Path.IsPathRooted(path) - ? path - : Path.Combine(GetCurrentDirectory(), path); - } + private string EnsureAbsolutePath(string path) + { + return Path.IsPathRooted(path) + ? path + : Path.Combine(GetCurrentDirectory(), path); + } - private void CheckSearchPattern(string searchPattern) + private void CheckSearchPattern(string searchPattern) + { + if (searchPattern == null) { - if (searchPattern == null) - { - throw new ArgumentNullException(nameof(searchPattern)); - } - - const string TWO_DOTS = ".."; - Func createException = () => new ArgumentException(@"Search pattern cannot contain "".."" to move up directories and can be contained only internally in file/directory names, as in ""a..b"".", searchPattern); + throw new ArgumentNullException(nameof(searchPattern)); + } - if (mockFileDataAccessor.StringOperations.EndsWith(searchPattern, TWO_DOTS)) - { - throw createException(); - } + const string TWO_DOTS = ".."; + Func createException = () => new ArgumentException(@"Search pattern cannot contain "".."" to move up directories and can be contained only internally in file/directory names, as in ""a..b"".", searchPattern); - var position = mockFileDataAccessor.StringOperations.IndexOf(searchPattern, TWO_DOTS); + if (mockFileDataAccessor.StringOperations.EndsWith(searchPattern, TWO_DOTS)) + { + throw createException(); + } - if (position >= 0) - { - var characterAfterTwoDots = searchPattern[position + 2]; + var position = mockFileDataAccessor.StringOperations.IndexOf(searchPattern, TWO_DOTS); - if (characterAfterTwoDots == Path.DirectorySeparatorChar || characterAfterTwoDots == Path.AltDirectorySeparatorChar) - { - throw createException(); - } - } + if (position >= 0) + { + var characterAfterTwoDots = searchPattern[position + 2]; - var invalidPathChars = Path.GetInvalidPathChars(); - if (searchPattern.IndexOfAny(invalidPathChars) > -1) + if (characterAfterTwoDots == Path.DirectorySeparatorChar || characterAfterTwoDots == Path.AltDirectorySeparatorChar) { - throw CommonExceptions.IllegalCharactersInPath(nameof(searchPattern)); + throw createException(); } } - private string ReplaceLastOccurrence(string source, string find, string replace) + var invalidPathChars = Path.GetInvalidPathChars(); + if (searchPattern.IndexOfAny(invalidPathChars) > -1) { - if (source == null) - { - return source; - } + throw CommonExceptions.IllegalCharactersInPath(nameof(searchPattern)); + } + } - var place = source.LastIndexOf(find); + private string ReplaceLastOccurrence(string source, string find, string replace) + { + if (source == null) + { + return source; + } - if (place == -1) - { - return source; - } + var place = source.LastIndexOf(find); - var result = source.Remove(place, find.Length).Insert(place, replace); - return result; + if (place == -1) + { + return source; } + var result = source.Remove(place, find.Length).Insert(place, replace); + return result; + } + #if FEATURE_ENUMERATION_OPTIONS private SearchOption EnumerationOptionsToSearchOption(EnumerationOptions enumerationOptions) { @@ -822,5 +822,4 @@ static Exception CreateExceptionForUnsupportedProperty(string propertyName) : SearchOption.TopDirectoryOnly; } #endif - } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryData.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryData.cs index d3c3d3cdf..77293dd2b 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryData.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryData.cs @@ -1,36 +1,35 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockDirectoryData : MockFileData - { +public class MockDirectoryData : MockFileData +{ #if FEATURE_SERIALIZABLE - [NonSerialized] + [NonSerialized] #endif - private DirectorySecurity accessControl; + private DirectorySecurity accessControl; - /// - public MockDirectoryData() : base(string.Empty) - { - Attributes = FileAttributes.Directory; - } + /// + public MockDirectoryData() : base(string.Empty) + { + Attributes = FileAttributes.Directory; + } - /// - [SupportedOSPlatform("windows")] - public new DirectorySecurity AccessControl + /// + [SupportedOSPlatform("windows")] + public new DirectorySecurity AccessControl + { + get { - get - { - // DirectorySecurity's constructor will throw PlatformNotSupportedException on non-Windows platform, so we initialize it in lazy way. - // This let's us use this class as long as we don't use AccessControl property. - return accessControl ?? (accessControl = new DirectorySecurity()); - } - set { accessControl = value; } + // DirectorySecurity's constructor will throw PlatformNotSupportedException on non-Windows platform, so we initialize it in lazy way. + // This let's us use this class as long as we don't use AccessControl property. + return accessControl ?? (accessControl = new DirectorySecurity()); } + set { accessControl = value; } } } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfo.cs index 690c63ba7..8099ead93 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfo.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfo.cs @@ -3,457 +3,456 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions.TestingHelpers -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers; - /// +using XFS = MockUnixSupport; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockDirectoryInfo : DirectoryInfoBase, IFileSystemAclSupport - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - private string directoryPath; - private string originalPath; - private MockFileData cachedMockFileData; - private bool refreshOnNextRead; - - /// - /// Initializes a new instance of the class. - /// - /// The mock file data accessor. - /// The directory path. - /// Thrown if or is . - public MockDirectoryInfo(IMockFileDataAccessor mockFileDataAccessor, string directoryPath) : base(mockFileDataAccessor?.FileSystem) - { - this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); +public class MockDirectoryInfo : DirectoryInfoBase, IFileSystemAclSupport +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private string directoryPath; + private string originalPath; + private MockFileData cachedMockFileData; + private bool refreshOnNextRead; + + /// + /// Initializes a new instance of the class. + /// + /// The mock file data accessor. + /// The directory path. + /// Thrown if or is . + public MockDirectoryInfo(IMockFileDataAccessor mockFileDataAccessor, string directoryPath) : base(mockFileDataAccessor?.FileSystem) + { + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); - if (directoryPath == null) - { - throw new ArgumentNullException("path", StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); - } - if (directoryPath.Trim() == string.Empty) - { - throw CommonExceptions.PathIsNotOfALegalForm("path"); - } - - SetDirectoryPath(directoryPath); - Refresh(); + if (directoryPath == null) + { + throw new ArgumentNullException("path", StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); } - -#if FEATURE_CREATE_SYMBOLIC_LINK - /// - public override void CreateAsSymbolicLink(string pathToTarget) + if (directoryPath.Trim() == string.Empty) { - FileSystem.Directory.CreateSymbolicLink(FullName, pathToTarget); + throw CommonExceptions.PathIsNotOfALegalForm("path"); } + + SetDirectoryPath(directoryPath); + Refresh(); + } + +#if FEATURE_CREATE_SYMBOLIC_LINK + /// + public override void CreateAsSymbolicLink(string pathToTarget) + { + FileSystem.Directory.CreateSymbolicLink(FullName, pathToTarget); + } #endif - /// - public override void Delete() - { - mockFileDataAccessor.Directory.Delete(directoryPath); - refreshOnNextRead = true; - } + /// + public override void Delete() + { + mockFileDataAccessor.Directory.Delete(directoryPath); + refreshOnNextRead = true; + } - /// - public override void Refresh() - { - var mockFileData = mockFileDataAccessor.GetFile(directoryPath) ?? MockFileData.NullObject; - cachedMockFileData = mockFileData.Clone(); - } + /// + public override void Refresh() + { + var mockFileData = mockFileDataAccessor.GetFile(directoryPath) ?? MockFileData.NullObject; + cachedMockFileData = mockFileData.Clone(); + } #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) - { - return FileSystem.Directory.ResolveLinkTarget(FullName, returnFinalTarget); - } + /// + public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) + { + return FileSystem.Directory.ResolveLinkTarget(FullName, returnFinalTarget); + } #endif - /// - public override FileAttributes Attributes - { - get { return GetMockFileDataForRead().Attributes; } - set { GetMockFileDataForWrite().Attributes = value | FileAttributes.Directory; } - } + /// + public override FileAttributes Attributes + { + get { return GetMockFileDataForRead().Attributes; } + set { GetMockFileDataForWrite().Attributes = value | FileAttributes.Directory; } + } - /// - public override DateTime CreationTime - { - get { return GetMockFileDataForRead().CreationTime.LocalDateTime; } - set { GetMockFileDataForWrite().CreationTime = value; } - } + /// + public override DateTime CreationTime + { + get { return GetMockFileDataForRead().CreationTime.LocalDateTime; } + set { GetMockFileDataForWrite().CreationTime = value; } + } - /// - public override DateTime CreationTimeUtc - { - get { return GetMockFileDataForRead().CreationTime.UtcDateTime; } - set { GetMockFileDataForWrite().CreationTime = value; } - } + /// + public override DateTime CreationTimeUtc + { + get { return GetMockFileDataForRead().CreationTime.UtcDateTime; } + set { GetMockFileDataForWrite().CreationTime = value; } + } - /// - public override bool Exists - { - get { - var mockFileData = GetMockFileDataForRead(); - return (int)mockFileData.Attributes != -1 && mockFileData.IsDirectory; - } + /// + public override bool Exists + { + get { + var mockFileData = GetMockFileDataForRead(); + return (int)mockFileData.Attributes != -1 && mockFileData.IsDirectory; } + } - /// - public override string Extension + /// + public override string Extension + { + get { - get - { - // System.IO.Path.GetExtension does only string manipulation, - // so it's safe to delegate. - return Path.GetExtension(directoryPath); - } + // System.IO.Path.GetExtension does only string manipulation, + // so it's safe to delegate. + return Path.GetExtension(directoryPath); } + } - /// - public override string FullName + /// + public override string FullName + { + get { - get - { - var root = mockFileDataAccessor.Path.GetPathRoot(directoryPath); - - if (mockFileDataAccessor.StringOperations.Equals(directoryPath, root)) - { - // drives have the trailing slash - return directoryPath; - } + var root = mockFileDataAccessor.Path.GetPathRoot(directoryPath); - // directories do not have a trailing slash - return directoryPath.TrimEnd('\\').TrimEnd('/'); + if (mockFileDataAccessor.StringOperations.Equals(directoryPath, root)) + { + // drives have the trailing slash + return directoryPath; } - } - /// - public override DateTime LastAccessTime - { - get { return GetMockFileDataForRead().LastAccessTime.LocalDateTime; } - set { GetMockFileDataForWrite().LastAccessTime = value; } + // directories do not have a trailing slash + return directoryPath.TrimEnd('\\').TrimEnd('/'); } + } - /// - public override DateTime LastAccessTimeUtc - { - get { return GetMockFileDataForRead().LastAccessTime.UtcDateTime; } - set { GetMockFileDataForWrite().LastAccessTime = value; } - } + /// + public override DateTime LastAccessTime + { + get { return GetMockFileDataForRead().LastAccessTime.LocalDateTime; } + set { GetMockFileDataForWrite().LastAccessTime = value; } + } - /// - public override DateTime LastWriteTime - { - get { return GetMockFileDataForRead().LastWriteTime.LocalDateTime; } - set { GetMockFileDataForWrite().LastWriteTime = value; } - } + /// + public override DateTime LastAccessTimeUtc + { + get { return GetMockFileDataForRead().LastAccessTime.UtcDateTime; } + set { GetMockFileDataForWrite().LastAccessTime = value; } + } - /// - public override DateTime LastWriteTimeUtc - { - get { return GetMockFileDataForRead().LastWriteTime.UtcDateTime; } - set { GetMockFileDataForWrite().LastWriteTime = value; } - } + /// + public override DateTime LastWriteTime + { + get { return GetMockFileDataForRead().LastWriteTime.LocalDateTime; } + set { GetMockFileDataForWrite().LastWriteTime = value; } + } + + /// + public override DateTime LastWriteTimeUtc + { + get { return GetMockFileDataForRead().LastWriteTime.UtcDateTime; } + set { GetMockFileDataForWrite().LastWriteTime = value; } + } #if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET - /// - public override string LinkTarget - { - get { return GetMockFileDataForRead().LinkTarget; } - } + /// + public override string LinkTarget + { + get { return GetMockFileDataForRead().LinkTarget; } + } #endif - /// - public override string Name + /// + public override string Name + { + get { - get - { - var mockPath = new MockPath(mockFileDataAccessor); - return string.Equals(mockPath.GetPathRoot(directoryPath), directoryPath) ? directoryPath : mockPath.GetFileName(directoryPath.TrimEnd(mockFileDataAccessor.Path.DirectorySeparatorChar)); - } + var mockPath = new MockPath(mockFileDataAccessor); + return string.Equals(mockPath.GetPathRoot(directoryPath), directoryPath) ? directoryPath : mockPath.GetFileName(directoryPath.TrimEnd(mockFileDataAccessor.Path.DirectorySeparatorChar)); } + } - /// - public override void Create() - { - mockFileDataAccessor.Directory.CreateDirectory(FullName); - refreshOnNextRead = true; - } + /// + public override void Create() + { + mockFileDataAccessor.Directory.CreateDirectory(FullName); + refreshOnNextRead = true; + } - /// - public override IDirectoryInfo CreateSubdirectory(string path) - { - return mockFileDataAccessor.Directory.CreateDirectory(Path.Combine(FullName, path)); - } + /// + public override IDirectoryInfo CreateSubdirectory(string path) + { + return mockFileDataAccessor.Directory.CreateDirectory(Path.Combine(FullName, path)); + } - /// - public override void Delete(bool recursive) - { - mockFileDataAccessor.Directory.Delete(directoryPath, recursive); - refreshOnNextRead = true; - } + /// + public override void Delete(bool recursive) + { + mockFileDataAccessor.Directory.Delete(directoryPath, recursive); + refreshOnNextRead = true; + } - /// - public override IEnumerable EnumerateDirectories() - { - return GetDirectories(); - } + /// + public override IEnumerable EnumerateDirectories() + { + return GetDirectories(); + } - /// - public override IEnumerable EnumerateDirectories(string searchPattern) - { - return GetDirectories(searchPattern); - } + /// + public override IEnumerable EnumerateDirectories(string searchPattern) + { + return GetDirectories(searchPattern); + } - /// - public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) - { - return GetDirectories(searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) + { + return GetDirectories(searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS - /// - public override IEnumerable EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions) - { - return GetDirectories(searchPattern, enumerationOptions); - } + /// + public override IEnumerable EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetDirectories(searchPattern, enumerationOptions); + } #endif - /// - public override IEnumerable EnumerateFiles() - { - return GetFiles(); - } + /// + public override IEnumerable EnumerateFiles() + { + return GetFiles(); + } - /// - public override IEnumerable EnumerateFiles(string searchPattern) - { - return GetFiles(searchPattern); - } + /// + public override IEnumerable EnumerateFiles(string searchPattern) + { + return GetFiles(searchPattern); + } - /// - public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) - { - return GetFiles(searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) + { + return GetFiles(searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS - /// - public override IEnumerable EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions) - { - return GetFiles(searchPattern, enumerationOptions); - } + /// + public override IEnumerable EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetFiles(searchPattern, enumerationOptions); + } #endif - /// - public override IEnumerable EnumerateFileSystemInfos() - { - return GetFileSystemInfos(); - } + /// + public override IEnumerable EnumerateFileSystemInfos() + { + return GetFileSystemInfos(); + } - /// - public override IEnumerable EnumerateFileSystemInfos(string searchPattern) - { - return GetFileSystemInfos(searchPattern); - } + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern) + { + return GetFileSystemInfos(searchPattern); + } - /// - public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return GetFileSystemInfos(searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return GetFileSystemInfos(searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS - /// - public override IEnumerable EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) - { - return GetFileSystemInfos(searchPattern, enumerationOptions); - } + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetFileSystemInfos(searchPattern, enumerationOptions); + } #endif - /// - public override IDirectoryInfo[] GetDirectories() - { - return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath)); - } + /// + public override IDirectoryInfo[] GetDirectories() + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath)); + } - /// - public override IDirectoryInfo[] GetDirectories(string searchPattern) - { - return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern)); - } + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern) + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern)); + } - /// - public override IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) - { - return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern, searchOption)); - } + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern, searchOption)); + } #if FEATURE_ENUMERATION_OPTIONS - /// - public override IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions) - { - return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern, enumerationOptions)); - } + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions) + { + return ConvertStringsToDirectories(mockFileDataAccessor.Directory.GetDirectories(directoryPath, searchPattern, enumerationOptions)); + } #endif - private DirectoryInfoBase[] ConvertStringsToDirectories(IEnumerable paths) - { - return paths - .Select(path => new MockDirectoryInfo(mockFileDataAccessor, path)) - .Cast() - .ToArray(); - } + private DirectoryInfoBase[] ConvertStringsToDirectories(IEnumerable paths) + { + return paths + .Select(path => new MockDirectoryInfo(mockFileDataAccessor, path)) + .Cast() + .ToArray(); + } - /// - public override IFileInfo[] GetFiles() - { - return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName)); - } + /// + public override IFileInfo[] GetFiles() + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName)); + } - /// - public override IFileInfo[] GetFiles(string searchPattern) - { - return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern)); - } + /// + public override IFileInfo[] GetFiles(string searchPattern) + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern)); + } - /// - public override IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption) - { - return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern, searchOption)); - } + /// + public override IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption) + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern, searchOption)); + } #if FEATURE_ENUMERATION_OPTIONS - /// - public override IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions) - { - return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern, enumerationOptions)); - } + /// + public override IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions) + { + return ConvertStringsToFiles(mockFileDataAccessor.Directory.GetFiles(FullName, searchPattern, enumerationOptions)); + } #endif - IFileInfo[] ConvertStringsToFiles(IEnumerable paths) - { - return paths - .Select(mockFileDataAccessor.FileInfo.New) - .ToArray(); - } + IFileInfo[] ConvertStringsToFiles(IEnumerable paths) + { + return paths + .Select(mockFileDataAccessor.FileInfo.New) + .ToArray(); + } - /// - public override IFileSystemInfo[] GetFileSystemInfos() - { - return GetFileSystemInfos("*"); - } + /// + public override IFileSystemInfo[] GetFileSystemInfos() + { + return GetFileSystemInfos("*"); + } - /// - public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern) - { - return GetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); - } + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern) + { + return GetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); + } - /// - public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return GetDirectories(searchPattern, searchOption).OfType().Concat(GetFiles(searchPattern, searchOption)).ToArray(); - } + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return GetDirectories(searchPattern, searchOption).OfType().Concat(GetFiles(searchPattern, searchOption)).ToArray(); + } #if FEATURE_ENUMERATION_OPTIONS - /// - public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) - { - return GetDirectories(searchPattern, enumerationOptions).OfType().Concat(GetFiles(searchPattern, enumerationOptions)).ToArray(); - } + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) + { + return GetDirectories(searchPattern, enumerationOptions).OfType().Concat(GetFiles(searchPattern, enumerationOptions)).ToArray(); + } #endif - /// - public override void MoveTo(string destDirName) - { - mockFileDataAccessor.Directory.Move(directoryPath, destDirName); - SetDirectoryPath(destDirName); - } + /// + public override void MoveTo(string destDirName) + { + mockFileDataAccessor.Directory.Move(directoryPath, destDirName); + SetDirectoryPath(destDirName); + } - /// - public override IDirectoryInfo Parent + /// + public override IDirectoryInfo Parent + { + get { - get - { - return mockFileDataAccessor.Directory.GetParent(directoryPath); - } + return mockFileDataAccessor.Directory.GetParent(directoryPath); } + } - /// - public override IDirectoryInfo Root + /// + public override IDirectoryInfo Root + { + get { - get - { - return new MockDirectoryInfo(mockFileDataAccessor, mockFileDataAccessor.Directory.GetDirectoryRoot(FullName)); - } + return new MockDirectoryInfo(mockFileDataAccessor, mockFileDataAccessor.Directory.GetDirectoryRoot(FullName)); } + } - private MockFileData GetMockFileDataForRead() + private MockFileData GetMockFileDataForRead() + { + if (refreshOnNextRead) { - if (refreshOnNextRead) - { - Refresh(); - refreshOnNextRead = false; - } - return cachedMockFileData; + Refresh(); + refreshOnNextRead = false; } + return cachedMockFileData; + } - private MockFileData GetMockFileDataForWrite() - { - refreshOnNextRead = true; - return mockFileDataAccessor.GetFile(directoryPath) - ?? throw CommonExceptions.CouldNotFindPartOfPath(directoryPath); - } + private MockFileData GetMockFileDataForWrite() + { + refreshOnNextRead = true; + return mockFileDataAccessor.GetFile(directoryPath) + ?? throw CommonExceptions.CouldNotFindPartOfPath(directoryPath); + } - /// - public override string ToString() - { - return originalPath; - } + /// + public override string ToString() + { + return originalPath; + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl() - { - return GetMockDirectoryData().AccessControl; - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return GetMockDirectoryData().AccessControl; + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) - { - return GetMockDirectoryData().AccessControl; - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return GetMockDirectoryData().AccessControl; + } - /// - [SupportedOSPlatform("windows")] - public void SetAccessControl(object value) - { - GetMockDirectoryData().AccessControl = value as DirectorySecurity; - } + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + GetMockDirectoryData().AccessControl = value as DirectorySecurity; + } - private void SetDirectoryPath(string path) - { - originalPath = path; - path = mockFileDataAccessor.Path.GetFullPath(path); - - path = path.TrimSlashes(); - if (XFS.IsWindowsPlatform()) - { - path = path.TrimEnd(' '); - } - this.directoryPath = path; - } + private void SetDirectoryPath(string path) + { + originalPath = path; + path = mockFileDataAccessor.Path.GetFullPath(path); - private MockDirectoryData GetMockDirectoryData() + path = path.TrimSlashes(); + if (XFS.IsWindowsPlatform()) { - return mockFileDataAccessor.GetFile(directoryPath) as MockDirectoryData - ?? throw CommonExceptions.CouldNotFindPartOfPath(directoryPath); + path = path.TrimEnd(' '); } + this.directoryPath = path; + } + + private MockDirectoryData GetMockDirectoryData() + { + return mockFileDataAccessor.GetFile(directoryPath) as MockDirectoryData + ?? throw CommonExceptions.CouldNotFindPartOfPath(directoryPath); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfoFactory.cs index f73697b43..0c025098b 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDirectoryInfoFactory.cs @@ -1,38 +1,37 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockDirectoryInfoFactory : IDirectoryInfoFactory +public class MockDirectoryInfoFactory : IDirectoryInfoFactory +{ + readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockDirectoryInfoFactory(IMockFileDataAccessor mockFileSystem) { - readonly IMockFileDataAccessor mockFileSystem; + this.mockFileSystem = mockFileSystem; + } - /// - public MockDirectoryInfoFactory(IMockFileDataAccessor mockFileSystem) - { - this.mockFileSystem = mockFileSystem; - } + /// + public IFileSystem FileSystem + => mockFileSystem; - /// - public IFileSystem FileSystem - => mockFileSystem; + /// + public IDirectoryInfo New(string path) + { + return new MockDirectoryInfo(mockFileSystem, path); + } - /// - public IDirectoryInfo New(string path) + /// + public IDirectoryInfo Wrap(DirectoryInfo directoryInfo) + { + if (directoryInfo == null) { - return new MockDirectoryInfo(mockFileSystem, path); + return null; } - /// - public IDirectoryInfo Wrap(DirectoryInfo directoryInfo) - { - if (directoryInfo == null) - { - return null; - } - - return new MockDirectoryInfo(mockFileSystem, directoryInfo.FullName); - } + return new MockDirectoryInfo(mockFileSystem, directoryInfo.FullName); } } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveData.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveData.cs index 9d3dc169e..0ae4d7e65 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveData.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveData.cs @@ -1,76 +1,75 @@  -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// The class represents the associated data of a drive. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockDriveData { /// - /// The class represents the associated data of a drive. + /// Initializes a new instance of the class. /// -#if FEATURE_SERIALIZABLE - [Serializable] -#endif - public class MockDriveData + public MockDriveData() { - /// - /// Initializes a new instance of the class. - /// - public MockDriveData() - { - IsReady = true; - } + IsReady = true; + } - /// - /// Initializes a new instance of the class by copying the given . - /// - /// The template instance. - /// Thrown if is . - public MockDriveData(MockDriveData template) + /// + /// Initializes a new instance of the class by copying the given . + /// + /// The template instance. + /// Thrown if is . + public MockDriveData(MockDriveData template) + { + if (template == null) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } - - AvailableFreeSpace = template.AvailableFreeSpace; - DriveFormat = template.DriveFormat; - DriveType = template.DriveType; - IsReady = template.IsReady; - TotalFreeSpace = template.TotalFreeSpace; - TotalSize = template.TotalSize; - VolumeLabel = template.VolumeLabel; + throw new ArgumentNullException(nameof(template)); } - /// - /// Gets or sets the amount of available free space of the , in bytes. - /// - public long AvailableFreeSpace { get; set; } + AvailableFreeSpace = template.AvailableFreeSpace; + DriveFormat = template.DriveFormat; + DriveType = template.DriveType; + IsReady = template.IsReady; + TotalFreeSpace = template.TotalFreeSpace; + TotalSize = template.TotalSize; + VolumeLabel = template.VolumeLabel; + } - /// - /// Gets or sets the name of the file system of the , such as NTFS or FAT32. - /// - public string DriveFormat { get; set; } + /// + /// Gets or sets the amount of available free space of the , in bytes. + /// + public long AvailableFreeSpace { get; set; } - /// - /// Gets or sets the drive type of the , such as CD-ROM, removable, network, or fixed. - /// - public DriveType DriveType { get; set; } + /// + /// Gets or sets the name of the file system of the , such as NTFS or FAT32. + /// + public string DriveFormat { get; set; } - /// - /// Gets or sets the value that indicates whether the is ready. - /// - public bool IsReady { get; set; } + /// + /// Gets or sets the drive type of the , such as CD-ROM, removable, network, or fixed. + /// + public DriveType DriveType { get; set; } + + /// + /// Gets or sets the value that indicates whether the is ready. + /// + public bool IsReady { get; set; } - /// - /// Gets or sets the total amount of free space available on the , in bytes. - /// - public long TotalFreeSpace { get; set; } + /// + /// Gets or sets the total amount of free space available on the , in bytes. + /// + public long TotalFreeSpace { get; set; } - /// - /// Gets or sets the total size of storage space on the , in bytes. - /// - public long TotalSize { get; set; } + /// + /// Gets or sets the total size of storage space on the , in bytes. + /// + public long TotalSize { get; set; } - /// - /// Gets or sets the volume label of the . - /// - public string VolumeLabel { get; set; } - } -} + /// + /// Gets or sets the volume label of the . + /// + public string VolumeLabel { get; set; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfo.cs index fcacd5472..c6d85c787 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfo.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfo.cs @@ -1,121 +1,120 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockDriveInfo : DriveInfoBase +public class MockDriveInfo : DriveInfoBase +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private readonly string name; + + /// + public MockDriveInfo(IMockFileDataAccessor mockFileDataAccessor, string name) : base(mockFileDataAccessor?.FileSystem) { - private readonly IMockFileDataAccessor mockFileDataAccessor; - private readonly string name; + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + this.name = mockFileDataAccessor.PathVerifier.NormalizeDriveName(name); + } - /// - public MockDriveInfo(IMockFileDataAccessor mockFileDataAccessor, string name) : base(mockFileDataAccessor?.FileSystem) + /// + public override long AvailableFreeSpace + { + get { - this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); - this.name = mockFileDataAccessor.PathVerifier.NormalizeDriveName(name); + var mockDriveData = GetMockDriveData(); + return mockDriveData.AvailableFreeSpace; } + } - /// - public override long AvailableFreeSpace + /// + public override string DriveFormat + { + get { - get - { - var mockDriveData = GetMockDriveData(); - return mockDriveData.AvailableFreeSpace; - } + var mockDriveData = GetMockDriveData(); + return mockDriveData.DriveFormat; } + } - /// - public override string DriveFormat + /// + public override DriveType DriveType + { + get { - get - { - var mockDriveData = GetMockDriveData(); - return mockDriveData.DriveFormat; - } + var mockDriveData = GetMockDriveData(); + return mockDriveData.DriveType; } + } - /// - public override DriveType DriveType + /// + public override bool IsReady + { + get { - get - { - var mockDriveData = GetMockDriveData(); - return mockDriveData.DriveType; - } + var mockDriveData = GetMockDriveData(); + return mockDriveData.IsReady; } + } - /// - public override bool IsReady - { - get - { - var mockDriveData = GetMockDriveData(); - return mockDriveData.IsReady; - } - } + /// + public override string Name + { + get { return name; } + } - /// - public override string Name + /// + public override IDirectoryInfo RootDirectory + { + get { - get { return name; } + return mockFileDataAccessor.DirectoryInfo.New(Name); } + } - /// - public override IDirectoryInfo RootDirectory + /// + public override long TotalFreeSpace + { + get { - get - { - return mockFileDataAccessor.DirectoryInfo.New(Name); - } + var mockDriveData = GetMockDriveData(); + return mockDriveData.TotalFreeSpace; } + } - /// - public override long TotalFreeSpace + /// + public override long TotalSize + { + get { - get - { - var mockDriveData = GetMockDriveData(); - return mockDriveData.TotalFreeSpace; - } + var mockDriveData = GetMockDriveData(); + return mockDriveData.TotalSize; } + } - /// - public override long TotalSize + /// + public override string VolumeLabel + { + get { - get - { - var mockDriveData = GetMockDriveData(); - return mockDriveData.TotalSize; - } + var mockDriveData = GetMockDriveData(); + return mockDriveData.VolumeLabel; } - - /// - public override string VolumeLabel + set { - get - { - var mockDriveData = GetMockDriveData(); - return mockDriveData.VolumeLabel; - } - set - { - var mockDriveData = GetMockDriveData(); - mockDriveData.VolumeLabel = value; - } + var mockDriveData = GetMockDriveData(); + mockDriveData.VolumeLabel = value; } + } - /// - public override string ToString() - { - return Name; - } + /// + public override string ToString() + { + return Name; + } - private MockDriveData GetMockDriveData() - { - return mockFileDataAccessor.GetDrive(name) - ?? throw CommonExceptions.FileNotFound(name); - } + private MockDriveData GetMockDriveData() + { + return mockFileDataAccessor.GetDrive(name) + ?? throw CommonExceptions.FileNotFound(name); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfoFactory.cs index 11aa610ff..488862df2 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockDriveInfoFactory.cs @@ -1,103 +1,102 @@ using System.Collections.Generic; -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockDriveInfoFactory : IDriveInfoFactory - { - private readonly IMockFileDataAccessor mockFileSystem; +public class MockDriveInfoFactory : IDriveInfoFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; - /// - public MockDriveInfoFactory(IMockFileDataAccessor mockFileSystem) - { - this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); - } + /// + public MockDriveInfoFactory(IMockFileDataAccessor mockFileSystem) + { + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } - /// - public IFileSystem FileSystem - => mockFileSystem; + /// + public IFileSystem FileSystem + => mockFileSystem; - /// - public IDriveInfo[] GetDrives() + /// + public IDriveInfo[] GetDrives() + { + var result = new List(); + foreach (string driveLetter in mockFileSystem.AllDrives) { - var result = new List(); - foreach (string driveLetter in mockFileSystem.AllDrives) + try { - try - { - var mockDriveInfo = new MockDriveInfo(mockFileSystem, driveLetter); - result.Add(mockDriveInfo); - } - catch (ArgumentException) - { - // invalid drives should be ignored - } + var mockDriveInfo = new MockDriveInfo(mockFileSystem, driveLetter); + result.Add(mockDriveInfo); + } + catch (ArgumentException) + { + // invalid drives should be ignored } - - return result.ToArray(); } - /// - public IDriveInfo New(string driveName) - { - var drive = mockFileSystem.Path.GetPathRoot(driveName); + return result.ToArray(); + } - return new MockDriveInfo(mockFileSystem, drive); - } + /// + public IDriveInfo New(string driveName) + { + var drive = mockFileSystem.Path.GetPathRoot(driveName); - /// - public IDriveInfo Wrap(DriveInfo driveInfo) + return new MockDriveInfo(mockFileSystem, drive); + } + + /// + public IDriveInfo Wrap(DriveInfo driveInfo) + { + if (driveInfo == null) { - if (driveInfo == null) - { - return null; - } + return null; + } - return New(driveInfo.Name); + return New(driveInfo.Name); + } + + private string NormalizeDriveName(string driveName) + { + if (driveName.Length == 3 && mockFileSystem.StringOperations.EndsWith(driveName, @":\")) + { + return mockFileSystem.StringOperations.ToUpper(driveName[0]) + @":\"; } - private string NormalizeDriveName(string driveName) + if (mockFileSystem.StringOperations.StartsWith(driveName, @"\\")) { - if (driveName.Length == 3 && mockFileSystem.StringOperations.EndsWith(driveName, @":\")) - { - return mockFileSystem.StringOperations.ToUpper(driveName[0]) + @":\"; - } + return null; + } - if (mockFileSystem.StringOperations.StartsWith(driveName, @"\\")) - { - return null; - } + return driveName; + } - return driveName; - } + private class DriveEqualityComparer : IEqualityComparer + { + private readonly IMockFileDataAccessor mockFileSystem; - private class DriveEqualityComparer : IEqualityComparer + public DriveEqualityComparer(IMockFileDataAccessor mockFileSystem) { - private readonly IMockFileDataAccessor mockFileSystem; - - public DriveEqualityComparer(IMockFileDataAccessor mockFileSystem) - { - this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); - } + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } - public bool Equals(string x, string y) - { - return ReferenceEquals(x, y) || - (HasDrivePrefix(x) && HasDrivePrefix(y) && mockFileSystem.StringOperations.Equals(x[0], y[0])); - } + public bool Equals(string x, string y) + { + return ReferenceEquals(x, y) || + (HasDrivePrefix(x) && HasDrivePrefix(y) && mockFileSystem.StringOperations.Equals(x[0], y[0])); + } - private static bool HasDrivePrefix(string x) - { - return x != null && x.Length >= 2 && x[1] == ':'; - } + private static bool HasDrivePrefix(string x) + { + return x != null && x.Length >= 2 && x[1] == ':'; + } - public int GetHashCode(string obj) - { - return mockFileSystem.StringOperations.ToUpper(obj).GetHashCode(); - } + public int GetHashCode(string obj) + { + return mockFileSystem.StringOperations.ToUpper(obj).GetHashCode(); } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs index 3f025bd34..839b96e1d 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFile.cs @@ -4,23 +4,23 @@ using System.Text; using Microsoft.Win32.SafeHandles; -namespace System.IO.Abstractions.TestingHelpers -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers; - /// +using XFS = MockUnixSupport; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public partial class MockFile : FileBase - { - private readonly IMockFileDataAccessor mockFileDataAccessor; +public partial class MockFile : FileBase +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; - /// - public MockFile(IMockFileDataAccessor mockFileDataAccessor) : base(mockFileDataAccessor?.FileSystem) - { - this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); - } + /// + public MockFile(IMockFileDataAccessor mockFileDataAccessor) : base(mockFileDataAccessor?.FileSystem) + { + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + } #if FEATURE_FILE_SPAN /// @@ -49,53 +49,53 @@ public override void AppendAllBytes(string path, ReadOnlySpan bytes) } #endif - /// - public override void AppendAllLines(string path, IEnumerable contents) - { - AppendAllLines(path, contents, MockFileData.DefaultEncoding); - } + /// + public override void AppendAllLines(string path, IEnumerable contents) + { + AppendAllLines(path, contents, MockFileData.DefaultEncoding); + } - /// - public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, nameof(contents)); - VerifyValueIsNotNull(encoding, nameof(encoding)); + /// + public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, nameof(contents)); + VerifyValueIsNotNull(encoding, nameof(encoding)); - var concatContents = contents.Aggregate("", (a, b) => a + b + Environment.NewLine); - AppendAllText(path, concatContents, encoding); - } + var concatContents = contents.Aggregate("", (a, b) => a + b + Environment.NewLine); + AppendAllText(path, concatContents, encoding); + } - /// - public override void AppendAllText(string path, string contents) + /// + public override void AppendAllText(string path, string contents) + { + AppendAllText(path, contents, MockFileData.DefaultEncoding); + } + + /// + public override void AppendAllText(string path, string contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (encoding == null) { - AppendAllText(path, contents, MockFileData.DefaultEncoding); + throw new ArgumentNullException(nameof(encoding)); } - /// - public override void AppendAllText(string path, string contents, Encoding encoding) + if (!mockFileDataAccessor.FileExists(path)) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } - - if (!mockFileDataAccessor.FileExists(path)) - { - VerifyDirectoryExists(path); - mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(contents, encoding), TimeAdjustments.All)); - } - else - { - var file = mockFileDataAccessor.GetFile(path); - file.CheckFileAccess(path, FileAccess.Write); - mockFileDataAccessor.AdjustTimes(file, TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); - var bytesToAppend = encoding.GetBytes(contents); - file.Contents = file.Contents.Concat(bytesToAppend).ToArray(); - } + VerifyDirectoryExists(path); + mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(contents, encoding), TimeAdjustments.All)); + } + else + { + var file = mockFileDataAccessor.GetFile(path); + file.CheckFileAccess(path, FileAccess.Write); + mockFileDataAccessor.AdjustTimes(file, TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + var bytesToAppend = encoding.GetBytes(contents); + file.Contents = file.Contents.Concat(bytesToAppend).ToArray(); } + } #if FEATURE_FILE_SPAN /// @@ -111,95 +111,95 @@ public override void AppendAllText(string path, ReadOnlySpan contents, Enc } #endif - /// - public override StreamWriter AppendText(string path) + /// + public override StreamWriter AppendText(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + if (mockFileDataAccessor.FileExists(path)) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + StreamWriter sw = new StreamWriter(OpenWrite(path)); + sw.BaseStream.Seek(0, SeekOrigin.End); //push the stream pointer at the end for append. + return sw; + } - if (mockFileDataAccessor.FileExists(path)) - { - StreamWriter sw = new StreamWriter(OpenWrite(path)); - sw.BaseStream.Seek(0, SeekOrigin.End); //push the stream pointer at the end for append. - return sw; - } + return new StreamWriter(Create(path)); + } - return new StreamWriter(Create(path)); - } + /// + public override void Copy(string sourceFileName, string destFileName) + { + Copy(sourceFileName, destFileName, false); + } - /// - public override void Copy(string sourceFileName, string destFileName) + /// + public override void Copy(string sourceFileName, string destFileName, bool overwrite) + { + if (sourceFileName == null) { - Copy(sourceFileName, destFileName, false); + throw CommonExceptions.FilenameCannotBeNull(nameof(sourceFileName)); } - /// - public override void Copy(string sourceFileName, string destFileName, bool overwrite) + if (destFileName == null) { - if (sourceFileName == null) - { - throw CommonExceptions.FilenameCannotBeNull(nameof(sourceFileName)); - } - - if (destFileName == null) - { - throw CommonExceptions.FilenameCannotBeNull(nameof(destFileName)); - } + throw CommonExceptions.FilenameCannotBeNull(nameof(destFileName)); + } - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName)); - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName)); - if (!Exists(sourceFileName)) - { - throw CommonExceptions.FileNotFound(sourceFileName); - } + if (!Exists(sourceFileName)) + { + throw CommonExceptions.FileNotFound(sourceFileName); + } - VerifyDirectoryExists(destFileName); + VerifyDirectoryExists(destFileName); - var fileExists = mockFileDataAccessor.FileExists(destFileName); - if (fileExists) + var fileExists = mockFileDataAccessor.FileExists(destFileName); + if (fileExists) + { + if (!overwrite) { - if (!overwrite) - { - throw CommonExceptions.FileAlreadyExists(destFileName); - } - - mockFileDataAccessor.RemoveFile(destFileName); + throw CommonExceptions.FileAlreadyExists(destFileName); } - var sourceFileData = mockFileDataAccessor.GetFile(sourceFileName); - sourceFileData.CheckFileAccess(sourceFileName, FileAccess.Read); - var destFileData = new MockFileData(sourceFileData); - mockFileDataAccessor.AdjustTimes(destFileData, TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime); - mockFileDataAccessor.AddFile(destFileName, destFileData); + mockFileDataAccessor.RemoveFile(destFileName); } - /// - public override FileSystemStream Create(string path) => - Create(path, 4096); + var sourceFileData = mockFileDataAccessor.GetFile(sourceFileName); + sourceFileData.CheckFileAccess(sourceFileName, FileAccess.Read); + var destFileData = new MockFileData(sourceFileData); + mockFileDataAccessor.AdjustTimes(destFileData, TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime); + mockFileDataAccessor.AddFile(destFileName, destFileData); + } - /// - public override FileSystemStream Create(string path, int bufferSize) => - Create(path, bufferSize, FileOptions.None); + /// + public override FileSystemStream Create(string path) => + Create(path, 4096); - /// - public override FileSystemStream Create(string path, int bufferSize, FileOptions options) => - CreateInternal(path, FileAccess.ReadWrite, options); + /// + public override FileSystemStream Create(string path, int bufferSize) => + Create(path, bufferSize, FileOptions.None); + + /// + public override FileSystemStream Create(string path, int bufferSize, FileOptions options) => + CreateInternal(path, FileAccess.ReadWrite, options); - private FileSystemStream CreateInternal(string path, FileAccess access, FileOptions options) + private FileSystemStream CreateInternal(string path, FileAccess access, FileOptions options) + { + if (path == null) { - if (path == null) - { - throw new ArgumentNullException(nameof(path), "Path cannot be null."); - } + throw new ArgumentNullException(nameof(path), "Path cannot be null."); + } - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); - VerifyDirectoryExists(path); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); + VerifyDirectoryExists(path); - var mockFileData = new MockFileData(new byte[0]); - mockFileDataAccessor.AdjustTimes(mockFileData, TimeAdjustments.All); - mockFileDataAccessor.AddFile(path, mockFileData); - return OpenInternal(path, FileMode.Open, access, options); - } + var mockFileData = new MockFileData(new byte[0]); + mockFileDataAccessor.AdjustTimes(mockFileData, TimeAdjustments.All); + mockFileDataAccessor.AddFile(path, mockFileData); + return OpenInternal(path, FileMode.Open, access, options); + } #if FEATURE_CREATE_SYMBOLIC_LINK /// @@ -243,125 +243,125 @@ public override IFileSystemInfo CreateSymbolicLink(string path, string pathToTar return mockFileInfo; } #endif - /// - public override StreamWriter CreateText(string path) + /// + public override StreamWriter CreateText(string path) + { + return new StreamWriter(Create(path)); + } + + /// + public override void Decrypt(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + new MockFileInfo(mockFileDataAccessor, path).Decrypt(); + } + /// + public override void Delete(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + + // We mimic exact behavior of the standard File.Delete() method + // which throws exception only if the folder does not exist, + // but silently returns if deleting a non-existing file in an existing folder. + VerifyDirectoryExists(path); + + var file = mockFileDataAccessor.GetFile(path); + if (file != null && !file.AllowedFileShare.HasFlag(FileShare.Delete)) { - return new StreamWriter(Create(path)); + throw CommonExceptions.ProcessCannotAccessFileInUse(path); } - /// - public override void Decrypt(string path) + if (file != null && file.IsDirectory) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - new MockFileInfo(mockFileDataAccessor, path).Decrypt(); + throw new UnauthorizedAccessException($"Access to the path '{path}' is denied."); } - /// - public override void Delete(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - // We mimic exact behavior of the standard File.Delete() method - // which throws exception only if the folder does not exist, - // but silently returns if deleting a non-existing file in an existing folder. - VerifyDirectoryExists(path); + mockFileDataAccessor.RemoveFile(path); + } - var file = mockFileDataAccessor.GetFile(path); - if (file != null && !file.AllowedFileShare.HasFlag(FileShare.Delete)) - { - throw CommonExceptions.ProcessCannotAccessFileInUse(path); - } + /// + public override void Encrypt(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - if (file != null && file.IsDirectory) - { - throw new UnauthorizedAccessException($"Access to the path '{path}' is denied."); - } + new MockFileInfo(mockFileDataAccessor, path).Encrypt(); + } - mockFileDataAccessor.RemoveFile(path); + /// + public override bool Exists(string path) + { + if (path == null) + { + return false; } - /// - public override void Encrypt(string path) + if (path.Trim() == string.Empty) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - new MockFileInfo(mockFileDataAccessor, path).Encrypt(); + return false; } - /// - public override bool Exists(string path) + //Not handling exceptions here so that mock behaviour is as similar as possible to System.IO.File.Exists (See #810) + try { - if (path == null) - { - return false; - } - - if (path.Trim() == string.Empty) - { - return false; - } + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); - //Not handling exceptions here so that mock behaviour is as similar as possible to System.IO.File.Exists (See #810) - try - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, nameof(path)); + var file = mockFileDataAccessor.GetFile(path); + return file != null && !file.IsDirectory; + } + catch (ArgumentException) { } + catch (NotSupportedException) { } + catch (IOException) { } + catch (UnauthorizedAccessException) { } - var file = mockFileDataAccessor.GetFile(path); - return file != null && !file.IsDirectory; - } - catch (ArgumentException) { } - catch (NotSupportedException) { } - catch (IOException) { } - catch (UnauthorizedAccessException) { } + return false; + } - return false; + /// + /// Gets the of the file on the path. + /// + /// The path to the file. + /// The of the file on the path. + /// is empty, contains only white spaces, or contains invalid characters. + /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// is in an invalid format. + /// represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found. + /// represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found. + /// This file is being used by another process. + /// The caller does not have the required permission. + public override FileAttributes GetAttributes(string path) + { + if (path != null && path.Length == 0) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); } - /// - /// Gets the of the file on the path. - /// - /// The path to the file. - /// The of the file on the path. - /// is empty, contains only white spaces, or contains invalid characters. - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// is in an invalid format. - /// represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found. - /// represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found. - /// This file is being used by another process. - /// The caller does not have the required permission. - public override FileAttributes GetAttributes(string path) - { - if (path != null && path.Length == 0) - { - throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); - } - - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - var possibleFileData = mockFileDataAccessor.GetFile(path); - FileAttributes result; - if (possibleFileData != null) + var possibleFileData = mockFileDataAccessor.GetFile(path); + FileAttributes result; + if (possibleFileData != null) + { + result = possibleFileData.Attributes; + } + else + { + var directoryInfo = mockFileDataAccessor.DirectoryInfo.New(path); + if (directoryInfo.Exists) { - result = possibleFileData.Attributes; + result = directoryInfo.Attributes; } else { - var directoryInfo = mockFileDataAccessor.DirectoryInfo.New(path); - if (directoryInfo.Exists) - { - result = directoryInfo.Attributes; - } - else - { - VerifyDirectoryExists(path); + VerifyDirectoryExists(path); - throw CommonExceptions.FileNotFound(path); - } + throw CommonExceptions.FileNotFound(path); } - - return result; } + return result; + } + #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public override FileAttributes GetAttributes(SafeFileHandle fileHandle) @@ -370,13 +370,13 @@ public override FileAttributes GetAttributes(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetCreationTime(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override DateTime GetCreationTime(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return GetTimeFromFile(path, data => data.CreationTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + return GetTimeFromFile(path, data => data.CreationTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -386,13 +386,13 @@ public override DateTime GetCreationTime(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetCreationTimeUtc(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override DateTime GetCreationTimeUtc(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return GetTimeFromFile(path, data => data.CreationTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + return GetTimeFromFile(path, data => data.CreationTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -402,13 +402,13 @@ public override DateTime GetCreationTimeUtc(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastAccessTime(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override DateTime GetLastAccessTime(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return GetTimeFromFile(path, data => data.LastAccessTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + return GetTimeFromFile(path, data => data.LastAccessTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -418,13 +418,13 @@ public override DateTime GetLastAccessTime(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastAccessTimeUtc(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return GetTimeFromFile(path, data => data.LastAccessTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + return GetTimeFromFile(path, data => data.LastAccessTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -434,13 +434,13 @@ public override DateTime GetLastAccessTimeUtc(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastWriteTime(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override DateTime GetLastWriteTime(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return GetTimeFromFile(path, data => data.LastWriteTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + return GetTimeFromFile(path, data => data.LastWriteTime.LocalDateTime, () => MockFileData.DefaultDateTimeOffset.LocalDateTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -450,13 +450,13 @@ public override DateTime GetLastWriteTime(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastWriteTimeUtc(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return GetTimeFromFile(path, data => data.LastWriteTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + return GetTimeFromFile(path, data => data.LastWriteTime.UtcDateTime, () => MockFileData.DefaultDateTimeOffset.UtcDateTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -490,24 +490,69 @@ public override UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle) } #endif - private DateTime GetTimeFromFile(string path, Func existingFileFunction, Func nonExistingFileFunction) + private DateTime GetTimeFromFile(string path, Func existingFileFunction, Func nonExistingFileFunction) + { + DateTime result; + MockFileData file = mockFileDataAccessor.GetFile(path); + if (file != null) + { + result = existingFileFunction(file); + } + else + { + result = nonExistingFileFunction(); + } + + return result; + } + + /// + public override void Move(string sourceFileName, string destFileName) + { + if (sourceFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(sourceFileName)); + } + + if (destFileName == null) + { + throw CommonExceptions.FilenameCannotBeNull(nameof(destFileName)); + } + + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName)); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName)); + + if (mockFileDataAccessor.GetFile(destFileName) != null) { - DateTime result; - MockFileData file = mockFileDataAccessor.GetFile(path); - if (file != null) + if (mockFileDataAccessor.StringOperations.Equals(destFileName, sourceFileName)) { - result = existingFileFunction(file); + return; } else { - result = nonExistingFileFunction(); + throw new IOException("A file can not be created if it already exists."); } + } + + var sourceFile = mockFileDataAccessor.GetFile(sourceFileName); - return result; + if (sourceFile == null) + { + throw CommonExceptions.FileNotFound(sourceFileName); + } + if (!sourceFile.AllowedFileShare.HasFlag(FileShare.Delete)) + { + throw CommonExceptions.ProcessCannotAccessFileInUse(); } + VerifyDirectoryExists(destFileName); + + mockFileDataAccessor.RemoveFile(sourceFileName); + mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime)); + } +#if FEATURE_FILE_MOVE_WITH_OVERWRITE /// - public override void Move(string sourceFileName, string destFileName) + public override void Move(string sourceFileName, string destFileName, bool overwrite) { if (sourceFileName == null) { @@ -524,16 +569,17 @@ public override void Move(string sourceFileName, string destFileName) if (mockFileDataAccessor.GetFile(destFileName) != null) { - if (mockFileDataAccessor.StringOperations.Equals(destFileName, sourceFileName)) + if (destFileName.Equals(sourceFileName)) { return; } - else + else if (!overwrite) { throw new IOException("A file can not be created if it already exists."); } } + var sourceFile = mockFileDataAccessor.GetFile(sourceFileName); if (sourceFile == null) @@ -545,292 +591,246 @@ public override void Move(string sourceFileName, string destFileName) throw CommonExceptions.ProcessCannotAccessFileInUse(); } VerifyDirectoryExists(destFileName); - + mockFileDataAccessor.RemoveFile(sourceFileName); mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime)); } +#endif -#if FEATURE_FILE_MOVE_WITH_OVERWRITE - /// - public override void Move(string sourceFileName, string destFileName, bool overwrite) - { - if (sourceFileName == null) - { - throw CommonExceptions.FilenameCannotBeNull(nameof(sourceFileName)); - } - - if (destFileName == null) - { - throw CommonExceptions.FilenameCannotBeNull(nameof(destFileName)); - } + /// + public override FileSystemStream Open(string path, FileMode mode) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(sourceFileName, nameof(sourceFileName)); - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(destFileName, nameof(destFileName)); + return Open(path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None); + } - if (mockFileDataAccessor.GetFile(destFileName) != null) - { - if (destFileName.Equals(sourceFileName)) - { - return; - } - else if (!overwrite) - { - throw new IOException("A file can not be created if it already exists."); - } - } + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + return Open(path, mode, access, FileShare.None); + } - var sourceFile = mockFileDataAccessor.GetFile(sourceFileName); + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share) => + OpenInternal(path, mode, access, FileOptions.None); - if (sourceFile == null) - { - throw CommonExceptions.FileNotFound(sourceFileName); - } - if (!sourceFile.AllowedFileShare.HasFlag(FileShare.Delete)) - { - throw CommonExceptions.ProcessCannotAccessFileInUse(); - } - VerifyDirectoryExists(destFileName); - - mockFileDataAccessor.RemoveFile(sourceFileName); - mockFileDataAccessor.AddFile(destFileName, mockFileDataAccessor.AdjustTimes(new MockFileData(sourceFile), TimeAdjustments.LastAccessTime)); +#if FEATURE_FILESTREAM_OPTIONS + /// + public override FileSystemStream Open(string path, FileStreamOptions options) + { + return OpenInternal(path, options.Mode, options.Access, options.Options); } #endif - /// - public override FileSystemStream Open(string path, FileMode mode) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + private FileSystemStream OpenInternal( + string path, + FileMode mode, + FileAccess access, + FileOptions options) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return Open(path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None); - } + bool exists = mockFileDataAccessor.FileExists(path); - /// - public override FileSystemStream Open(string path, FileMode mode, FileAccess access) + if (mode == FileMode.CreateNew && exists) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return Open(path, mode, access, FileShare.None); + throw CommonExceptions.FileAlreadyExists(path); } - /// - public override FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share) => - OpenInternal(path, mode, access, FileOptions.None); + if ((mode == FileMode.Open || mode == FileMode.Truncate) && !exists) + { + throw CommonExceptions.FileNotFound(path); + } -#if FEATURE_FILESTREAM_OPTIONS - /// - public override FileSystemStream Open(string path, FileStreamOptions options) + if (!exists || mode == FileMode.CreateNew) { - return OpenInternal(path, options.Mode, options.Access, options.Options); + return CreateInternal(path, access, options); } -#endif - private FileSystemStream OpenInternal( - string path, - FileMode mode, - FileAccess access, - FileOptions options) + if (mode == FileMode.Create || mode == FileMode.Truncate) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + Delete(path); + return CreateInternal(path, access, options); + } - bool exists = mockFileDataAccessor.FileExists(path); + var mockFileData = mockFileDataAccessor.GetFile(path); + mockFileData.CheckFileAccess(path, access); + var timeAdjustments = TimeAdjustments.LastAccessTime; + if (access.HasFlag(FileAccess.Write)) + { + timeAdjustments |= TimeAdjustments.LastWriteTime; + } + mockFileDataAccessor.AdjustTimes(mockFileData, timeAdjustments); - if (mode == FileMode.CreateNew && exists) - { - throw CommonExceptions.FileAlreadyExists(path); - } + return new MockFileStream(mockFileDataAccessor, path, mode, access, options); + } - if ((mode == FileMode.Open || mode == FileMode.Truncate) && !exists) - { - throw CommonExceptions.FileNotFound(path); - } + /// + public override FileSystemStream OpenRead(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - if (!exists || mode == FileMode.CreateNew) - { - return CreateInternal(path, access, options); - } + return Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); + } - if (mode == FileMode.Create || mode == FileMode.Truncate) - { - Delete(path); - return CreateInternal(path, access, options); - } + /// + public override StreamReader OpenText(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - var mockFileData = mockFileDataAccessor.GetFile(path); - mockFileData.CheckFileAccess(path, access); - var timeAdjustments = TimeAdjustments.LastAccessTime; - if (access.HasFlag(FileAccess.Write)) - { - timeAdjustments |= TimeAdjustments.LastWriteTime; - } - mockFileDataAccessor.AdjustTimes(mockFileData, timeAdjustments); + return new StreamReader(OpenRead(path)); + } - return new MockFileStream(mockFileDataAccessor, path, mode, access, options); - } + /// + public override FileSystemStream OpenWrite(string path) => OpenWriteInternal(path, FileOptions.None); - /// - public override FileSystemStream OpenRead(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + private FileSystemStream OpenWriteInternal(string path, FileOptions options) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + return OpenInternal(path, FileMode.OpenOrCreate, FileAccess.Write, options); + } - return Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - } + /// + public override byte[] ReadAllBytes(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - /// - public override StreamReader OpenText(string path) + if (!mockFileDataAccessor.FileExists(path)) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - return new StreamReader(OpenRead(path)); + throw CommonExceptions.FileNotFound(path); } + mockFileDataAccessor.GetFile(path).CheckFileAccess(path, FileAccess.Read); + var fileData = mockFileDataAccessor.GetFile(path); + mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); + return fileData.Contents.ToArray(); + } - /// - public override FileSystemStream OpenWrite(string path) => OpenWriteInternal(path, FileOptions.None); + /// + public override string[] ReadAllLines(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - private FileSystemStream OpenWriteInternal(string path, FileOptions options) + if (!mockFileDataAccessor.FileExists(path)) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return OpenInternal(path, FileMode.OpenOrCreate, FileAccess.Write, options); + throw CommonExceptions.FileNotFound(path); } + var fileData = mockFileDataAccessor.GetFile(path); + fileData.CheckFileAccess(path, FileAccess.Read); + mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); - /// - public override byte[] ReadAllBytes(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + return fileData + .TextContents + .SplitLines(); + } - if (!mockFileDataAccessor.FileExists(path)) - { - throw CommonExceptions.FileNotFound(path); - } - mockFileDataAccessor.GetFile(path).CheckFileAccess(path, FileAccess.Read); - var fileData = mockFileDataAccessor.GetFile(path); - mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); - return fileData.Contents.ToArray(); - } + /// + public override string[] ReadAllLines(string path, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - /// - public override string[] ReadAllLines(string path) + if (encoding == null) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - - if (!mockFileDataAccessor.FileExists(path)) - { - throw CommonExceptions.FileNotFound(path); - } - var fileData = mockFileDataAccessor.GetFile(path); - fileData.CheckFileAccess(path, FileAccess.Read); - mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); - - return fileData - .TextContents - .SplitLines(); + throw new ArgumentNullException(nameof(encoding)); } - /// - public override string[] ReadAllLines(string path, Encoding encoding) + if (!mockFileDataAccessor.FileExists(path)) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + throw CommonExceptions.FileNotFound(path); + } - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + var fileData = mockFileDataAccessor.GetFile(path); + fileData.CheckFileAccess(path, FileAccess.Read); + mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); - if (!mockFileDataAccessor.FileExists(path)) - { - throw CommonExceptions.FileNotFound(path); - } + using (var ms = new MemoryStream(fileData.Contents)) + using (var sr = new StreamReader(ms, encoding)) + { + return sr.ReadToEnd().SplitLines(); + } + } - var fileData = mockFileDataAccessor.GetFile(path); - fileData.CheckFileAccess(path, FileAccess.Read); - mockFileDataAccessor.AdjustTimes(fileData, TimeAdjustments.LastAccessTime); + /// + public override string ReadAllText(string path) + { + return ReadAllText(path, MockFileData.DefaultEncoding); + } - using (var ms = new MemoryStream(fileData.Contents)) - using (var sr = new StreamReader(ms, encoding)) - { - return sr.ReadToEnd().SplitLines(); - } - } + /// + public override string ReadAllText(string path, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - /// - public override string ReadAllText(string path) + if (!mockFileDataAccessor.FileExists(path)) { - return ReadAllText(path, MockFileData.DefaultEncoding); + throw CommonExceptions.FileNotFound(path); } - /// - public override string ReadAllText(string path, Encoding encoding) + if (encoding == null) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + throw new ArgumentNullException(nameof(encoding)); + } - if (!mockFileDataAccessor.FileExists(path)) - { - throw CommonExceptions.FileNotFound(path); - } + return ReadAllTextInternal(path, encoding); + } - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + /// + public override IEnumerable ReadLines(string path) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - return ReadAllTextInternal(path, encoding); - } + return ReadAllLines(path); + } - /// - public override IEnumerable ReadLines(string path) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override IEnumerable ReadLines(string path, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(encoding, "encoding"); - return ReadAllLines(path); - } + return ReadAllLines(path, encoding); + } - /// - public override IEnumerable ReadLines(string path, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(encoding, "encoding"); + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) + { + Replace(sourceFileName, destinationFileName, destinationBackupFileName, false); + } - return ReadAllLines(path, encoding); + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + if (sourceFileName == null) + { + throw new ArgumentNullException(nameof(sourceFileName)); } - /// - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) + if (destinationFileName == null) { - Replace(sourceFileName, destinationFileName, destinationBackupFileName, false); + throw new ArgumentNullException(nameof(destinationFileName)); } - /// - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + if (!mockFileDataAccessor.FileExists(sourceFileName)) { - if (sourceFileName == null) - { - throw new ArgumentNullException(nameof(sourceFileName)); - } - - if (destinationFileName == null) - { - throw new ArgumentNullException(nameof(destinationFileName)); - } - - if (!mockFileDataAccessor.FileExists(sourceFileName)) - { - throw CommonExceptions.FileNotFound(sourceFileName); - } - - if (!mockFileDataAccessor.FileExists(destinationFileName)) - { - throw CommonExceptions.FileNotFound(destinationFileName); - } + throw CommonExceptions.FileNotFound(sourceFileName); + } - if (destinationBackupFileName != null) - { - Copy(destinationFileName, destinationBackupFileName, overwrite: true); - } + if (!mockFileDataAccessor.FileExists(destinationFileName)) + { + throw CommonExceptions.FileNotFound(destinationFileName); + } - Delete(destinationFileName); - Move(sourceFileName, destinationFileName); + if (destinationBackupFileName != null) + { + Copy(destinationFileName, destinationBackupFileName, overwrite: true); } + Delete(destinationFileName); + Move(sourceFileName, destinationFileName); + } + #if FEATURE_CREATE_SYMBOLIC_LINK /// public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) @@ -875,30 +875,30 @@ public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFi } #endif - /// - public override void SetAttributes(string path, FileAttributes fileAttributes) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override void SetAttributes(string path, FileAttributes fileAttributes) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - var possibleFileData = mockFileDataAccessor.GetFile(path); - if (possibleFileData == null) + var possibleFileData = mockFileDataAccessor.GetFile(path); + if (possibleFileData == null) + { + var directoryInfo = mockFileDataAccessor.DirectoryInfo.New(path); + if (directoryInfo.Exists) { - var directoryInfo = mockFileDataAccessor.DirectoryInfo.New(path); - if (directoryInfo.Exists) - { - directoryInfo.Attributes = fileAttributes; - } - else - { - throw CommonExceptions.FileNotFound(path); - } + directoryInfo.Attributes = fileAttributes; } else { - mockFileDataAccessor.AdjustTimes(possibleFileData, TimeAdjustments.LastAccessTime); - possibleFileData.Attributes = fileAttributes; + throw CommonExceptions.FileNotFound(path); } } + else + { + mockFileDataAccessor.AdjustTimes(possibleFileData, TimeAdjustments.LastAccessTime); + possibleFileData.Attributes = fileAttributes; + } + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -908,13 +908,13 @@ public override void SetAttributes(SafeFileHandle fileHandle, FileAttributes fil } #endif - /// - public override void SetCreationTime(string path, DateTime creationTime) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTime); - } + mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -924,13 +924,13 @@ public override void SetCreationTime(SafeFileHandle fileHandle, DateTime creatio } #endif - /// - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTimeUtc, TimeSpan.Zero); - } + mockFileDataAccessor.GetFile(path).CreationTime = new DateTimeOffset(creationTimeUtc, TimeSpan.Zero); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -940,13 +940,13 @@ public override void SetCreationTimeUtc(SafeFileHandle fileHandle, DateTime crea } #endif - /// - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTime); - } + mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -956,13 +956,13 @@ public override void SetLastAccessTime(SafeFileHandle fileHandle, DateTime lastA } #endif - /// - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTimeUtc, TimeSpan.Zero); - } + mockFileDataAccessor.GetFile(path).LastAccessTime = new DateTimeOffset(lastAccessTimeUtc, TimeSpan.Zero); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -972,13 +972,13 @@ public override void SetLastAccessTimeUtc(SafeFileHandle fileHandle, DateTime la } #endif - /// - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTime); - } + mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -988,13 +988,13 @@ public override void SetLastWriteTime(SafeFileHandle fileHandle, DateTime lastWr } #endif - /// - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTimeUtc, TimeSpan.Zero); - } + mockFileDataAccessor.GetFile(path).LastWriteTime = new DateTimeOffset(lastWriteTimeUtc, TimeSpan.Zero); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -1028,44 +1028,44 @@ public override void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mod } #endif - /// - /// Creates a new file, writes the specified byte array to the file, and then closes the file. - /// If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The bytes to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. - /// - public override void WriteAllBytes(string path, byte[] bytes) - { - VerifyValueIsNotNull(bytes, "bytes"); + /// + /// Creates a new file, writes the specified byte array to the file, and then closes the file. + /// If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The bytes to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. + /// + public override void WriteAllBytes(string path, byte[] bytes) + { + VerifyValueIsNotNull(bytes, "bytes"); - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyDirectoryExists(path); + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyDirectoryExists(path); - mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(bytes.ToArray()), TimeAdjustments.All)); - } + mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(new MockFileData(bytes.ToArray()), TimeAdjustments.All)); + } #if FEATURE_FILE_SPAN /// @@ -1075,276 +1075,276 @@ public override void WriteAllBytes(string path, ReadOnlySpan bytes) } #endif - /// - /// Creates a new file, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. - /// - /// - public override void WriteAllLines(string path, IEnumerable contents) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - - WriteAllLines(path, contents, MockFileData.DefaultEncoding); - } - - /// - /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// The character encoding to use. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either , , or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create a file that contains the following: - /// - /// - /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. - /// - /// - /// The contents of a collection that implements an of strings. - /// - /// - /// - /// - public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - VerifyValueIsNotNull(encoding, "encoding"); + /// + /// Creates a new file, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. + /// + /// + public override void WriteAllLines(string path, IEnumerable contents) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); - var sb = new StringBuilder(); - foreach (var line in contents) - { - sb.AppendLine(line); - } + WriteAllLines(path, contents, MockFileData.DefaultEncoding); + } - WriteAllText(path, sb.ToString(), encoding); - } - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - - WriteAllLines(path, contents, MockFileData.DefaultEncoding); - } - - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// An object that represents the character encoding applied to the string array. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents, Encoding encoding) - { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(contents, "contents"); - VerifyValueIsNotNull(encoding, "encoding"); - - WriteAllLines(path, new List(contents), encoding); - } - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. - /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. - /// - /// - public override void WriteAllText(string path, string contents) - { - WriteAllText(path, contents, MockFileData.DefaultEncoding); - } - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// The encoding to apply to the string. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. - /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. - /// - public override void WriteAllText(string path, string contents, Encoding encoding) + /// + /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// The character encoding to use. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either , , or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create a file that contains the following: + /// + /// + /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. + /// + /// + /// The contents of a collection that implements an of strings. + /// + /// + /// + /// + public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); + VerifyValueIsNotNull(encoding, "encoding"); + + var sb = new StringBuilder(); + foreach (var line in contents) { - mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - VerifyValueIsNotNull(path, "path"); + sb.AppendLine(line); + } - if (mockFileDataAccessor.Directory.Exists(path)) - { - throw CommonExceptions.AccessDenied(path); - } + WriteAllText(path, sb.ToString(), encoding); + } - VerifyDirectoryExists(path); + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); + + WriteAllLines(path, contents, MockFileData.DefaultEncoding); + } + + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// An object that represents the character encoding applied to the string array. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(contents, "contents"); + VerifyValueIsNotNull(encoding, "encoding"); - MockFileData data = contents == null ? new MockFileData(new byte[0]) : new MockFileData(contents, encoding); - mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(data, TimeAdjustments.All)); + WriteAllLines(path, new List(contents), encoding); + } + + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. + /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. + /// + /// + public override void WriteAllText(string path, string contents) + { + WriteAllText(path, contents, MockFileData.DefaultEncoding); + } + + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// The encoding to apply to the string. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. + /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. + /// + public override void WriteAllText(string path, string contents, Encoding encoding) + { + mockFileDataAccessor.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + VerifyValueIsNotNull(path, "path"); + + if (mockFileDataAccessor.Directory.Exists(path)) + { + throw CommonExceptions.AccessDenied(path); } + VerifyDirectoryExists(path); + + MockFileData data = contents == null ? new MockFileData(new byte[0]) : new MockFileData(contents, encoding); + mockFileDataAccessor.AddFile(path, mockFileDataAccessor.AdjustTimes(data, TimeAdjustments.All)); + } + #if FEATURE_FILE_SPAN /// public override void WriteAllText(string path, ReadOnlySpan contents) @@ -1359,40 +1359,39 @@ public override void WriteAllText(string path, ReadOnlySpan contents, Enco } #endif - internal static string ReadAllBytes(byte[] contents, Encoding encoding) + internal static string ReadAllBytes(byte[] contents, Encoding encoding) + { + using (var ms = new MemoryStream(contents)) + using (var sr = new StreamReader(ms, encoding)) { - using (var ms = new MemoryStream(contents)) - using (var sr = new StreamReader(ms, encoding)) - { - return sr.ReadToEnd(); - } + return sr.ReadToEnd(); } + } - private string ReadAllTextInternal(string path, Encoding encoding) - { - var mockFileData = mockFileDataAccessor.GetFile(path); - mockFileData.CheckFileAccess(path, FileAccess.Read); - mockFileDataAccessor.AdjustTimes(mockFileData, TimeAdjustments.LastAccessTime); - return ReadAllBytes(mockFileData.Contents, encoding); - } + private string ReadAllTextInternal(string path, Encoding encoding) + { + var mockFileData = mockFileDataAccessor.GetFile(path); + mockFileData.CheckFileAccess(path, FileAccess.Read); + mockFileDataAccessor.AdjustTimes(mockFileData, TimeAdjustments.LastAccessTime); + return ReadAllBytes(mockFileData.Contents, encoding); + } - private void VerifyValueIsNotNull(object value, string parameterName) + private void VerifyValueIsNotNull(object value, string parameterName) + { + if (value == null) { - if (value == null) - { - throw new ArgumentNullException(parameterName, StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); - } + throw new ArgumentNullException(parameterName, StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); } + } - private void VerifyDirectoryExists(string path) - { - var pathOps = mockFileDataAccessor.Path; - var dir = pathOps.GetDirectoryName(pathOps.GetFullPath(path)); + private void VerifyDirectoryExists(string path) + { + var pathOps = mockFileDataAccessor.Path; + var dir = pathOps.GetDirectoryName(pathOps.GetFullPath(path)); - if (!mockFileDataAccessor.Directory.Exists(dir)) - { - throw CommonExceptions.CouldNotFindPartOfPath(path); - } + if (!mockFileDataAccessor.Directory.Exists(dir)) + { + throw CommonExceptions.CouldNotFindPartOfPath(path); } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileData.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileData.cs index a7cfebb65..ea15019a1 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileData.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileData.cs @@ -3,209 +3,209 @@ using System.Security.AccessControl; using System.Text; -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// The class represents the associated data of a file. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class MockFileData { /// - /// The class represents the associated data of a file. + /// The default encoding. /// -#if FEATURE_SERIALIZABLE - [Serializable] -#endif - public class MockFileData - { - /// - /// The default encoding. - /// - public static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true); + public static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true); - /// - /// The null object. It represents the data of a non-existing file or directory. - /// - internal static readonly MockFileData NullObject = new MockFileData(string.Empty) - { - LastWriteTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), - LastAccessTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), - CreationTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), - Attributes = (FileAttributes)(-1), - }; + /// + /// The null object. It represents the data of a non-existing file or directory. + /// + internal static readonly MockFileData NullObject = new MockFileData(string.Empty) + { + LastWriteTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), + LastAccessTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), + CreationTime = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), + Attributes = (FileAttributes)(-1), + }; - /// - /// Gets the default date time offset. - /// E.g. for not existing files. - /// - public static readonly DateTimeOffset DefaultDateTimeOffset = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); + /// + /// Gets the default date time offset. + /// E.g. for not existing files. + /// + public static readonly DateTimeOffset DefaultDateTimeOffset = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); - /// - /// The access control of the . - /// + /// + /// The access control of the . + /// #if FEATURE_SERIALIZABLE - [NonSerialized] + [NonSerialized] #endif - private FileSecurity accessControl; + private FileSecurity accessControl; - /// - /// Gets a value indicating whether the is a directory or not. - /// - public bool IsDirectory { get { return Attributes.HasFlag(FileAttributes.Directory); } } + /// + /// Gets a value indicating whether the is a directory or not. + /// + public bool IsDirectory { get { return Attributes.HasFlag(FileAttributes.Directory); } } - /// - /// Initializes a new instance of the class with an empty content. - /// - private MockFileData() - { - var now = DateTime.UtcNow; - LastWriteTime = now; - LastAccessTime = now; - CreationTime = now; - } + /// + /// Initializes a new instance of the class with an empty content. + /// + private MockFileData() + { + var now = DateTime.UtcNow; + LastWriteTime = now; + LastAccessTime = now; + CreationTime = now; + } - /// - /// Initializes a new instance of the class with the content of using the encoding of . - /// - /// The textual content encoded into bytes with . - public MockFileData(string textContents) - : this(DefaultEncoding.GetBytes(textContents)) - { } + /// + /// Initializes a new instance of the class with the content of using the encoding of . + /// + /// The textual content encoded into bytes with . + public MockFileData(string textContents) + : this(DefaultEncoding.GetBytes(textContents)) + { } - /// - /// Initializes a new instance of the class with the content of using the encoding of . - /// - /// The textual content. - /// The specific encoding used the encode the text. - /// The constructor respect the BOM of . - public MockFileData(string textContents, Encoding encoding) - : this() - { - Contents = encoding.GetPreamble().Concat(encoding.GetBytes(textContents)).ToArray(); - } + /// + /// Initializes a new instance of the class with the content of using the encoding of . + /// + /// The textual content. + /// The specific encoding used the encode the text. + /// The constructor respect the BOM of . + public MockFileData(string textContents, Encoding encoding) + : this() + { + Contents = encoding.GetPreamble().Concat(encoding.GetBytes(textContents)).ToArray(); + } - /// - /// Initializes a new instance of the class with the content of . - /// - /// The actual content. - /// Thrown if is . - public MockFileData(byte[] contents) - : this() - { - Contents = contents ?? throw new ArgumentNullException(nameof(contents)); - } + /// + /// Initializes a new instance of the class with the content of . + /// + /// The actual content. + /// Thrown if is . + public MockFileData(byte[] contents) + : this() + { + Contents = contents ?? throw new ArgumentNullException(nameof(contents)); + } - /// - /// Initializes a new instance of the class by copying the given . - /// - /// The template instance. - /// Thrown if is . - public MockFileData(MockFileData template) + /// + /// Initializes a new instance of the class by copying the given . + /// + /// The template instance. + /// Thrown if is . + public MockFileData(MockFileData template) + { + if (template == null) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } - - accessControl = template.accessControl; - Attributes = template.Attributes; - Contents = template.Contents.ToArray(); - CreationTime = template.CreationTime; - LastAccessTime = template.LastAccessTime; - LastWriteTime = template.LastWriteTime; + throw new ArgumentNullException(nameof(template)); + } + + accessControl = template.accessControl; + Attributes = template.Attributes; + Contents = template.Contents.ToArray(); + CreationTime = template.CreationTime; + LastAccessTime = template.LastAccessTime; + LastWriteTime = template.LastWriteTime; #if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET - LinkTarget = template.LinkTarget; + LinkTarget = template.LinkTarget; #endif - } + } - /// - /// Gets or sets the byte contents of the . - /// - public byte[] Contents { get; set; } + /// + /// Gets or sets the byte contents of the . + /// + public byte[] Contents { get; set; } - /// - /// Gets or sets the file version info of the - /// - public IFileVersionInfo FileVersionInfo { get; set; } + /// + /// Gets or sets the file version info of the + /// + public IFileVersionInfo FileVersionInfo { get; set; } - /// - /// Gets or sets the string contents of the . - /// - /// - /// The setter uses the using this can scramble the actual contents. - /// - public string TextContents - { - get { return MockFile.ReadAllBytes(Contents, DefaultEncoding); } - set { Contents = DefaultEncoding.GetBytes(value); } - } + /// + /// Gets or sets the string contents of the . + /// + /// + /// The setter uses the using this can scramble the actual contents. + /// + public string TextContents + { + get { return MockFile.ReadAllBytes(Contents, DefaultEncoding); } + set { Contents = DefaultEncoding.GetBytes(value); } + } - /// - /// Gets or sets the date and time the was created. - /// - public DateTimeOffset CreationTime - { - get { return creationTime; } - set { creationTime = value.ToUniversalTime(); } - } - private DateTimeOffset creationTime; + /// + /// Gets or sets the date and time the was created. + /// + public DateTimeOffset CreationTime + { + get { return creationTime; } + set { creationTime = value.ToUniversalTime(); } + } + private DateTimeOffset creationTime; - /// - /// Gets or sets the date and time of the was last accessed to. - /// - public DateTimeOffset LastAccessTime - { - get { return lastAccessTime; } - set { lastAccessTime = value.ToUniversalTime(); } - } - private DateTimeOffset lastAccessTime; + /// + /// Gets or sets the date and time of the was last accessed to. + /// + public DateTimeOffset LastAccessTime + { + get { return lastAccessTime; } + set { lastAccessTime = value.ToUniversalTime(); } + } + private DateTimeOffset lastAccessTime; - /// - /// Gets or sets the date and time of the was last written to. - /// - public DateTimeOffset LastWriteTime - { - get { return lastWriteTime; } - set { lastWriteTime = value.ToUniversalTime(); } - } - private DateTimeOffset lastWriteTime; + /// + /// Gets or sets the date and time of the was last written to. + /// + public DateTimeOffset LastWriteTime + { + get { return lastWriteTime; } + set { lastWriteTime = value.ToUniversalTime(); } + } + private DateTimeOffset lastWriteTime; #if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET - /// - /// Gets or sets the link target of the . - /// - public string LinkTarget { get; set; } + /// + /// Gets or sets the link target of the . + /// + public string LinkTarget { get; set; } #endif - /// - /// Casts a string into . - /// - /// The path of the to be created. - public static implicit operator MockFileData(string s) - { - return new MockFileData(s); - } + /// + /// Casts a string into . + /// + /// The path of the to be created. + public static implicit operator MockFileData(string s) + { + return new MockFileData(s); + } - /// - /// Gets or sets the specified of the . - /// - public FileAttributes Attributes { get; set; } = FileAttributes.Normal; + /// + /// Gets or sets the specified of the . + /// + public FileAttributes Attributes { get; set; } = FileAttributes.Normal; - /// - /// Gets or sets of the . - /// - [SupportedOSPlatform("windows")] - public FileSecurity AccessControl + /// + /// Gets or sets of the . + /// + [SupportedOSPlatform("windows")] + public FileSecurity AccessControl + { + get { - get - { - // FileSecurity's constructor will throw PlatformNotSupportedException on non-Windows platform, so we initialize it in lazy way. - // This let's us use this class as long as we don't use AccessControl property. - return accessControl ?? (accessControl = new FileSecurity()); - } - set { accessControl = value; } + // FileSecurity's constructor will throw PlatformNotSupportedException on non-Windows platform, so we initialize it in lazy way. + // This let's us use this class as long as we don't use AccessControl property. + return accessControl ?? (accessControl = new FileSecurity()); } + set { accessControl = value; } + } - /// - /// Gets or sets the File sharing mode for this file, this allows you to lock a file for reading or writing. - /// - public FileShare AllowedFileShare { get; set; } = FileShare.ReadWrite | FileShare.Delete; + /// + /// Gets or sets the File sharing mode for this file, this allows you to lock a file for reading or writing. + /// + public FileShare AllowedFileShare { get; set; } = FileShare.ReadWrite | FileShare.Delete; #if FEATURE_UNIX_FILE_MODE /// @@ -216,31 +216,30 @@ public FileSecurity AccessControl UnixFileMode.OtherRead | UnixFileMode.UserWrite; #endif - /// - /// Checks whether the file is accessible for this type of FileAccess. - /// MockFileData can be configured to have FileShare.None, which indicates it is locked by a 'different process'. - /// - /// If the file is 'locked by a different process', an IOException will be thrown. - /// If the file is read-only and is accessed for writing, an UnauthorizedAccessException will be thrown. - /// - /// The path is used in the exception message to match the message in real life situations - /// The access type to check - internal void CheckFileAccess(string path, FileAccess access) + /// + /// Checks whether the file is accessible for this type of FileAccess. + /// MockFileData can be configured to have FileShare.None, which indicates it is locked by a 'different process'. + /// + /// If the file is 'locked by a different process', an IOException will be thrown. + /// If the file is read-only and is accessed for writing, an UnauthorizedAccessException will be thrown. + /// + /// The path is used in the exception message to match the message in real life situations + /// The access type to check + internal void CheckFileAccess(string path, FileAccess access) + { + if (!AllowedFileShare.HasFlag((FileShare)access)) { - if (!AllowedFileShare.HasFlag((FileShare)access)) - { - throw CommonExceptions.ProcessCannotAccessFileInUse(path); - } - - if (Attributes.HasFlag(FileAttributes.ReadOnly) && access.HasFlag(FileAccess.Write)) - { - throw CommonExceptions.AccessDenied(path); - } + throw CommonExceptions.ProcessCannotAccessFileInUse(path); } - internal virtual MockFileData Clone() + if (Attributes.HasFlag(FileAttributes.ReadOnly) && access.HasFlag(FileAccess.Write)) { - return new MockFileData(this); + throw CommonExceptions.AccessDenied(path); } } -} + + internal virtual MockFileData Clone() + { + return new MockFileData(this); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfo.cs index f9dd951f5..188ea3e0a 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfo.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfo.cs @@ -1,443 +1,442 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileInfo : FileInfoBase, IFileSystemAclSupport - { - private readonly IMockFileDataAccessor mockFileSystem; - private string path; - private readonly string originalPath; - private MockFileData cachedMockFileData; - private MockFile mockFile; - private bool refreshOnNextRead; +public class MockFileInfo : FileInfoBase, IFileSystemAclSupport +{ + private readonly IMockFileDataAccessor mockFileSystem; + private string path; + private readonly string originalPath; + private MockFileData cachedMockFileData; + private MockFile mockFile; + private bool refreshOnNextRead; - /// - public MockFileInfo(IMockFileDataAccessor mockFileSystem, string path) : base(mockFileSystem?.FileSystem) - { - this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); - mockFileSystem.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); - this.originalPath = path; - this.path = mockFileSystem.Path.GetFullPath(path); - this.mockFile = new MockFile(mockFileSystem); - Refresh(); - } + /// + public MockFileInfo(IMockFileDataAccessor mockFileSystem, string path) : base(mockFileSystem?.FileSystem) + { + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + mockFileSystem.PathVerifier.IsLegalAbsoluteOrRelative(path, "path"); + this.originalPath = path; + this.path = mockFileSystem.Path.GetFullPath(path); + this.mockFile = new MockFile(mockFileSystem); + Refresh(); + } #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public override void CreateAsSymbolicLink(string pathToTarget) - { - FileSystem.File.CreateSymbolicLink(FullName, pathToTarget); - } + /// + public override void CreateAsSymbolicLink(string pathToTarget) + { + FileSystem.File.CreateSymbolicLink(FullName, pathToTarget); + } #endif - /// - public override void Delete() - { - refreshOnNextRead = true; - mockFile.Delete(path); - } + /// + public override void Delete() + { + refreshOnNextRead = true; + mockFile.Delete(path); + } - /// - public override void Refresh() - { - var mockFileData = mockFileSystem.GetFile(path)?.Clone(); - cachedMockFileData = mockFileData ?? MockFileData.NullObject.Clone(); - } + /// + public override void Refresh() + { + var mockFileData = mockFileSystem.GetFile(path)?.Clone(); + cachedMockFileData = mockFileData ?? MockFileData.NullObject.Clone(); + } #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) - { - return FileSystem.File.ResolveLinkTarget(FullName, returnFinalTarget); - } + /// + public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) + { + return FileSystem.File.ResolveLinkTarget(FullName, returnFinalTarget); + } #endif - /// - public override FileAttributes Attributes - { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.Attributes; - } - set - { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.Attributes = value & ~FileAttributes.Directory; - } - } - - /// - public override DateTime CreationTime + /// + public override FileAttributes Attributes + { + get { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.CreationTime.LocalDateTime; - } - set - { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.CreationTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); - } + var mockFileData = GetMockFileDataForRead(); + return mockFileData.Attributes; } - - /// - public override DateTime CreationTimeUtc + set { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.CreationTime.UtcDateTime; - } - set - { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.CreationTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); - } + var mockFileData = GetMockFileDataForWrite(); + mockFileData.Attributes = value & ~FileAttributes.Directory; } + } - /// - public override bool Exists + /// + public override DateTime CreationTime + { + get { - get - { - var mockFileData = GetMockFileDataForRead(); - return (int)mockFileData.Attributes != -1 && !mockFileData.IsDirectory; - } + var mockFileData = GetMockFileDataForRead(); + return mockFileData.CreationTime.LocalDateTime; } - - /// - public override string Extension + set { - get - { - // System.IO.Path.GetExtension does only string manipulation, - // so it's safe to delegate. - return Path.GetExtension(path); - } + var mockFileData = GetMockFileDataForWrite(); + mockFileData.CreationTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); } + } - /// - public override string FullName + /// + public override DateTime CreationTimeUtc + { + get { - get { return path; } + var mockFileData = GetMockFileDataForRead(); + return mockFileData.CreationTime.UtcDateTime; } - - /// - public override DateTime LastAccessTime + set { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.LastAccessTime.LocalDateTime; - } - set - { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.LastAccessTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); - } + var mockFileData = GetMockFileDataForWrite(); + mockFileData.CreationTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); } + } - /// - public override DateTime LastAccessTimeUtc + /// + public override bool Exists + { + get { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.LastAccessTime.UtcDateTime; - } - set - { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.LastAccessTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); - } + var mockFileData = GetMockFileDataForRead(); + return (int)mockFileData.Attributes != -1 && !mockFileData.IsDirectory; } + } - /// - public override DateTime LastWriteTime + /// + public override string Extension + { + get { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.LastWriteTime.LocalDateTime; - } - set - { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.LastWriteTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); - } + // System.IO.Path.GetExtension does only string manipulation, + // so it's safe to delegate. + return Path.GetExtension(path); } + } - /// - public override DateTime LastWriteTimeUtc - { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.LastWriteTime.UtcDateTime; - } - set - { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.LastWriteTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); - } - } + /// + public override string FullName + { + get { return path; } + } -#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET - /// - public override string LinkTarget + /// + public override DateTime LastAccessTime + { + get { - get - { - var mockFileData = GetMockFileDataForRead(); - return mockFileData.LinkTarget; - } + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastAccessTime.LocalDateTime; } -#endif - - /// - public override string Name + set { - get { return new MockPath(mockFileSystem).GetFileName(path); } + var mockFileData = GetMockFileDataForWrite(); + mockFileData.LastAccessTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); } + } - /// - public override StreamWriter AppendText() + /// + public override DateTime LastAccessTimeUtc + { + get { - return new StreamWriter(new MockFileStream(mockFileSystem, FullName, FileMode.Append, FileAccess.Write)); + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastAccessTime.UtcDateTime; } - - /// - public override IFileInfo CopyTo(string destFileName) + set { - return CopyTo(destFileName, false); + var mockFileData = GetMockFileDataForWrite(); + mockFileData.LastAccessTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); } + } - /// - public override IFileInfo CopyTo(string destFileName, bool overwrite) + /// + public override DateTime LastWriteTime + { + get { - if (destFileName == FullName) - { - return this; - } - mockFile.Copy(FullName, destFileName, overwrite); - return mockFileSystem.FileInfo.New(destFileName); + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastWriteTime.LocalDateTime; } - - /// - public override FileSystemStream Create() + set { - var result = mockFile.Create(FullName); - refreshOnNextRead = true; - return result; + var mockFileData = GetMockFileDataForWrite(); + mockFileData.LastWriteTime = AdjustUnspecifiedKind(value, DateTimeKind.Local); } + } - /// - public override StreamWriter CreateText() + /// + public override DateTime LastWriteTimeUtc + { + get { - var result = mockFile.CreateText(FullName); - refreshOnNextRead = true; - return result; + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LastWriteTime.UtcDateTime; } - - /// - public override void Decrypt() + set { var mockFileData = GetMockFileDataForWrite(); - mockFileData.Attributes &= ~FileAttributes.Encrypted; + mockFileData.LastWriteTime = AdjustUnspecifiedKind(value, DateTimeKind.Utc); } + } - /// - public override void Encrypt() +#if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET + /// + public override string LinkTarget + { + get { - var mockFileData = GetMockFileDataForWrite(); - mockFileData.Attributes |= FileAttributes.Encrypted; + var mockFileData = GetMockFileDataForRead(); + return mockFileData.LinkTarget; } + } +#endif + + /// + public override string Name + { + get { return new MockPath(mockFileSystem).GetFileName(path); } + } + + /// + public override StreamWriter AppendText() + { + return new StreamWriter(new MockFileStream(mockFileSystem, FullName, FileMode.Append, FileAccess.Write)); + } + + /// + public override IFileInfo CopyTo(string destFileName) + { + return CopyTo(destFileName, false); + } - /// - public override void MoveTo(string destFileName) + /// + public override IFileInfo CopyTo(string destFileName, bool overwrite) + { + if (destFileName == FullName) { - mockFile.Move(path, destFileName); - path = mockFileSystem.Path.GetFullPath(destFileName); + return this; } + mockFile.Copy(FullName, destFileName, overwrite); + return mockFileSystem.FileInfo.New(destFileName); + } + + /// + public override FileSystemStream Create() + { + var result = mockFile.Create(FullName); + refreshOnNextRead = true; + return result; + } + + /// + public override StreamWriter CreateText() + { + var result = mockFile.CreateText(FullName); + refreshOnNextRead = true; + return result; + } + + /// + public override void Decrypt() + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.Attributes &= ~FileAttributes.Encrypted; + } + + /// + public override void Encrypt() + { + var mockFileData = GetMockFileDataForWrite(); + mockFileData.Attributes |= FileAttributes.Encrypted; + } + + /// + public override void MoveTo(string destFileName) + { + mockFile.Move(path, destFileName); + path = mockFileSystem.Path.GetFullPath(destFileName); + } #if FEATURE_FILE_MOVE_WITH_OVERWRITE - /// - public override void MoveTo(string destFileName, bool overwrite) - { - mockFile.Move(path, destFileName, overwrite); - path = mockFileSystem.Path.GetFullPath(destFileName); - } + /// + public override void MoveTo(string destFileName, bool overwrite) + { + mockFile.Move(path, destFileName, overwrite); + path = mockFileSystem.Path.GetFullPath(destFileName); + } #endif - /// - public override FileSystemStream Open(FileMode mode) - { - return mockFile.Open(FullName, mode); - } + /// + public override FileSystemStream Open(FileMode mode) + { + return mockFile.Open(FullName, mode); + } - /// - public override FileSystemStream Open(FileMode mode, FileAccess access) - { - return mockFile.Open(FullName, mode, access); - } + /// + public override FileSystemStream Open(FileMode mode, FileAccess access) + { + return mockFile.Open(FullName, mode, access); + } - /// - public override FileSystemStream Open(FileMode mode, FileAccess access, FileShare share) - { - return mockFile.Open(FullName, mode, access, share); - } + /// + public override FileSystemStream Open(FileMode mode, FileAccess access, FileShare share) + { + return mockFile.Open(FullName, mode, access, share); + } #if FEATURE_FILESTREAM_OPTIONS - /// - public override FileSystemStream Open(FileStreamOptions options) - { - return mockFile.Open(FullName, options.Mode, options.Access, options.Share); - } + /// + public override FileSystemStream Open(FileStreamOptions options) + { + return mockFile.Open(FullName, options.Mode, options.Access, options.Share); + } #endif - /// - public override FileSystemStream OpenRead() => mockFile.OpenRead(path); + /// + public override FileSystemStream OpenRead() => mockFile.OpenRead(path); + + /// + public override StreamReader OpenText() => mockFile.OpenText(path); - /// - public override StreamReader OpenText() => mockFile.OpenText(path); + /// + public override FileSystemStream OpenWrite() => mockFile.OpenWrite(path); - /// - public override FileSystemStream OpenWrite() => mockFile.OpenWrite(path); + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName) + { + return Replace(destinationFileName, destinationBackupFileName, false); + } - /// - public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName) - { - return Replace(destinationFileName, destinationBackupFileName, false); - } + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + mockFile.Replace(path, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); + return mockFileSystem.FileInfo.New(destinationFileName); + } - /// - public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + /// + public override IDirectoryInfo Directory + { + get { - mockFile.Replace(path, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); - return mockFileSystem.FileInfo.New(destinationFileName); + return mockFileSystem.DirectoryInfo.New(DirectoryName); } + } - /// - public override IDirectoryInfo Directory + /// + public override string DirectoryName + { + get { - get - { - return mockFileSystem.DirectoryInfo.New(DirectoryName); - } + // System.IO.Path.GetDirectoryName does only string manipulation, + // so it's safe to delegate. + return Path.GetDirectoryName(path); } + } - /// - public override string DirectoryName + /// + public override bool IsReadOnly + { + get { - get - { - // System.IO.Path.GetDirectoryName does only string manipulation, - // so it's safe to delegate. - return Path.GetDirectoryName(path); - } + var mockFileData = GetMockFileDataForRead(); + return (mockFileData.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; } - - /// - public override bool IsReadOnly + set { - get + var mockFileData = GetMockFileDataForWrite(); + if (value) { - var mockFileData = GetMockFileDataForRead(); - return (mockFileData.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + mockFileData.Attributes |= FileAttributes.ReadOnly; } - set + else { - var mockFileData = GetMockFileDataForWrite(); - if (value) - { - mockFileData.Attributes |= FileAttributes.ReadOnly; - } - else - { - mockFileData.Attributes &= ~FileAttributes.ReadOnly; - } + mockFileData.Attributes &= ~FileAttributes.ReadOnly; } } + } - /// - public override long Length + /// + public override long Length + { + get { - get + var mockFileData = GetMockFileDataForRead(); + if (mockFileData == null || mockFileData.IsDirectory) { - var mockFileData = GetMockFileDataForRead(); - if (mockFileData == null || mockFileData.IsDirectory) - { - throw CommonExceptions.FileNotFound(path); - } - return mockFileData.Contents.Length; + throw CommonExceptions.FileNotFound(path); } + return mockFileData.Contents.Length; } + } - /// - public override string ToString() - { - return originalPath; - } + /// + public override string ToString() + { + return originalPath; + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl() - { - return GetMockFileData().AccessControl; - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return GetMockFileData().AccessControl; + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) - { - return GetMockFileData().AccessControl; - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return GetMockFileData().AccessControl; + } - /// - [SupportedOSPlatform("windows")] - public void SetAccessControl(object value) - { - GetMockFileData().AccessControl = value as FileSecurity; - } + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + GetMockFileData().AccessControl = value as FileSecurity; + } - private MockFileData GetMockFileData() - { - return mockFileSystem.GetFile(path) - ?? throw CommonExceptions.FileNotFound(path); - } + private MockFileData GetMockFileData() + { + return mockFileSystem.GetFile(path) + ?? throw CommonExceptions.FileNotFound(path); + } - private static DateTime AdjustUnspecifiedKind(DateTime time, DateTimeKind fallbackKind) + private static DateTime AdjustUnspecifiedKind(DateTime time, DateTimeKind fallbackKind) + { + if (time.Kind == DateTimeKind.Unspecified) { - if (time.Kind == DateTimeKind.Unspecified) - { - return DateTime.SpecifyKind(time, fallbackKind); - } - - return time; + return DateTime.SpecifyKind(time, fallbackKind); } - private MockFileData GetMockFileDataForRead() - { - if (refreshOnNextRead) - { - Refresh(); - refreshOnNextRead = false; - } - return cachedMockFileData; - } + return time; + } - private MockFileData GetMockFileDataForWrite() + private MockFileData GetMockFileDataForRead() + { + if (refreshOnNextRead) { - refreshOnNextRead = true; - return mockFileSystem.GetFile(path) - ?? throw CommonExceptions.FileNotFound(path); + Refresh(); + refreshOnNextRead = false; } + return cachedMockFileData; + } + + private MockFileData GetMockFileDataForWrite() + { + refreshOnNextRead = true; + return mockFileSystem.GetFile(path) + ?? throw CommonExceptions.FileNotFound(path); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfoFactory.cs index 44c28061b..7d72ffa7c 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileInfoFactory.cs @@ -1,38 +1,37 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileInfoFactory : IFileInfoFactory +public class MockFileInfoFactory : IFileInfoFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockFileInfoFactory(IMockFileDataAccessor mockFileSystem) { - private readonly IMockFileDataAccessor mockFileSystem; + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } - /// - public MockFileInfoFactory(IMockFileDataAccessor mockFileSystem) - { - this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); - } + /// + public IFileSystem FileSystem + => mockFileSystem; - /// - public IFileSystem FileSystem - => mockFileSystem; + /// + public IFileInfo New(string fileName) + { + return new MockFileInfo(mockFileSystem, fileName); + } - /// - public IFileInfo New(string fileName) + /// + public IFileInfo Wrap(FileInfo fileInfo) + { + if (fileInfo == null) { - return new MockFileInfo(mockFileSystem, fileName); + return null; } - /// - public IFileInfo Wrap(FileInfo fileInfo) - { - if (fileInfo == null) - { - return null; - } - - return new MockFileInfo(mockFileSystem, fileInfo.FullName); - } + return new MockFileInfo(mockFileSystem, fileInfo.FullName); } } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStream.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStream.cs index 1226344e0..1be2241af 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStream.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStream.cs @@ -3,185 +3,185 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileStream : FileSystemStream, IFileSystemAclSupport +public class MockFileStream : FileSystemStream, IFileSystemAclSupport +{ + /// + /// Wrapper around a with no backing store, which + /// is used as a replacement for a . As such + /// it implements the same properties and methods as a . + /// + public new static FileSystemStream Null { get; } = new NullFileSystemStream(); + + private class NullFileSystemStream : FileSystemStream { /// - /// Wrapper around a with no backing store, which - /// is used as a replacement for a . As such - /// it implements the same properties and methods as a . + /// Initializes a new instance of . /// - public new static FileSystemStream Null { get; } = new NullFileSystemStream(); - - private class NullFileSystemStream : FileSystemStream + public NullFileSystemStream() : base(Null, ".", true) { - /// - /// Initializes a new instance of . - /// - public NullFileSystemStream() : base(Null, ".", true) - { - } } + } - private readonly IMockFileDataAccessor mockFileDataAccessor; - private readonly string path; - private readonly FileAccess access = FileAccess.ReadWrite; - private readonly FileOptions options; - private readonly MockFileData fileData; - private bool disposed; + private readonly IMockFileDataAccessor mockFileDataAccessor; + private readonly string path; + private readonly FileAccess access = FileAccess.ReadWrite; + private readonly FileOptions options; + private readonly MockFileData fileData; + private bool disposed; - /// - public MockFileStream( - IMockFileDataAccessor mockFileDataAccessor, - string path, - FileMode mode, - FileAccess access = FileAccess.ReadWrite, - FileOptions options = FileOptions.None) + /// + public MockFileStream( + IMockFileDataAccessor mockFileDataAccessor, + string path, + FileMode mode, + FileAccess access = FileAccess.ReadWrite, + FileOptions options = FileOptions.None) : base(new MemoryStream(), - path == null ? null : Path.GetFullPath(path), - (options & FileOptions.Asynchronous) != 0) + path == null ? null : Path.GetFullPath(path), + (options & FileOptions.Asynchronous) != 0) - { - ThrowIfInvalidModeAccess(mode, access); + { + ThrowIfInvalidModeAccess(mode, access); - this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); - this.path = path; - this.options = options; + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + this.path = path; + this.options = options; - if (mockFileDataAccessor.FileExists(path)) + if (mockFileDataAccessor.FileExists(path)) + { + if (mode.Equals(FileMode.CreateNew)) { - if (mode.Equals(FileMode.CreateNew)) - { - throw CommonExceptions.FileAlreadyExists(path); - } + throw CommonExceptions.FileAlreadyExists(path); + } - fileData = mockFileDataAccessor.GetFile(path); - fileData.CheckFileAccess(path, access); + fileData = mockFileDataAccessor.GetFile(path); + fileData.CheckFileAccess(path, access); - var timeAdjustments = GetTimeAdjustmentsForFileStreamWhenFileExists(mode, access); - mockFileDataAccessor.AdjustTimes(fileData, timeAdjustments); - var existingContents = fileData.Contents; - var keepExistingContents = - existingContents?.Length > 0 && - mode != FileMode.Truncate && mode != FileMode.Create; - if (keepExistingContents) - { - base.Write(existingContents, 0, existingContents.Length); - base.Seek(0, mode == FileMode.Append - ? SeekOrigin.End - : SeekOrigin.Begin); - } + var timeAdjustments = GetTimeAdjustmentsForFileStreamWhenFileExists(mode, access); + mockFileDataAccessor.AdjustTimes(fileData, timeAdjustments); + var existingContents = fileData.Contents; + var keepExistingContents = + existingContents?.Length > 0 && + mode != FileMode.Truncate && mode != FileMode.Create; + if (keepExistingContents) + { + base.Write(existingContents, 0, existingContents.Length); + base.Seek(0, mode == FileMode.Append + ? SeekOrigin.End + : SeekOrigin.Begin); } - else + } + else + { + var directoryPath = mockFileDataAccessor.Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directoryPath) && !mockFileDataAccessor.Directory.Exists(directoryPath)) { - var directoryPath = mockFileDataAccessor.Path.GetDirectoryName(path); - if (!string.IsNullOrEmpty(directoryPath) && !mockFileDataAccessor.Directory.Exists(directoryPath)) - { - throw CommonExceptions.CouldNotFindPartOfPath(path); - } - - if (mode.Equals(FileMode.Open) || mode.Equals(FileMode.Truncate)) - { - throw CommonExceptions.FileNotFound(path); - } + throw CommonExceptions.CouldNotFindPartOfPath(path); + } - fileData = new MockFileData(new byte[] { }); - mockFileDataAccessor.AdjustTimes(fileData, - TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime); - mockFileDataAccessor.AddFile(path, fileData); + if (mode.Equals(FileMode.Open) || mode.Equals(FileMode.Truncate)) + { + throw CommonExceptions.FileNotFound(path); } - this.access = access; + fileData = new MockFileData(new byte[] { }); + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime); + mockFileDataAccessor.AddFile(path, fileData); } - private static void ThrowIfInvalidModeAccess(FileMode mode, FileAccess access) + this.access = access; + } + + private static void ThrowIfInvalidModeAccess(FileMode mode, FileAccess access) + { + if (mode == FileMode.Append) { - if (mode == FileMode.Append) + if (access == FileAccess.Read) { - if (access == FileAccess.Read) - { - throw CommonExceptions.InvalidAccessCombination(mode, access); - } - - if (access != FileAccess.Write) - { - throw CommonExceptions.AppendAccessOnlyInWriteOnlyMode(); - } + throw CommonExceptions.InvalidAccessCombination(mode, access); } - if (!access.HasFlag(FileAccess.Write) && - (mode == FileMode.Truncate || mode == FileMode.CreateNew || - mode == FileMode.Create || mode == FileMode.Append)) + if (access != FileAccess.Write) { - throw CommonExceptions.InvalidAccessCombination(mode, access); + throw CommonExceptions.AppendAccessOnlyInWriteOnlyMode(); } } - /// - public override bool CanRead => access.HasFlag(FileAccess.Read); - - /// - public override bool CanWrite => access.HasFlag(FileAccess.Write); - - /// - public override int Read(byte[] buffer, int offset, int count) + if (!access.HasFlag(FileAccess.Write) && + (mode == FileMode.Truncate || mode == FileMode.CreateNew || + mode == FileMode.Create || mode == FileMode.Append)) { - mockFileDataAccessor.AdjustTimes(fileData, - TimeAdjustments.LastAccessTime); - return base.Read(buffer, offset, count); + throw CommonExceptions.InvalidAccessCombination(mode, access); } + } - /// - protected override void Dispose(bool disposing) + /// + public override bool CanRead => access.HasFlag(FileAccess.Read); + + /// + public override bool CanWrite => access.HasFlag(FileAccess.Write); + + /// + public override int Read(byte[] buffer, int offset, int count) + { + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime); + return base.Read(buffer, offset, count); + } + + /// + protected override void Dispose(bool disposing) + { + if (disposed) { - if (disposed) - { - return; - } - InternalFlush(); - base.Dispose(disposing); - OnClose(); - disposed = true; + return; } + InternalFlush(); + base.Dispose(disposing); + OnClose(); + disposed = true; + } - /// - public override void EndWrite(IAsyncResult asyncResult) + /// + public override void EndWrite(IAsyncResult asyncResult) + { + if (!CanWrite) { - if (!CanWrite) - { - throw new NotSupportedException("Stream does not support writing."); - } - base.EndWrite(asyncResult); + throw new NotSupportedException("Stream does not support writing."); } + base.EndWrite(asyncResult); + } - /// - public override void SetLength(long value) + /// + public override void SetLength(long value) + { + if (!CanWrite) { - if (!CanWrite) - { - throw new NotSupportedException("Stream does not support writing."); - } - - base.SetLength(value); + throw new NotSupportedException("Stream does not support writing."); } - /// - public override void Write(byte[] buffer, int offset, int count) + base.SetLength(value); + } + + /// + public override void Write(byte[] buffer, int offset, int count) + { + if (!CanWrite) { - if (!CanWrite) - { - throw new NotSupportedException("Stream does not support writing."); - } - mockFileDataAccessor.AdjustTimes(fileData, - TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); - base.Write(buffer, offset, count); + throw new NotSupportedException("Stream does not support writing."); } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + base.Write(buffer, offset, count); + } #if FEATURE_SPAN /// @@ -197,18 +197,18 @@ public override void Write(ReadOnlySpan buffer) } #endif - /// - public override Task WriteAsync(byte[] buffer, int offset, int count, - CancellationToken cancellationToken) + /// + public override Task WriteAsync(byte[] buffer, int offset, int count, + CancellationToken cancellationToken) + { + if (!CanWrite) { - if (!CanWrite) - { - throw new NotSupportedException("Stream does not support writing."); - } - mockFileDataAccessor.AdjustTimes(fileData, - TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); - return base.WriteAsync(buffer, offset, count, cancellationToken); + throw new NotSupportedException("Stream does not support writing."); } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + return base.WriteAsync(buffer, offset, count, cancellationToken); + } #if FEATURE_SPAN /// @@ -225,118 +225,117 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, } #endif - /// - public override void WriteByte(byte value) + /// + public override void WriteByte(byte value) + { + if (!CanWrite) { - if (!CanWrite) - { - throw new NotSupportedException("Stream does not support writing."); - } - mockFileDataAccessor.AdjustTimes(fileData, - TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); - base.WriteByte(value); + throw new NotSupportedException("Stream does not support writing."); } + mockFileDataAccessor.AdjustTimes(fileData, + TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime); + base.WriteByte(value); + } - /// - public override void Flush() - { - InternalFlush(); - } + /// + public override void Flush() + { + InternalFlush(); + } - /// - public override void Flush(bool flushToDisk) - => InternalFlush(); + /// + public override void Flush(bool flushToDisk) + => InternalFlush(); - /// - public override Task FlushAsync(CancellationToken cancellationToken) - { - InternalFlush(); - return Task.CompletedTask; - } + /// + public override Task FlushAsync(CancellationToken cancellationToken) + { + InternalFlush(); + return Task.CompletedTask; + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl() - { - return GetMockFileData().AccessControl; - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return GetMockFileData().AccessControl; + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) - { - return GetMockFileData().AccessControl; - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return GetMockFileData().AccessControl; + } - /// - [SupportedOSPlatform("windows")] - public void SetAccessControl(object value) - { - GetMockFileData().AccessControl = value as FileSecurity; - } + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + GetMockFileData().AccessControl = value as FileSecurity; + } + + private MockFileData GetMockFileData() + { + return mockFileDataAccessor.GetFile(path) + ?? throw CommonExceptions.FileNotFound(path); + } - private MockFileData GetMockFileData() + private void InternalFlush() + { + if (mockFileDataAccessor.FileExists(path)) { - return mockFileDataAccessor.GetFile(path) - ?? throw CommonExceptions.FileNotFound(path); + var mockFileData = mockFileDataAccessor.GetFile(path); + /* reset back to the beginning .. */ + var position = Position; + Seek(0, SeekOrigin.Begin); + /* .. read everything out */ + var data = new byte[Length]; + _ = Read(data, 0, (int)Length); + /* restore to original position */ + Seek(position, SeekOrigin.Begin); + /* .. put it in the mock system */ + mockFileData.Contents = data; } + } - private void InternalFlush() + private void OnClose() + { + if (options.HasFlag(FileOptions.DeleteOnClose) && mockFileDataAccessor.FileExists(path)) { - if (mockFileDataAccessor.FileExists(path)) - { - var mockFileData = mockFileDataAccessor.GetFile(path); - /* reset back to the beginning .. */ - var position = Position; - Seek(0, SeekOrigin.Begin); - /* .. read everything out */ - var data = new byte[Length]; - _ = Read(data, 0, (int)Length); - /* restore to original position */ - Seek(position, SeekOrigin.Begin); - /* .. put it in the mock system */ - mockFileData.Contents = data; - } + mockFileDataAccessor.RemoveFile(path); } - private void OnClose() + if (options.HasFlag(FileOptions.Encrypted) && mockFileDataAccessor.FileExists(path)) { - if (options.HasFlag(FileOptions.DeleteOnClose) && mockFileDataAccessor.FileExists(path)) - { - mockFileDataAccessor.RemoveFile(path); - } - - if (options.HasFlag(FileOptions.Encrypted) && mockFileDataAccessor.FileExists(path)) - { #pragma warning disable CA1416 // Ignore SupportedOSPlatform for testing helper encryption - mockFileDataAccessor.FileInfo.New(path).Encrypt(); + mockFileDataAccessor.FileInfo.New(path).Encrypt(); #pragma warning restore CA1416 - } } + } - private TimeAdjustments GetTimeAdjustmentsForFileStreamWhenFileExists(FileMode mode, FileAccess access) + private TimeAdjustments GetTimeAdjustmentsForFileStreamWhenFileExists(FileMode mode, FileAccess access) + { + switch (mode) { - switch (mode) - { - case FileMode.Append: - case FileMode.CreateNew: - if (access.HasFlag(FileAccess.Read)) - { - return TimeAdjustments.LastAccessTime; - } - return TimeAdjustments.None; - case FileMode.Create: - case FileMode.Truncate: - if (access.HasFlag(FileAccess.Write)) - { - return TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime; - } + case FileMode.Append: + case FileMode.CreateNew: + if (access.HasFlag(FileAccess.Read)) + { return TimeAdjustments.LastAccessTime; - case FileMode.Open: - case FileMode.OpenOrCreate: - default: - return TimeAdjustments.None; - } + } + return TimeAdjustments.None; + case FileMode.Create: + case FileMode.Truncate: + if (access.HasFlag(FileAccess.Write)) + { + return TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime; + } + return TimeAdjustments.LastAccessTime; + case FileMode.Open: + case FileMode.OpenOrCreate: + default: + return TimeAdjustments.None; } } } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStreamFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStreamFactory.cs index 26a773f0a..9cd34f7ae 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStreamFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileStreamFactory.cs @@ -1,69 +1,68 @@ using System.Security.AccessControl; using Microsoft.Win32.SafeHandles; -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileStreamFactory : IFileStreamFactory - { - private readonly IMockFileDataAccessor mockFileSystem; +public class MockFileStreamFactory : IFileStreamFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; - /// - public MockFileStreamFactory(IMockFileDataAccessor mockFileSystem) - => this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + /// + public MockFileStreamFactory(IMockFileDataAccessor mockFileSystem) + => this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); - /// - public IFileSystem FileSystem - => mockFileSystem; + /// + public IFileSystem FileSystem + => mockFileSystem; - /// - public FileSystemStream New(SafeFileHandle handle, FileAccess access) - => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access) + => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); - /// - public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize) - => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize) + => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); - /// - public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) - => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) + => new MockFileStream(mockFileSystem, handle.ToString(), FileMode.Open, access: access); - /// - public FileSystemStream New(string path, FileMode mode) - => new MockFileStream(mockFileSystem, path, mode); + /// + public FileSystemStream New(string path, FileMode mode) + => new MockFileStream(mockFileSystem, path, mode); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access) - => new MockFileStream(mockFileSystem, path, mode, access); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access) + => new MockFileStream(mockFileSystem, path, mode, access); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share) - => new MockFileStream(mockFileSystem, path, mode, access); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share) + => new MockFileStream(mockFileSystem, path, mode, access); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) - => new MockFileStream(mockFileSystem, path, mode, access); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) + => new MockFileStream(mockFileSystem, path, mode, access); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) - => new MockFileStream(mockFileSystem, path, mode, access); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) + => new MockFileStream(mockFileSystem, path, mode, access); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, - FileOptions options) - => new MockFileStream(mockFileSystem, path, mode, access, options); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, + FileOptions options) + => new MockFileStream(mockFileSystem, path, mode, access, options); #if FEATURE_FILESTREAM_OPTIONS - /// - public FileSystemStream New(string path, FileStreamOptions options) - => new MockFileStream(mockFileSystem, path, options.Mode, options.Access, options.Options); + /// + public FileSystemStream New(string path, FileStreamOptions options) + => new MockFileStream(mockFileSystem, path, options.Mode, options.Access, options.Options); #endif - /// - public FileSystemStream Wrap(FileStream fileStream) - => throw new NotSupportedException("You cannot wrap an existing FileStream in the MockFileSystem instance!"); - } + /// + public FileSystemStream Wrap(FileStream fileStream) + => throw new NotSupportedException("You cannot wrap an existing FileStream in the MockFileSystem instance!"); } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystem.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystem.cs index 572461551..6169ec66a 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystem.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystem.cs @@ -3,582 +3,581 @@ using System.Reflection; using System.Runtime.Serialization; -namespace System.IO.Abstractions.TestingHelpers -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers; - /// +using XFS = MockUnixSupport; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileSystem : FileSystemBase, IMockFileDataAccessor - { - private const string DEFAULT_CURRENT_DIRECTORY = @"C:\"; - private const string TEMP_DIRECTORY = @"C:\temp\"; +public class MockFileSystem : FileSystemBase, IMockFileDataAccessor +{ + private const string DEFAULT_CURRENT_DIRECTORY = @"C:\"; + private const string TEMP_DIRECTORY = @"C:\temp\"; - private readonly IDictionary files; - private readonly IDictionary drives; - private readonly PathVerifier pathVerifier; + private readonly IDictionary files; + private readonly IDictionary drives; + private readonly PathVerifier pathVerifier; #if FEATURE_SERIALIZABLE - [NonSerialized] + [NonSerialized] #endif - private Func dateTimeProvider = defaultDateTimeProvider; - private static Func defaultDateTimeProvider = () => DateTime.UtcNow; - - /// - public MockFileSystem() : this(null) { } - - /// - public MockFileSystem(IDictionary files, string currentDirectory = "") - : this(files, new MockFileSystemOptions - { - CurrentDirectory = currentDirectory, - CreateDefaultTempDir = true - }) { } + private Func dateTimeProvider = defaultDateTimeProvider; + private static Func defaultDateTimeProvider = () => DateTime.UtcNow; - /// - public MockFileSystem(MockFileSystemOptions options) - : this(null, options) { } + /// + public MockFileSystem() : this(null) { } - /// - public MockFileSystem(IDictionary files, MockFileSystemOptions options) + /// + public MockFileSystem(IDictionary files, string currentDirectory = "") + : this(files, new MockFileSystemOptions { - options ??= new MockFileSystemOptions(); - var currentDirectory = options.CurrentDirectory; - if (string.IsNullOrEmpty(currentDirectory)) - { - currentDirectory = XFS.Path(DEFAULT_CURRENT_DIRECTORY); - } - else if (!System.IO.Path.IsPathRooted(currentDirectory)) - { - throw new ArgumentException("Current directory needs to be rooted.", nameof(currentDirectory)); - } + CurrentDirectory = currentDirectory, + CreateDefaultTempDir = true + }) { } - var defaultTempDirectory = XFS.Path(TEMP_DIRECTORY); + /// + public MockFileSystem(MockFileSystemOptions options) + : this(null, options) { } - StringOperations = new StringOperations(XFS.IsUnixPlatform()); - pathVerifier = new PathVerifier(this); - this.files = new Dictionary(StringOperations.Comparer); - drives = new Dictionary(StringOperations.Comparer); + /// + public MockFileSystem(IDictionary files, MockFileSystemOptions options) + { + options ??= new MockFileSystemOptions(); + var currentDirectory = options.CurrentDirectory; + if (string.IsNullOrEmpty(currentDirectory)) + { + currentDirectory = XFS.Path(DEFAULT_CURRENT_DIRECTORY); + } + else if (!System.IO.Path.IsPathRooted(currentDirectory)) + { + throw new ArgumentException("Current directory needs to be rooted.", nameof(currentDirectory)); + } - Path = new MockPath(this, defaultTempDirectory); - File = new MockFile(this); - Directory = new MockDirectory(this, currentDirectory); - FileInfo = new MockFileInfoFactory(this); - FileVersionInfo = new MockFileVersionInfoFactory(this); - FileStream = new MockFileStreamFactory(this); - DirectoryInfo = new MockDirectoryInfoFactory(this); - DriveInfo = new MockDriveInfoFactory(this); - FileSystemWatcher = new MockFileSystemWatcherFactory(this); + var defaultTempDirectory = XFS.Path(TEMP_DIRECTORY); - if (files != null) - { - foreach (var entry in files) - { - AddFile(entry.Key, entry.Value); - } - } + StringOperations = new StringOperations(XFS.IsUnixPlatform()); + pathVerifier = new PathVerifier(this); + this.files = new Dictionary(StringOperations.Comparer); + drives = new Dictionary(StringOperations.Comparer); - if (!FileExists(currentDirectory)) - { - AddDirectory(currentDirectory); - } + Path = new MockPath(this, defaultTempDirectory); + File = new MockFile(this); + Directory = new MockDirectory(this, currentDirectory); + FileInfo = new MockFileInfoFactory(this); + FileVersionInfo = new MockFileVersionInfoFactory(this); + FileStream = new MockFileStreamFactory(this); + DirectoryInfo = new MockDirectoryInfoFactory(this); + DriveInfo = new MockDriveInfoFactory(this); + FileSystemWatcher = new MockFileSystemWatcherFactory(this); - if (options.CreateDefaultTempDir && !FileExists(defaultTempDirectory)) + if (files != null) + { + foreach (var entry in files) { - AddDirectory(defaultTempDirectory); + AddFile(entry.Key, entry.Value); } } - /// - public StringOperations StringOperations { get; } - /// - public override IFile File { get; } - /// - public override IDirectory Directory { get; } - /// - public override IFileInfoFactory FileInfo { get; } - /// - public override IFileVersionInfoFactory FileVersionInfo { get; } - /// - public override IFileStreamFactory FileStream { get; } - /// - public override IPath Path { get; } - /// - public override IDirectoryInfoFactory DirectoryInfo { get; } - /// - public override IDriveInfoFactory DriveInfo { get; } - /// - public override IFileSystemWatcherFactory FileSystemWatcher { get; } - /// - public IFileSystem FileSystem => this; - /// - public PathVerifier PathVerifier => pathVerifier; - - /// - /// Replaces the time provider with a mocked instance. This allows to influence the used time in tests. - /// - /// If not set, the default implementation returns . - /// - /// The function that returns the current . - /// - public MockFileSystem MockTime(Func dateTimeProvider) - { - this.dateTimeProvider = dateTimeProvider ?? defaultDateTimeProvider; - 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); + if (!FileExists(currentDirectory)) + { + AddDirectory(currentDirectory); + } - return checkCaps ? GetPathWithCorrectDirectoryCapitalization(fullPath) : fullPath; + if (options.CreateDefaultTempDir && !FileExists(defaultTempDirectory)) + { + AddDirectory(defaultTempDirectory); } + } - //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) + /// + public StringOperations StringOperations { get; } + /// + public override IFile File { get; } + /// + public override IDirectory Directory { get; } + /// + public override IFileInfoFactory FileInfo { get; } + /// + public override IFileVersionInfoFactory FileVersionInfo { get; } + /// + public override IFileStreamFactory FileStream { get; } + /// + public override IPath Path { get; } + /// + public override IDirectoryInfoFactory DirectoryInfo { get; } + /// + public override IDriveInfoFactory DriveInfo { get; } + /// + public override IFileSystemWatcherFactory FileSystemWatcher { get; } + /// + public IFileSystem FileSystem => this; + /// + public PathVerifier PathVerifier => pathVerifier; + + /// + /// Replaces the time provider with a mocked instance. This allows to influence the used time in tests. + /// + /// If not set, the default implementation returns . + /// + /// The function that returns the current . + /// + public MockFileSystem MockTime(Func dateTimeProvider) + { + this.dateTimeProvider = dateTimeProvider ?? defaultDateTimeProvider; + return this; + } + + private string FixPath(string path, bool checkCaps = false) + { + if (path == null) { - string[] splitPath = fullPath.Split(Path.DirectorySeparatorChar); - string leftHalf = fullPath; - string rightHalf = ""; + throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } - for (int i = splitPath.Length - 1; i > 1; i--) - { - rightHalf = i == splitPath.Length - 1 ? splitPath[i] : splitPath[i] + Path.DirectorySeparatorChar + rightHalf; - int lastSeparator = leftHalf.LastIndexOf(Path.DirectorySeparatorChar); - leftHalf = lastSeparator > 0 ? leftHalf.Substring(0, lastSeparator) : leftHalf; + var pathSeparatorFixed = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); + var fullPath = Path.GetFullPath(pathSeparatorFixed); - if (DirectoryExistsWithoutFixingPath(leftHalf)) - { - string baseDirectory = files[leftHalf].Path; - return baseDirectory + Path.DirectorySeparatorChar + rightHalf; - } - } + return checkCaps ? GetPathWithCorrectDirectoryCapitalization(fullPath) : fullPath; + } - return fullPath.TrimSlashes(); - } + //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) + { + string[] splitPath = fullPath.Split(Path.DirectorySeparatorChar); + string leftHalf = fullPath; + string rightHalf = ""; - /// - public MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjustments) + for (int i = splitPath.Length - 1; i > 1; i--) { - var now = dateTimeProvider(); - if (timeAdjustments.HasFlag(TimeAdjustments.CreationTime)) - { - fileData.CreationTime = now; - } + rightHalf = i == splitPath.Length - 1 ? splitPath[i] : splitPath[i] + Path.DirectorySeparatorChar + rightHalf; + int lastSeparator = leftHalf.LastIndexOf(Path.DirectorySeparatorChar); + leftHalf = lastSeparator > 0 ? leftHalf.Substring(0, lastSeparator) : leftHalf; - if (timeAdjustments.HasFlag(TimeAdjustments.LastAccessTime)) + if (DirectoryExistsWithoutFixingPath(leftHalf)) { - fileData.LastAccessTime = now; + string baseDirectory = files[leftHalf].Path; + return baseDirectory + Path.DirectorySeparatorChar + rightHalf; } + } - if (timeAdjustments.HasFlag(TimeAdjustments.LastWriteTime)) - { - fileData.LastWriteTime = now; - } + return fullPath.TrimSlashes(); + } - return fileData; + /// + public MockFileData AdjustTimes(MockFileData fileData, TimeAdjustments timeAdjustments) + { + var now = dateTimeProvider(); + if (timeAdjustments.HasFlag(TimeAdjustments.CreationTime)) + { + fileData.CreationTime = now; } - /// - public MockFileData GetFile(string path) + if (timeAdjustments.HasFlag(TimeAdjustments.LastAccessTime)) { - path = FixPath(path).TrimSlashes(); - return GetFileWithoutFixingPath(path); + fileData.LastAccessTime = now; } - /// - public MockDriveData GetDrive(string name) + if (timeAdjustments.HasFlag(TimeAdjustments.LastWriteTime)) { - name = PathVerifier.NormalizeDriveName(name); - lock (drives) - { - return drives.TryGetValue(name, out var result) ? result : null; - } + fileData.LastWriteTime = now; } - private void SetEntry(string path, MockFileData mockFile) + return fileData; + } + + /// + public MockFileData GetFile(string path) + { + path = FixPath(path).TrimSlashes(); + return GetFileWithoutFixingPath(path); + } + + /// + public MockDriveData GetDrive(string name) + { + name = PathVerifier.NormalizeDriveName(name); + lock (drives) { - path = FixPath(path, true).TrimSlashes(); + return drives.TryGetValue(name, out var result) ? result : null; + } + } - lock (files) - { - files[path] = new FileSystemEntry { Path = path, Data = mockFile }; - } + private void SetEntry(string path, MockFileData mockFile) + { + path = FixPath(path, true).TrimSlashes(); - lock (drives) + lock (files) + { + files[path] = new FileSystemEntry { Path = path, Data = mockFile }; + } + + lock (drives) + { + if (PathVerifier.TryNormalizeDriveName(path, out string driveLetter)) { - if (PathVerifier.TryNormalizeDriveName(path, out string driveLetter)) + if (!drives.ContainsKey(driveLetter)) { - if (!drives.ContainsKey(driveLetter)) - { - drives[driveLetter] = new MockDriveData(); - } + drives[driveLetter] = new MockDriveData(); } } } + } - /// - public void AddFile(string path, MockFileData mockFile) - { - var fixedPath = FixPath(path, true); - - mockFile ??= new MockFileData(string.Empty); - var file = GetFile(fixedPath); + /// + public void AddFile(string path, MockFileData mockFile) + { + var fixedPath = FixPath(path, true); - if (file != null) - { - var isReadOnly = (file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; - var isHidden = (file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; + mockFile ??= new MockFileData(string.Empty); + var file = GetFile(fixedPath); - if (isReadOnly || isHidden) - { - throw CommonExceptions.AccessDenied(path); - } - file.CheckFileAccess(fixedPath, FileAccess.Write); - mockFile.CreationTime = file.CreationTime; - } + if (file != null) + { + var isReadOnly = (file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + var isHidden = (file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; - var directoryPath = Path.GetDirectoryName(fixedPath); - if (directoryPath == null) - { - AddDrive(fixedPath, new MockDriveData()); - } - else if (!DirectoryExistsWithoutFixingPath(directoryPath)) + if (isReadOnly || isHidden) { - AddDirectory(directoryPath); + throw CommonExceptions.AccessDenied(path); } - - mockFile.FileVersionInfo ??= new MockFileVersionInfo(fixedPath); - - SetEntry(fixedPath, mockFile); + file.CheckFileAccess(fixedPath, FileAccess.Write); + mockFile.CreationTime = file.CreationTime; } - /// - /// Add a new file that is empty. - /// - /// A string representing the path of the new file to add. - public void AddEmptyFile(string path) + var directoryPath = Path.GetDirectoryName(fixedPath); + if (directoryPath == null) { - AddFile(path, new MockFileData("")); + AddDrive(fixedPath, new MockDriveData()); } - - /// - /// Add a new file that is empty. - /// - /// An representing the path of the new file to add. - public void AddEmptyFile(IFileInfo path) + else if (!DirectoryExistsWithoutFixingPath(directoryPath)) { - AddEmptyFile(path.FullName); - path.Refresh(); + AddDirectory(directoryPath); } - /// - /// Add a new, empty directory. - /// - /// An representing the path of the new directory to add. - public void AddDirectory(IDirectoryInfo path) - { - AddDirectory(path.FullName); - path.Refresh(); - } + mockFile.FileVersionInfo ??= new MockFileVersionInfo(fixedPath); - /// - /// Add a new file with its contents set to a specified . - /// - /// An representing the path of the new file to add. - /// The data to use for the contents of the new file. - public void AddFile(IFileInfo path, MockFileData data) - { - AddFile(path.FullName, data); - path.Refresh(); - } + SetEntry(fixedPath, mockFile); + } + + /// + /// Add a new file that is empty. + /// + /// A string representing the path of the new file to add. + public void AddEmptyFile(string path) + { + AddFile(path, new MockFileData("")); + } + + /// + /// Add a new file that is empty. + /// + /// An representing the path of the new file to add. + public void AddEmptyFile(IFileInfo path) + { + AddEmptyFile(path.FullName); + path.Refresh(); + } + + /// + /// Add a new, empty directory. + /// + /// An representing the path of the new directory to add. + public void AddDirectory(IDirectoryInfo path) + { + AddDirectory(path.FullName); + path.Refresh(); + } + + /// + /// Add a new file with its contents set to a specified . + /// + /// An representing the path of the new file to add. + /// The data to use for the contents of the new file. + public void AddFile(IFileInfo path, MockFileData data) + { + AddFile(path.FullName, data); + path.Refresh(); + } - /// - /// Gets a file. - /// - /// The path of the file to get. - /// The file. if the file does not exist. - public MockFileData GetFile(IFileInfo path) + /// + /// Gets a file. + /// + /// The path of the file to get. + /// The file. if the file does not exist. + public MockFileData GetFile(IFileInfo path) + { + return GetFile(path.FullName); + } + + /// + public void AddDirectory(string path) + { + var fixedPath = FixPath(path, true); + var separator = Path.DirectorySeparatorChar.ToString(); + + if (FileExists(fixedPath) && FileIsReadOnly(fixedPath)) { - return GetFile(path.FullName); + throw CommonExceptions.AccessDenied(fixedPath); } + var lastIndex = 0; + var isUnc = + StringOperations.StartsWith(fixedPath, @"\\") || + StringOperations.StartsWith(fixedPath, @"//"); - /// - public void AddDirectory(string path) + if (isUnc) { - var fixedPath = FixPath(path, true); - var separator = Path.DirectorySeparatorChar.ToString(); + //First, confirm they aren't trying to create '\\server\' + lastIndex = StringOperations.IndexOf(fixedPath, separator, 2); - if (FileExists(fixedPath) && FileIsReadOnly(fixedPath)) + if (lastIndex < 0) { - throw CommonExceptions.AccessDenied(fixedPath); + throw CommonExceptions.InvalidUncPath(nameof(path)); } - var lastIndex = 0; - var isUnc = - StringOperations.StartsWith(fixedPath, @"\\") || - StringOperations.StartsWith(fixedPath, @"//"); - if (isUnc) + /* + * Although CreateDirectory(@"\\server\share\") is not going to work in real code, we allow it here for the purposes of setting up test doubles. + * See PR https://github.com/TestableIO/System.IO.Abstractions/pull/90 for conversation + */ + } + + while ((lastIndex = StringOperations.IndexOf(fixedPath, separator, lastIndex + 1)) > -1) + { + var segment = fixedPath.Substring(0, lastIndex + 1); + if (!DirectoryExistsWithoutFixingPath(segment)) { - //First, confirm they aren't trying to create '\\server\' - lastIndex = StringOperations.IndexOf(fixedPath, separator, 2); + SetEntry(segment, new MockDirectoryData()); + } + } - if (lastIndex < 0) - { - throw CommonExceptions.InvalidUncPath(nameof(path)); - } + var s = StringOperations.EndsWith(fixedPath, separator) ? fixedPath : fixedPath + separator; + SetEntry(s, new MockDirectoryData()); + } - /* - * Although CreateDirectory(@"\\server\share\") is not going to work in real code, we allow it here for the purposes of setting up test doubles. - * See PR https://github.com/TestableIO/System.IO.Abstractions/pull/90 for conversation - */ + /// + public void AddFileFromEmbeddedResource(string path, Assembly resourceAssembly, string embeddedResourcePath) + { + using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(embeddedResourcePath)) + { + if (embeddedResourceStream == null) + { + throw new ArgumentException("Resource not found in assembly", nameof(embeddedResourcePath)); } - while ((lastIndex = StringOperations.IndexOf(fixedPath, separator, lastIndex + 1)) > -1) + using (var streamReader = new BinaryReader(embeddedResourceStream)) { - var segment = fixedPath.Substring(0, lastIndex + 1); - if (!DirectoryExistsWithoutFixingPath(segment)) - { - SetEntry(segment, new MockDirectoryData()); - } + var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length); + AddFile(path, new MockFileData(fileData)); } - - var s = StringOperations.EndsWith(fixedPath, separator) ? fixedPath : fixedPath + separator; - SetEntry(s, new MockDirectoryData()); } + } - /// - public void AddFileFromEmbeddedResource(string path, Assembly resourceAssembly, string embeddedResourcePath) + /// + public void AddFilesFromEmbeddedNamespace(string path, Assembly resourceAssembly, string embeddedResourcePath) + { + var matchingResources = resourceAssembly.GetManifestResourceNames().Where(f => f.StartsWith(embeddedResourcePath)); + foreach (var resource in matchingResources) { - using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(embeddedResourcePath)) + using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(resource)) + using (var streamReader = new BinaryReader(embeddedResourceStream)) { - if (embeddedResourceStream == null) - { - throw new ArgumentException("Resource not found in assembly", nameof(embeddedResourcePath)); - } - - using (var streamReader = new BinaryReader(embeddedResourceStream)) - { - var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length); - AddFile(path, new MockFileData(fileData)); - } + var fileName = resource.Substring(embeddedResourcePath.Length + 1); + var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length); + var filePath = Path.Combine(path, fileName); + AddFile(filePath, new MockFileData(fileData)); } } + } - /// - public void AddFilesFromEmbeddedNamespace(string path, Assembly resourceAssembly, string embeddedResourcePath) + /// + public void AddDrive(string name, MockDriveData mockDrive) + { + name = PathVerifier.NormalizeDriveName(name); + lock (drives) { - var matchingResources = resourceAssembly.GetManifestResourceNames().Where(f => f.StartsWith(embeddedResourcePath)); - foreach (var resource in matchingResources) - { - using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(resource)) - using (var streamReader = new BinaryReader(embeddedResourceStream)) - { - var fileName = resource.Substring(embeddedResourcePath.Length + 1); - var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length); - var filePath = Path.Combine(path, fileName); - AddFile(filePath, new MockFileData(fileData)); - } - } + drives[name] = mockDrive; } + } + + /// + public void MoveDirectory(string sourcePath, string destPath) + { + sourcePath = FixPath(sourcePath); + destPath = FixPath(destPath); + + var sourcePathSequence = sourcePath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); - /// - public void AddDrive(string name, MockDriveData mockDrive) + lock (files) { - name = PathVerifier.NormalizeDriveName(name); - lock (drives) + var affectedPaths = files.Keys + .Where(p => PathStartsWith(p, sourcePathSequence)) + .ToList(); + + foreach (var path in affectedPaths) { - drives[name] = mockDrive; + var newPath = Path.Combine(destPath, path.Substring(sourcePath.Length).TrimStart(Path.DirectorySeparatorChar)); + var entry = files[path]; + entry.Path = newPath; + files[newPath] = entry; + files.Remove(path); } } - /// - public void MoveDirectory(string sourcePath, string destPath) + bool PathStartsWith(string path, string[] minMatch) { - sourcePath = FixPath(sourcePath); - destPath = FixPath(destPath); - - var sourcePathSequence = sourcePath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); - - lock (files) + var pathSequence = path.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); + if (pathSequence.Length < minMatch.Length) { - var affectedPaths = files.Keys - .Where(p => PathStartsWith(p, sourcePathSequence)) - .ToList(); - - foreach (var path in affectedPaths) - { - var newPath = Path.Combine(destPath, path.Substring(sourcePath.Length).TrimStart(Path.DirectorySeparatorChar)); - var entry = files[path]; - entry.Path = newPath; - files[newPath] = entry; - files.Remove(path); - } + return false; } - bool PathStartsWith(string path, string[] minMatch) + for (var i = 0; i < minMatch.Length; i++) { - var pathSequence = path.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); - if (pathSequence.Length < minMatch.Length) + if (!StringOperations.Equals(minMatch[i], pathSequence[i])) { return false; } - - for (var i = 0; i < minMatch.Length; i++) - { - if (!StringOperations.Equals(minMatch[i], pathSequence[i])) - { - return false; - } - } - - return true; } + + return true; } + } - /// - public void RemoveFile(string path) - { - path = FixPath(path); + /// + public void RemoveFile(string path) + { + path = FixPath(path); - lock (files) + lock (files) + { + if (FileExists(path) && (FileIsReadOnly(path) || Directory.Exists(path) && AnyFileIsReadOnly(path))) { - if (FileExists(path) && (FileIsReadOnly(path) || Directory.Exists(path) && AnyFileIsReadOnly(path))) - { - throw CommonExceptions.AccessDenied(path); - } - - files.Remove(path); + throw CommonExceptions.AccessDenied(path); } + + files.Remove(path); } + } - /// - public bool FileExists(string path) + /// + public bool FileExists(string path) + { + if (string.IsNullOrEmpty(path)) { - if (string.IsNullOrEmpty(path)) - { - return false; - } + return false; + } - path = FixPath(path).TrimSlashes(); + path = FixPath(path).TrimSlashes(); - lock (files) - { - return files.ContainsKey(path); - } + lock (files) + { + return files.ContainsKey(path); } + } - /// - public IEnumerable AllPaths + /// + public IEnumerable AllPaths + { + get { - get + lock (files) { - lock (files) - { - return files.Keys.ToArray(); - } + return files.Keys.ToArray(); } } + } - /// - public IEnumerable AllNodes + /// + public IEnumerable AllNodes + { + get { - get + lock (files) { - lock (files) - { - return AllPaths.Where(path => !IsStartOfAnotherPath(path)).ToArray(); - } + return AllPaths.Where(path => !IsStartOfAnotherPath(path)).ToArray(); } } + } - /// - public IEnumerable AllFiles + /// + public IEnumerable AllFiles + { + get { - get + lock (files) { - lock (files) - { - return files.Where(f => !f.Value.Data.IsDirectory).Select(f => f.Key).ToArray(); - } + return files.Where(f => !f.Value.Data.IsDirectory).Select(f => f.Key).ToArray(); } } + } - /// - public IEnumerable AllDirectories + /// + public IEnumerable AllDirectories + { + get { - get + lock (files) { - lock (files) - { - return files.Where(f => f.Value.Data.IsDirectory).Select(f => f.Key).ToArray(); - } + return files.Where(f => f.Value.Data.IsDirectory).Select(f => f.Key).ToArray(); } } + } - /// - public IEnumerable AllDrives + /// + public IEnumerable AllDrives + { + get { - get + lock (drives) { - lock (drives) - { - return drives.Keys.ToArray(); - } + return drives.Keys.ToArray(); } } + } - [OnDeserializing] - private void OnDeserializing(StreamingContext c) - { - dateTimeProvider = defaultDateTimeProvider; - } + [OnDeserializing] + private void OnDeserializing(StreamingContext c) + { + dateTimeProvider = defaultDateTimeProvider; + } - private bool AnyFileIsReadOnly(string path) - { - return Directory.GetFiles(path).Any(file => FileIsReadOnly(file)); - } + private bool AnyFileIsReadOnly(string path) + { + return Directory.GetFiles(path).Any(file => FileIsReadOnly(file)); + } - private bool IsStartOfAnotherPath(string path) - { - return AllPaths.Any(otherPath => otherPath.StartsWith(path) && otherPath != path); - } + private bool IsStartOfAnotherPath(string path) + { + return AllPaths.Any(otherPath => otherPath.StartsWith(path) && otherPath != path); + } - private MockFileData GetFileWithoutFixingPath(string path) + private MockFileData GetFileWithoutFixingPath(string path) + { + lock (files) { - lock (files) - { - return files.TryGetValue(path, out var result) ? result.Data : null; - } + return files.TryGetValue(path, out var result) ? result.Data : null; } + } - private bool DirectoryExistsWithoutFixingPath(string path) + private bool DirectoryExistsWithoutFixingPath(string path) + { + lock (files) { - lock (files) - { - return files.TryGetValue(path, out var result) && result.Data.IsDirectory; - } + return files.TryGetValue(path, out var result) && result.Data.IsDirectory; } + } - private bool FileIsReadOnly(string path) - { - return (GetFile(path).Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; - } + private bool FileIsReadOnly(string path) + { + return (GetFile(path).Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + } #if FEATURE_SERIALIZABLE - [Serializable] + [Serializable] #endif - private class FileSystemEntry - { - public string Path { get; set; } - public MockFileData Data { get; set; } - } + private class FileSystemEntry + { + public string Path { get; set; } + public MockFileData Data { get; set; } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemOptions.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemOptions.cs index b356346bc..f6f19dbf3 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemOptions.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemOptions.cs @@ -1,18 +1,17 @@ -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Constructor options for +/// +public class MockFileSystemOptions { /// - /// Constructor options for + /// The with which the is initialized. /// - public class MockFileSystemOptions - { - /// - /// The with which the is initialized. - /// - public string CurrentDirectory { get; init; } = ""; + public string CurrentDirectory { get; init; } = ""; - /// - /// Flag indicating, if a temporary directory should be created. - /// - public bool CreateDefaultTempDir { get; init; } = true; - } -} + /// + /// Flag indicating, if a temporary directory should be created. + /// + public bool CreateDefaultTempDir { get; init; } = true; +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemWatcherFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemWatcherFactory.cs index a55f3ef5e..ad60ae5d5 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemWatcherFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileSystemWatcherFactory.cs @@ -1,42 +1,41 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileSystemWatcherFactory : IFileSystemWatcherFactory - { +public class MockFileSystemWatcherFactory : IFileSystemWatcherFactory +{ - /// - public MockFileSystemWatcherFactory(MockFileSystem mockFileSystem) - { - FileSystem = mockFileSystem; - } + /// + public MockFileSystemWatcherFactory(MockFileSystem mockFileSystem) + { + FileSystem = mockFileSystem; + } - /// - public IFileSystem FileSystem { get; } + /// + public IFileSystem FileSystem { get; } - /// - public IFileSystemWatcher New() - => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + /// + public IFileSystemWatcher New() + => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); - /// - public IFileSystemWatcher New(string path) - => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + /// + public IFileSystemWatcher New(string path) + => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); - /// - public IFileSystemWatcher New(string path, string filter) - => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + /// + public IFileSystemWatcher New(string path, string filter) + => throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); - /// - public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + /// + public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + { + if (fileSystemWatcher == null) { - if (fileSystemWatcher == null) - { - return null; - } - - throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); + return null; } + + throw new NotImplementedException(StringResources.Manager.GetString("FILE_SYSTEM_WATCHER_NOT_IMPLEMENTED_EXCEPTION")); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfo.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfo.cs index 1eaac4f59..16f220655 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfo.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfo.cs @@ -1,174 +1,173 @@ using System.Diagnostics; using System.Text; -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileVersionInfo : FileVersionInfoBase +public class MockFileVersionInfo : FileVersionInfoBase +{ + /// + public MockFileVersionInfo( + string fileName, + string fileVersion = null, + string productVersion = null, + string fileDescription = null, + string productName = null, + string companyName = null, + string comments = null, + string internalName = null, + bool isDebug = false, + bool isPatched = false, + bool isPrivateBuild = false, + bool isPreRelease = false, + bool isSpecialBuild = false, + string language = null, + string legalCopyright = null, + string legalTrademarks = null, + string originalFilename = null, + string privateBuild = null, + string specialBuild = null) { - /// - public MockFileVersionInfo( - string fileName, - string fileVersion = null, - string productVersion = null, - string fileDescription = null, - string productName = null, - string companyName = null, - string comments = null, - string internalName = null, - bool isDebug = false, - bool isPatched = false, - bool isPrivateBuild = false, - bool isPreRelease = false, - bool isSpecialBuild = false, - string language = null, - string legalCopyright = null, - string legalTrademarks = null, - string originalFilename = null, - string privateBuild = null, - string specialBuild = null) + FileName = fileName; + FileVersion = fileVersion; + ProductVersion = productVersion; + FileDescription = fileDescription; + ProductName = productName; + CompanyName = companyName; + Comments = comments; + InternalName = internalName; + IsDebug = isDebug; + IsPatched = isPatched; + IsPrivateBuild = isPrivateBuild; + IsPreRelease = isPreRelease; + IsSpecialBuild = isSpecialBuild; + Language = language; + LegalCopyright = legalCopyright; + LegalTrademarks = legalTrademarks; + OriginalFilename = originalFilename; + PrivateBuild = privateBuild; + SpecialBuild = specialBuild; + + if (Version.TryParse(fileVersion, out Version version)) { - FileName = fileName; - FileVersion = fileVersion; - ProductVersion = productVersion; - FileDescription = fileDescription; - ProductName = productName; - CompanyName = companyName; - Comments = comments; - InternalName = internalName; - IsDebug = isDebug; - IsPatched = isPatched; - IsPrivateBuild = isPrivateBuild; - IsPreRelease = isPreRelease; - IsSpecialBuild = isSpecialBuild; - Language = language; - LegalCopyright = legalCopyright; - LegalTrademarks = legalTrademarks; - OriginalFilename = originalFilename; - PrivateBuild = privateBuild; - SpecialBuild = specialBuild; - - if (Version.TryParse(fileVersion, out Version version)) - { - FileMajorPart = version.Major; - FileMinorPart = version.Minor; - FileBuildPart = version.Build; - FilePrivatePart = version.Revision; - } - - var parsedProductVersion = ProductVersionParser.Parse(productVersion); - - ProductMajorPart = parsedProductVersion.Major; - ProductMinorPart = parsedProductVersion.Minor; - ProductBuildPart = parsedProductVersion.Build; - ProductPrivatePart = parsedProductVersion.PrivatePart; + FileMajorPart = version.Major; + FileMinorPart = version.Minor; + FileBuildPart = version.Build; + FilePrivatePart = version.Revision; } - /// - public override string FileName { get; } + var parsedProductVersion = ProductVersionParser.Parse(productVersion); - /// - public override string FileVersion { get; } + ProductMajorPart = parsedProductVersion.Major; + ProductMinorPart = parsedProductVersion.Minor; + ProductBuildPart = parsedProductVersion.Build; + ProductPrivatePart = parsedProductVersion.PrivatePart; + } - /// - public override string ProductVersion { get; } + /// + public override string FileName { get; } - /// - public override string FileDescription { get; } + /// + public override string FileVersion { get; } - /// - public override string ProductName { get; } + /// + public override string ProductVersion { get; } - /// - public override string CompanyName { get; } + /// + public override string FileDescription { get; } - /// - public override string Comments { get; } + /// + public override string ProductName { get; } - /// - public override string InternalName { get; } + /// + public override string CompanyName { get; } - /// - public override bool IsDebug { get; } + /// + public override string Comments { get; } - /// - public override bool IsPatched { get; } + /// + public override string InternalName { get; } - /// - public override bool IsPrivateBuild { get; } + /// + public override bool IsDebug { get; } - /// - public override bool IsPreRelease { get; } + /// + public override bool IsPatched { get; } - /// - public override bool IsSpecialBuild { get; } + /// + public override bool IsPrivateBuild { get; } - /// - public override string Language { get; } + /// + public override bool IsPreRelease { get; } - /// - public override string LegalCopyright { get; } + /// + public override bool IsSpecialBuild { get; } - /// - public override string LegalTrademarks { get; } + /// + public override string Language { get; } - /// - public override string OriginalFilename { get; } + /// + public override string LegalCopyright { get; } - /// - public override string PrivateBuild { get; } + /// + public override string LegalTrademarks { get; } - /// - public override string SpecialBuild { get; } + /// + public override string OriginalFilename { get; } - /// - public override int FileMajorPart { get; } + /// + public override string PrivateBuild { get; } - /// - public override int FileMinorPart { get; } + /// + public override string SpecialBuild { get; } - /// - public override int FileBuildPart { get; } + /// + public override int FileMajorPart { get; } - /// - public override int FilePrivatePart { get; } + /// + public override int FileMinorPart { get; } - /// - public override int ProductMajorPart { get; } + /// + public override int FileBuildPart { get; } - /// - public override int ProductMinorPart { get; } + /// + public override int FilePrivatePart { get; } - /// - public override int ProductBuildPart { get; } + /// + public override int ProductMajorPart { get; } - /// - public override int ProductPrivatePart { get; } + /// + public override int ProductMinorPart { get; } - /// - public override string ToString() - { - // An initial capacity of 512 was chosen because it is large enough to cover - // the size of the static strings with enough capacity left over to cover - // average length property values. - var sb = new StringBuilder(512); - sb.Append("File: ").AppendLine(FileName); - sb.Append("InternalName: ").AppendLine(InternalName); - sb.Append("OriginalFilename: ").AppendLine(OriginalFilename); - sb.Append("FileVersion: ").AppendLine(FileVersion); - sb.Append("FileDescription: ").AppendLine(FileDescription); - sb.Append("Product: ").AppendLine(ProductName); - sb.Append("ProductVersion: ").AppendLine(ProductVersion); - sb.Append("Debug: ").AppendLine(IsDebug.ToString()); - sb.Append("Patched: ").AppendLine(IsPatched.ToString()); - sb.Append("PreRelease: ").AppendLine(IsPreRelease.ToString()); - sb.Append("PrivateBuild: ").AppendLine(IsPrivateBuild.ToString()); - sb.Append("SpecialBuild: ").AppendLine(IsSpecialBuild.ToString()); - sb.Append("Language: ").AppendLine(Language); - return sb.ToString(); - } + /// + public override int ProductBuildPart { get; } + + /// + public override int ProductPrivatePart { get; } + + /// + public override string ToString() + { + // An initial capacity of 512 was chosen because it is large enough to cover + // the size of the static strings with enough capacity left over to cover + // average length property values. + var sb = new StringBuilder(512); + sb.Append("File: ").AppendLine(FileName); + sb.Append("InternalName: ").AppendLine(InternalName); + sb.Append("OriginalFilename: ").AppendLine(OriginalFilename); + sb.Append("FileVersion: ").AppendLine(FileVersion); + sb.Append("FileDescription: ").AppendLine(FileDescription); + sb.Append("Product: ").AppendLine(ProductName); + sb.Append("ProductVersion: ").AppendLine(ProductVersion); + sb.Append("Debug: ").AppendLine(IsDebug.ToString()); + sb.Append("Patched: ").AppendLine(IsPatched.ToString()); + sb.Append("PreRelease: ").AppendLine(IsPreRelease.ToString()); + sb.Append("PrivateBuild: ").AppendLine(IsPrivateBuild.ToString()); + sb.Append("SpecialBuild: ").AppendLine(IsSpecialBuild.ToString()); + sb.Append("Language: ").AppendLine(Language); + return sb.ToString(); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfoFactory.cs index 76278f0dc..69de3f7dd 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockFileVersionInfoFactory.cs @@ -1,33 +1,32 @@ -namespace System.IO.Abstractions.TestingHelpers -{ - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockFileVersionInfoFactory : IFileVersionInfoFactory +public class MockFileVersionInfoFactory : IFileVersionInfoFactory +{ + private readonly IMockFileDataAccessor mockFileSystem; + + /// + public MockFileVersionInfoFactory(IMockFileDataAccessor mockFileSystem) { - private readonly IMockFileDataAccessor mockFileSystem; + this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); + } - /// - public MockFileVersionInfoFactory(IMockFileDataAccessor mockFileSystem) - { - this.mockFileSystem = mockFileSystem ?? throw new ArgumentNullException(nameof(mockFileSystem)); - } + /// + public IFileSystem FileSystem => mockFileSystem; - /// - public IFileSystem FileSystem => mockFileSystem; + /// + public IFileVersionInfo GetVersionInfo(string fileName) + { + MockFileData mockFileData = mockFileSystem.GetFile(fileName); - /// - public IFileVersionInfo GetVersionInfo(string fileName) + if (mockFileData != null) { - MockFileData mockFileData = mockFileSystem.GetFile(fileName); - - if (mockFileData != null) - { - return mockFileData.FileVersionInfo; - } - - throw CommonExceptions.FileNotFound(fileName); + return mockFileData.FileVersionInfo; } + + throw CommonExceptions.FileNotFound(fileName); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs index 1de4e5885..c1852f9e1 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockPath.cs @@ -2,191 +2,190 @@ using System.Globalization; using System.Linq; -namespace System.IO.Abstractions.TestingHelpers -{ - /// - /// PathWrapper calls direct to Path but all this does is string manipulation so we can inherit directly from PathWrapper as no IO is done - /// +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// PathWrapper calls direct to Path but all this does is string manipulation so we can inherit directly from PathWrapper as no IO is done +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class MockPath : PathWrapper - { - private readonly IMockFileDataAccessor mockFileDataAccessor; - private readonly string defaultTempDirectory; +public class MockPath : PathWrapper +{ + private readonly IMockFileDataAccessor mockFileDataAccessor; + private readonly string defaultTempDirectory; - /// - public MockPath(IMockFileDataAccessor mockFileDataAccessor) : this(mockFileDataAccessor, string.Empty) { } + /// + public MockPath(IMockFileDataAccessor mockFileDataAccessor) : this(mockFileDataAccessor, string.Empty) { } - /// - public MockPath(IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) : base(mockFileDataAccessor?.FileSystem) - { - this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); - this.defaultTempDirectory = !string.IsNullOrEmpty(defaultTempDirectory) ? defaultTempDirectory : base.GetTempPath(); - } + /// + public MockPath(IMockFileDataAccessor mockFileDataAccessor, string defaultTempDirectory) : base(mockFileDataAccessor?.FileSystem) + { + this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + this.defaultTempDirectory = !string.IsNullOrEmpty(defaultTempDirectory) ? defaultTempDirectory : base.GetTempPath(); + } #if FEATURE_PATH_EXISTS - /// - public override bool Exists(string path) - { - return mockFileDataAccessor.FileExists(path); - } + /// + public override bool Exists(string path) + { + return mockFileDataAccessor.FileExists(path); + } #endif - /// - public override string GetFullPath(string path) + /// + public override string GetFullPath(string path) + { + if (path == null) { - if (path == null) - { - throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); - } + throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } - if (string.IsNullOrWhiteSpace(path)) - { - throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); - } + if (string.IsNullOrWhiteSpace(path)) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); + } - path = path.Replace(AltDirectorySeparatorChar, DirectorySeparatorChar); + path = path.Replace(AltDirectorySeparatorChar, DirectorySeparatorChar); - bool isUnc = - mockFileDataAccessor.StringOperations.StartsWith(path, @"\\") || - mockFileDataAccessor.StringOperations.StartsWith(path, @"//"); + bool isUnc = + mockFileDataAccessor.StringOperations.StartsWith(path, @"\\") || + mockFileDataAccessor.StringOperations.StartsWith(path, @"//"); - string root = GetPathRoot(path); + string root = GetPathRoot(path); - bool hasTrailingSlash = path.Length > 1 && path[path.Length - 1] == DirectorySeparatorChar; + bool hasTrailingSlash = path.Length > 1 && path[path.Length - 1] == DirectorySeparatorChar; - string[] pathSegments; + string[] pathSegments; - if (root.Length == 0) - { - // relative path on the current drive or volume - path = mockFileDataAccessor.Directory.GetCurrentDirectory() + DirectorySeparatorChar + path; - pathSegments = GetSegments(path); - } - else if (isUnc) - { - // unc path - pathSegments = GetSegments(path); - if (pathSegments.Length < 2) - { - throw CommonExceptions.InvalidUncPath(nameof(path)); - } - } - else if (mockFileDataAccessor.StringOperations.Equals(@"\", root) || - mockFileDataAccessor.StringOperations.Equals(@"/", root)) - { - // absolute path on the current drive or volume - pathSegments = GetSegments(GetPathRoot(mockFileDataAccessor.Directory.GetCurrentDirectory()), path); - } - else + if (root.Length == 0) + { + // relative path on the current drive or volume + path = mockFileDataAccessor.Directory.GetCurrentDirectory() + DirectorySeparatorChar + path; + pathSegments = GetSegments(path); + } + else if (isUnc) + { + // unc path + pathSegments = GetSegments(path); + if (pathSegments.Length < 2) { - pathSegments = GetSegments(path); + throw CommonExceptions.InvalidUncPath(nameof(path)); } + } + else if (mockFileDataAccessor.StringOperations.Equals(@"\", root) || + mockFileDataAccessor.StringOperations.Equals(@"/", root)) + { + // absolute path on the current drive or volume + pathSegments = GetSegments(GetPathRoot(mockFileDataAccessor.Directory.GetCurrentDirectory()), path); + } + else + { + pathSegments = GetSegments(path); + } - // unc paths need at least two segments, the others need one segment - var isUnixRooted = mockFileDataAccessor.StringOperations.StartsWith( - mockFileDataAccessor.Directory.GetCurrentDirectory(), - "/"); + // unc paths need at least two segments, the others need one segment + var isUnixRooted = mockFileDataAccessor.StringOperations.StartsWith( + mockFileDataAccessor.Directory.GetCurrentDirectory(), + "/"); - var minPathSegments = isUnc - ? 2 - : isUnixRooted ? 0 : 1; + var minPathSegments = isUnc + ? 2 + : isUnixRooted ? 0 : 1; - var stack = new Stack(); - foreach (var segment in pathSegments) + var stack = new Stack(); + foreach (var segment in pathSegments) + { + if (mockFileDataAccessor.StringOperations.Equals("..", segment)) { - if (mockFileDataAccessor.StringOperations.Equals("..", segment)) + // only pop, if afterwards are at least the minimal amount of path segments + if (stack.Count > minPathSegments) { - // only pop, if afterwards are at least the minimal amount of path segments - if (stack.Count > minPathSegments) - { - stack.Pop(); - } - } - else if (mockFileDataAccessor.StringOperations.Equals(".", segment)) - { - // ignore . - } - else - { - stack.Push(segment); + stack.Pop(); } } - - var fullPath = string.Join(string.Format(CultureInfo.InvariantCulture, "{0}", DirectorySeparatorChar), stack.Reverse().ToArray()); - - if (hasTrailingSlash) - { - fullPath += DirectorySeparatorChar; - } - - if (isUnixRooted && !isUnc) - { - fullPath = "/" + fullPath; - } - else if (isUnixRooted) + else if (mockFileDataAccessor.StringOperations.Equals(".", segment)) { - fullPath = @"//" + fullPath; + // ignore . } - else if (isUnc) + else { - fullPath = @"\\" + fullPath; + stack.Push(segment); } - - return fullPath; } - private string[] GetSegments(params string[] paths) + var fullPath = string.Join(string.Format(CultureInfo.InvariantCulture, "{0}", DirectorySeparatorChar), stack.Reverse().ToArray()); + + if (hasTrailingSlash) { - return paths.SelectMany(path => path.Split(new[] { DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); + fullPath += DirectorySeparatorChar; } - /// - public override string GetTempFileName() + if (isUnixRooted && !isUnc) + { + fullPath = "/" + fullPath; + } + else if (isUnixRooted) { - string fileName = mockFileDataAccessor.Path.GetRandomFileName(); - string tempDir = this.GetTempPath(); + fullPath = @"//" + fullPath; + } + else if (isUnc) + { + fullPath = @"\\" + fullPath; + } + + return fullPath; + } - string fullPath = mockFileDataAccessor.Path.Combine(tempDir, fileName); + private string[] GetSegments(params string[] paths) + { + return paths.SelectMany(path => path.Split(new[] { DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); + } - mockFileDataAccessor.AddFile(fullPath, new MockFileData(string.Empty)); + /// + public override string GetTempFileName() + { + string fileName = mockFileDataAccessor.Path.GetRandomFileName(); + string tempDir = this.GetTempPath(); - return fullPath; - } + string fullPath = mockFileDataAccessor.Path.Combine(tempDir, fileName); + + mockFileDataAccessor.AddFile(fullPath, new MockFileData(string.Empty)); - /// - public override string GetTempPath() => defaultTempDirectory; + return fullPath; + } + + /// + public override string GetTempPath() => defaultTempDirectory; #if FEATURE_ADVANCED_PATH_OPERATIONS - /// - public override string GetRelativePath(string relativeTo, string path) + /// + public override string GetRelativePath(string relativeTo, string path) + { + if (relativeTo == null) { - if (relativeTo == null) - { - throw new ArgumentNullException(nameof(relativeTo), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); - } + throw new ArgumentNullException(nameof(relativeTo), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } - if (string.IsNullOrWhiteSpace(relativeTo)) - { - throw CommonExceptions.PathIsNotOfALegalForm(nameof(relativeTo)); - } + if (string.IsNullOrWhiteSpace(relativeTo)) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(relativeTo)); + } - if (path == null) - { - throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); - } + if (path == null) + { + throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); + } - if (path.Length == 0) - { - throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); - } + if (path.Length == 0) + { + throw CommonExceptions.PathIsNotOfALegalForm(nameof(path)); + } - relativeTo = GetFullPath(relativeTo); - path = GetFullPath(path); + relativeTo = GetFullPath(relativeTo); + path = GetFullPath(path); - return Path.GetRelativePath(relativeTo, path); - } -#endif + return Path.GetRelativePath(relativeTo, path); } -} +#endif +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockUnixSupport.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockUnixSupport.cs index 0b3458d83..b1a0e54c7 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockUnixSupport.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/MockUnixSupport.cs @@ -1,29 +1,28 @@ using System.Text.RegularExpressions; -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides helper methods for handling paths in a portable way. +/// +public static class MockUnixSupport { + private static readonly Regex pathTransform = new Regex(@"^[a-zA-Z]:(?.*)$"); + /// - /// Provides helper methods for handling paths in a portable way. + /// Normalizes the given path so that it works on all platfoms. /// - public static class MockUnixSupport - { - private static readonly Regex pathTransform = new Regex(@"^[a-zA-Z]:(?.*)$"); + public static string Path(string path) => path != null && IsUnixPlatform() + ? pathTransform.Replace(path, "${path}").Replace(@"\", "/") + : path; - /// - /// Normalizes the given path so that it works on all platfoms. - /// - public static string Path(string path) => path != null && IsUnixPlatform() - ? pathTransform.Replace(path, "${path}").Replace(@"\", "/") - : path; - - /// - /// Determines whether the current runtime platform is Unix. - /// - public static bool IsUnixPlatform() => IO.Path.DirectorySeparatorChar == '/'; + /// + /// Determines whether the current runtime platform is Unix. + /// + public static bool IsUnixPlatform() => IO.Path.DirectorySeparatorChar == '/'; - /// - /// Determines whether the current runtime platform is Windows. - /// - public static bool IsWindowsPlatform() => IO.Path.DirectorySeparatorChar == '\\'; - } -} + /// + /// Determines whether the current runtime platform is Windows. + /// + public static bool IsWindowsPlatform() => IO.Path.DirectorySeparatorChar == '\\'; +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/PathVerifier.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/PathVerifier.cs index d33c295e3..b56aa674c 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/PathVerifier.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/PathVerifier.cs @@ -1,168 +1,167 @@ using System.Linq; -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; + +/// +/// Provides helper methods for verifying paths. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class PathVerifier { - using XFS = MockUnixSupport; + private static readonly char[] AdditionalInvalidPathChars = { '*', '?' }; + private readonly IMockFileDataAccessor _mockFileDataAccessor; /// - /// Provides helper methods for verifying paths. + /// Creates a new verifier instance. /// -#if FEATURE_SERIALIZABLE - [Serializable] -#endif - public class PathVerifier + public PathVerifier(IMockFileDataAccessor mockFileDataAccessor) { - private static readonly char[] AdditionalInvalidPathChars = { '*', '?' }; - private readonly IMockFileDataAccessor _mockFileDataAccessor; + _mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + } - /// - /// Creates a new verifier instance. - /// - public PathVerifier(IMockFileDataAccessor mockFileDataAccessor) + /// + /// Determines whether the given path is legal. + /// + public void IsLegalAbsoluteOrRelative(string path, string paramName) + { + if (path == null) { - _mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor)); + throw new ArgumentNullException(paramName, StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); } - /// - /// Determines whether the given path is legal. - /// - public void IsLegalAbsoluteOrRelative(string path, string paramName) + if (path == string.Empty) { - if (path == null) - { - throw new ArgumentNullException(paramName, StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL")); - } - - if (path == string.Empty) - { - throw new ArgumentException("Empty file name is not legal.", paramName); - } - - if (path.Trim() == string.Empty) - { - throw CommonExceptions.PathIsNotOfALegalForm(paramName); - } - - if (XFS.IsWindowsPlatform() && !IsValidUseOfVolumeSeparatorChar(path)) - { - - throw CommonExceptions.InvalidUseOfVolumeSeparator(); - } - - if (ExtractFileName(path).IndexOfAny(_mockFileDataAccessor.Path.GetInvalidFileNameChars()) > -1) - { - throw CommonExceptions.IllegalCharactersInPath(); - } - - var filePath = ExtractFilePath(path); - - if (HasIllegalCharacters(filePath, checkAdditional: false)) - { - throw CommonExceptions.IllegalCharactersInPath(); - } + throw new ArgumentException("Empty file name is not legal.", paramName); } - private static bool IsValidUseOfVolumeSeparatorChar(string path) + if (path.Trim() == string.Empty) { - var lastVolSepIndex = path.LastIndexOf(Path.VolumeSeparatorChar); - return lastVolSepIndex == -1 || lastVolSepIndex == 1 && char.IsLetter(path[0]); + throw CommonExceptions.PathIsNotOfALegalForm(paramName); } - private string ExtractFileName(string fullFileName) + if (XFS.IsWindowsPlatform() && !IsValidUseOfVolumeSeparatorChar(path)) { - return fullFileName.Split( - _mockFileDataAccessor.Path.DirectorySeparatorChar, - _mockFileDataAccessor.Path.AltDirectorySeparatorChar).Last(); + + throw CommonExceptions.InvalidUseOfVolumeSeparator(); } - private string ExtractFilePath(string fullFileName) + if (ExtractFileName(path).IndexOfAny(_mockFileDataAccessor.Path.GetInvalidFileNameChars()) > -1) { - var extractFilePath = fullFileName.Split( - _mockFileDataAccessor.Path.DirectorySeparatorChar, - _mockFileDataAccessor.Path.AltDirectorySeparatorChar); - return string.Join(_mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(), extractFilePath.Take(extractFilePath.Length - 1)); + throw CommonExceptions.IllegalCharactersInPath(); } - /// - /// Determines whether the given path contains illegal characters. - /// - public bool HasIllegalCharacters(string path, bool checkAdditional) + var filePath = ExtractFilePath(path); + + if (HasIllegalCharacters(filePath, checkAdditional: false)) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + throw CommonExceptions.IllegalCharactersInPath(); + } + } - var invalidPathChars = _mockFileDataAccessor.Path.GetInvalidPathChars(); + private static bool IsValidUseOfVolumeSeparatorChar(string path) + { + var lastVolSepIndex = path.LastIndexOf(Path.VolumeSeparatorChar); + return lastVolSepIndex == -1 || lastVolSepIndex == 1 && char.IsLetter(path[0]); + } - if (checkAdditional) - { - return path.IndexOfAny(invalidPathChars.Concat(AdditionalInvalidPathChars).ToArray()) >= 0; - } + private string ExtractFileName(string fullFileName) + { + return fullFileName.Split( + _mockFileDataAccessor.Path.DirectorySeparatorChar, + _mockFileDataAccessor.Path.AltDirectorySeparatorChar).Last(); + } - return path.IndexOfAny(invalidPathChars) >= 0; + private string ExtractFilePath(string fullFileName) + { + var extractFilePath = fullFileName.Split( + _mockFileDataAccessor.Path.DirectorySeparatorChar, + _mockFileDataAccessor.Path.AltDirectorySeparatorChar); + return string.Join(_mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(), extractFilePath.Take(extractFilePath.Length - 1)); + } + + /// + /// Determines whether the given path contains illegal characters. + /// + public bool HasIllegalCharacters(string path, bool checkAdditional) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path)); } - /// - /// Throws an excpetion if the given path contains invalid characters. - /// - public void CheckInvalidPathChars(string path, bool checkAdditional = false) + var invalidPathChars = _mockFileDataAccessor.Path.GetInvalidPathChars(); + + if (checkAdditional) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + return path.IndexOfAny(invalidPathChars.Concat(AdditionalInvalidPathChars).ToArray()) >= 0; + } - if (HasIllegalCharacters(path, checkAdditional)) - { - throw CommonExceptions.IllegalCharactersInPath(); - } + return path.IndexOfAny(invalidPathChars) >= 0; + } + + /// + /// Throws an excpetion if the given path contains invalid characters. + /// + public void CheckInvalidPathChars(string path, bool checkAdditional = false) + { + if (path == null) + { + throw new ArgumentNullException(nameof(path)); } - /// - /// Determines the normalized drive name used for drive identification. - /// - /// Thrown if the is not a valid drive name. - public string NormalizeDriveName(string name) + if (HasIllegalCharacters(path, checkAdditional)) { - return TryNormalizeDriveName(name, out var result) - ? result - : throw new ArgumentException( - @"Object must be a root directory (""C:\"") or a drive letter (""C"")."); + throw CommonExceptions.IllegalCharactersInPath(); } + } + + /// + /// Determines the normalized drive name used for drive identification. + /// + /// Thrown if the is not a valid drive name. + public string NormalizeDriveName(string name) + { + return TryNormalizeDriveName(name, out var result) + ? result + : throw new ArgumentException( + @"Object must be a root directory (""C:\"") or a drive letter (""C"")."); + } - /// - /// Tries to determine the normalized drive name used for drive identification. - /// - public bool TryNormalizeDriveName(string name, out string result) + /// + /// Tries to determine the normalized drive name used for drive identification. + /// + public bool TryNormalizeDriveName(string name, out string result) + { + if (name == null) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + throw new ArgumentNullException(nameof(name)); + } - const string DRIVE_SEPARATOR = @":\"; + const string DRIVE_SEPARATOR = @":\"; - if (name.Length == 1 - || (name.Length == 2 && name[1] == ':') - || (name.Length == 3 && _mockFileDataAccessor.StringOperations.EndsWith(name, DRIVE_SEPARATOR))) - { - name = name[0] + DRIVE_SEPARATOR; - } - else + if (name.Length == 1 + || (name.Length == 2 && name[1] == ':') + || (name.Length == 3 && _mockFileDataAccessor.StringOperations.EndsWith(name, DRIVE_SEPARATOR))) + { + name = name[0] + DRIVE_SEPARATOR; + } + else + { + CheckInvalidPathChars(name); + name = _mockFileDataAccessor.Path.GetPathRoot(name); + + if (string.IsNullOrEmpty(name) || _mockFileDataAccessor.StringOperations.StartsWith(name, @"\\")) { - CheckInvalidPathChars(name); - name = _mockFileDataAccessor.Path.GetPathRoot(name); - - if (string.IsNullOrEmpty(name) || _mockFileDataAccessor.StringOperations.StartsWith(name, @"\\")) - { - result = null; - return false; - } + result = null; + return false; } - - result = name; - return true; } + + result = name; + return true; } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/ProductVersionParser.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/ProductVersionParser.cs index 011de195c..8f5d2459c 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/ProductVersionParser.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/ProductVersionParser.cs @@ -1,99 +1,98 @@ using System.Reflection; using System.Text.RegularExpressions; -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides functionality to parse a product version string into its major, minor, build, and private parts. +/// +internal static class ProductVersionParser { /// - /// Provides functionality to parse a product version string into its major, minor, build, and private parts. + /// Parses a product version string and extracts the numeric values for the major, minor, build, and private parts, + /// mimicking the behavior of the attribute. /// - internal static class ProductVersionParser + /// The product version string to parse. + /// + /// A object containing the parsed major, minor, build, and private parts. + /// If the input is invalid, returns a with all parts set to 0. + /// + /// + /// The method splits the input string into segments separated by dots ('.') and attempts to extract + /// the leading numeric value from each segment. A maximum of 4 segments are processed; if more than + /// 4 segments are present, all segments are ignored. Additionally, if a segment does not contain + /// a valid numeric part at its start or it contains more than just a number, the rest of the segments are ignored. + /// + public static ProductVersion Parse(string productVersion) { - /// - /// Parses a product version string and extracts the numeric values for the major, minor, build, and private parts, - /// mimicking the behavior of the attribute. - /// - /// The product version string to parse. - /// - /// A object containing the parsed major, minor, build, and private parts. - /// If the input is invalid, returns a with all parts set to 0. - /// - /// - /// The method splits the input string into segments separated by dots ('.') and attempts to extract - /// the leading numeric value from each segment. A maximum of 4 segments are processed; if more than - /// 4 segments are present, all segments are ignored. Additionally, if a segment does not contain - /// a valid numeric part at its start or it contains more than just a number, the rest of the segments are ignored. - /// - public static ProductVersion Parse(string productVersion) + if (string.IsNullOrWhiteSpace(productVersion)) { - if (string.IsNullOrWhiteSpace(productVersion)) - { - return new(); - } + return new(); + } - var segments = productVersion.Split('.'); - if (segments.Length > 4) - { - // if more than 4 segments are present, all segments are ignored - return new(); - } + var segments = productVersion.Split('.'); + if (segments.Length > 4) + { + // if more than 4 segments are present, all segments are ignored + return new(); + } - var regex = new Regex(@"^\d+"); + var regex = new Regex(@"^\d+"); - int[] parts = new int[4]; + int[] parts = new int[4]; - for (int i = 0; i < segments.Length; i++) + for (int i = 0; i < segments.Length; i++) + { + var match = regex.Match(segments[i]); + if (match.Success && int.TryParse(match.Value, out int number)) { - var match = regex.Match(segments[i]); - if (match.Success && int.TryParse(match.Value, out int number)) - { - parts[i] = number; + parts[i] = number; - if (match.Value != segments[i]) - { - // when a segment contains more than a number, the rest of the segments are ignored - break; - } - } - else + if (match.Value != segments[i]) { - // when a segment is not valid, the rest of the segments are ignored + // when a segment contains more than a number, the rest of the segments are ignored break; } } - - return new() + else { - Major = parts[0], - Minor = parts[1], - Build = parts[2], - PrivatePart = parts[3] - }; + // when a segment is not valid, the rest of the segments are ignored + break; + } } + return new() + { + Major = parts[0], + Minor = parts[1], + Build = parts[2], + PrivatePart = parts[3] + }; + } + + /// + /// Represents a product version with numeric parts for major, minor, build, and private versions. + /// + public class ProductVersion + { /// - /// Represents a product version with numeric parts for major, minor, build, and private versions. + /// Gets the major part of the version number /// - public class ProductVersion - { - /// - /// Gets the major part of the version number - /// - public int Major { get; init; } + public int Major { get; init; } - /// - /// Gets the minor part of the version number - /// - public int Minor { get; init; } + /// + /// Gets the minor part of the version number + /// + public int Minor { get; init; } - /// - /// Gets the build part of the version number - /// - public int Build { get; init; } + /// + /// Gets the build part of the version number + /// + public int Build { get; init; } - /// - /// Gets the private part of the version number - /// - public int PrivatePart { get; init; } - } + /// + /// Gets the private part of the version number + /// + public int PrivatePart { get; init; } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringExtensions.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringExtensions.cs index a133550e2..69db7f553 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringExtensions.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringExtensions.cs @@ -3,122 +3,121 @@ using System.Linq; using System.Text; -namespace System.IO.Abstractions.TestingHelpers -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers; + +using XFS = MockUnixSupport; - internal static class StringExtensions +internal static class StringExtensions +{ + [Pure] + public static string[] SplitLines(this string input) { - [Pure] - public static string[] SplitLines(this string input) + var list = new List(); + using (var reader = new StringReader(input)) { - var list = new List(); - using (var reader = new StringReader(input)) + string str; + while ((str = reader.ReadLine()) != null) { - string str; - while ((str = reader.ReadLine()) != null) - { - list.Add(str); - } + list.Add(str); } + } + + return list.ToArray(); + } - return list.ToArray(); + [Pure] + public static string Replace(this string source, string oldValue, string newValue, StringComparison comparisonType) + { + // from http://stackoverflow.com/a/22565605 with some adaptions + if (string.IsNullOrEmpty(oldValue)) + { + throw new ArgumentNullException(nameof(oldValue)); } - [Pure] - public static string Replace(this string source, string oldValue, string newValue, StringComparison comparisonType) + if (source.Length == 0) { - // from http://stackoverflow.com/a/22565605 with some adaptions - if (string.IsNullOrEmpty(oldValue)) - { - throw new ArgumentNullException(nameof(oldValue)); - } + return source; + } - if (source.Length == 0) - { - return source; - } + if (newValue == null) + { + newValue = string.Empty; + } - if (newValue == null) - { - newValue = string.Empty; - } + var result = new StringBuilder(); + int startingPos = 0; + int nextMatch; + while ((nextMatch = source.IndexOf(oldValue, startingPos, comparisonType)) > -1) + { + result.Append(source, startingPos, nextMatch - startingPos); + result.Append(newValue); + startingPos = nextMatch + oldValue.Length; + } - var result = new StringBuilder(); - int startingPos = 0; - int nextMatch; - while ((nextMatch = source.IndexOf(oldValue, startingPos, comparisonType)) > -1) - { - result.Append(source, startingPos, nextMatch - startingPos); - result.Append(newValue); - startingPos = nextMatch + oldValue.Length; - } + result.Append(source, startingPos, source.Length - startingPos); - result.Append(source, startingPos, source.Length - startingPos); + return result.ToString(); + } - return result.ToString(); + [Pure] + public static string TrimSlashes(this string path) + { + if (string.IsNullOrEmpty(path)) + { + return path; } - [Pure] - public static string TrimSlashes(this string path) + var trimmed = path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + + if (XFS.IsUnixPlatform() + && (path[0] == Path.DirectorySeparatorChar || path[0] == Path.AltDirectorySeparatorChar) + && trimmed == "") { - if (string.IsNullOrEmpty(path)) - { - return path; - } + return Path.DirectorySeparatorChar.ToString(); + } - var trimmed = path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + if (XFS.IsWindowsPlatform() + && trimmed.Length == 2 + && char.IsLetter(trimmed[0]) + && trimmed[1] == ':') + { + return trimmed + Path.DirectorySeparatorChar; + } - if (XFS.IsUnixPlatform() - && (path[0] == Path.DirectorySeparatorChar || path[0] == Path.AltDirectorySeparatorChar) - && trimmed == "") - { - return Path.DirectorySeparatorChar.ToString(); - } + return trimmed; + } - if (XFS.IsWindowsPlatform() - && trimmed.Length == 2 - && char.IsLetter(trimmed[0]) - && trimmed[1] == ':') - { - return trimmed + Path.DirectorySeparatorChar; - } + [Pure] + public static string NormalizeSlashes(this string path) + { + path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); + var sep = Path.DirectorySeparatorChar.ToString(); + var doubleSep = sep + sep; - return trimmed; - } + var prefixSeps = new string(path.TakeWhile(c => c == Path.DirectorySeparatorChar).ToArray()); + path = path.Substring(prefixSeps.Length); - [Pure] - public static string NormalizeSlashes(this string path) + // UNC Paths start with double slash but no reason + // to have more than 2 slashes at the start of a path + if (XFS.IsWindowsPlatform() && prefixSeps.Length >= 2) + { + prefixSeps = prefixSeps.Substring(0, 2); + } + else if (prefixSeps.Length > 1) { - path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); - var sep = Path.DirectorySeparatorChar.ToString(); - var doubleSep = sep + sep; + prefixSeps = prefixSeps.Substring(0, 1); + } - var prefixSeps = new string(path.TakeWhile(c => c == Path.DirectorySeparatorChar).ToArray()); - path = path.Substring(prefixSeps.Length); + while (true) + { + var newPath = path.Replace(doubleSep, sep); - // UNC Paths start with double slash but no reason - // to have more than 2 slashes at the start of a path - if (XFS.IsWindowsPlatform() && prefixSeps.Length >= 2) + if (path == newPath) { - prefixSeps = prefixSeps.Substring(0, 2); + return prefixSeps + path; } - else if (prefixSeps.Length > 1) - { - prefixSeps = prefixSeps.Substring(0, 1); - } - - while (true) - { - var newPath = path.Replace(doubleSep, sep); - if (path == newPath) - { - return prefixSeps + path; - } - - path = newPath; - } + path = newPath; } } } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringOperations.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringOperations.cs index a815a00de..9b20386cc 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringOperations.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringOperations.cs @@ -1,77 +1,75 @@ -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Provides operations against path strings dependeing on the case-senstivity of the runtime platform. +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class StringOperations { + private readonly bool caseSensitive; + private readonly StringComparison comparison; /// - /// Provides operations against path strings dependeing on the case-senstivity of the runtime platform. + /// Creates a new instance. /// -#if FEATURE_SERIALIZABLE - [Serializable] -#endif - public class StringOperations + public StringOperations(bool caseSensitive) { - private readonly bool caseSensitive; - private readonly StringComparison comparison; - - /// - /// Creates a new instance. - /// - public StringOperations(bool caseSensitive) - { - this.caseSensitive = caseSensitive; - comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; - } - - /// - /// Provides a string comparer. - /// - public StringComparer Comparer => caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; - /// - /// Determines whether the given string starts with the given prefix. - /// - public bool StartsWith(string s, string prefix) => s.StartsWith(prefix, comparison); - /// - /// Determines whether the given string ends with the given suffix. - /// - public bool EndsWith(string s, string suffix) => s.EndsWith(suffix, comparison); - /// - /// Determines whether the given strings are equal. - /// - public bool Equals(string x, string y) => string.Equals(x, y, comparison); - /// - /// Determines whether the given characters are equal. - /// - public bool Equals(char x, char y) => caseSensitive ? x == y : char.ToUpper(x) == char.ToUpper(y); - /// - /// Determines the index of the given substring in the string. - /// - public int IndexOf(string s, string substring) => s.IndexOf(substring, comparison); - /// - /// Determines the index of the given substring in the string. - /// - public int IndexOf(string s, string substring, int startIndex) => s.IndexOf(substring, startIndex, comparison); - /// - /// Determines whether the given string contains the given substring. - /// - public bool Contains(string s, string substring) => s.IndexOf(substring, comparison) >= 0; - /// - /// Replaces a given value by a new value. - /// - public string Replace(string s, string oldValue, string newValue) => s.Replace(oldValue, newValue, comparison); - /// - /// Provides the lower-case representation of the given character. - /// - public char ToLower(char c) => caseSensitive ? c : char.ToLower(c); - /// - /// Provides the upper-case representation of the given character. - /// - public char ToUpper(char c) => caseSensitive ? c : char.ToUpper(c); - /// - /// Provides the lower-case representation of the given string. - /// - public string ToLower(string s) => caseSensitive ? s : s.ToLower(); - /// - /// Provides the upper-case representation of the given string. - /// - public string ToUpper(string s) => caseSensitive ? s : s.ToUpper(); + this.caseSensitive = caseSensitive; + comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; } -} + + /// + /// Provides a string comparer. + /// + public StringComparer Comparer => caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; + /// + /// Determines whether the given string starts with the given prefix. + /// + public bool StartsWith(string s, string prefix) => s.StartsWith(prefix, comparison); + /// + /// Determines whether the given string ends with the given suffix. + /// + public bool EndsWith(string s, string suffix) => s.EndsWith(suffix, comparison); + /// + /// Determines whether the given strings are equal. + /// + public bool Equals(string x, string y) => string.Equals(x, y, comparison); + /// + /// Determines whether the given characters are equal. + /// + public bool Equals(char x, char y) => caseSensitive ? x == y : char.ToUpper(x) == char.ToUpper(y); + /// + /// Determines the index of the given substring in the string. + /// + public int IndexOf(string s, string substring) => s.IndexOf(substring, comparison); + /// + /// Determines the index of the given substring in the string. + /// + public int IndexOf(string s, string substring, int startIndex) => s.IndexOf(substring, startIndex, comparison); + /// + /// Determines whether the given string contains the given substring. + /// + public bool Contains(string s, string substring) => s.IndexOf(substring, comparison) >= 0; + /// + /// Replaces a given value by a new value. + /// + public string Replace(string s, string oldValue, string newValue) => s.Replace(oldValue, newValue, comparison); + /// + /// Provides the lower-case representation of the given character. + /// + public char ToLower(char c) => caseSensitive ? c : char.ToLower(c); + /// + /// Provides the upper-case representation of the given character. + /// + public char ToUpper(char c) => caseSensitive ? c : char.ToUpper(c); + /// + /// Provides the lower-case representation of the given string. + /// + public string ToLower(string s) => caseSensitive ? s : s.ToLower(); + /// + /// Provides the upper-case representation of the given string. + /// + public string ToUpper(string s) => caseSensitive ? s : s.ToUpper(); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringResources.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringResources.cs index 1874e40d7..60373fd02 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringResources.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/StringResources.cs @@ -1,12 +1,11 @@ using System.Reflection; using System.Resources; -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +internal static class StringResources { - internal static class StringResources - { - public static ResourceManager Manager { get; } = new ResourceManager( - $"{typeof(StringResources).Namespace}.Properties.Resources", - typeof(StringResources).GetTypeInfo().Assembly); - } -} + public static ResourceManager Manager { get; } = new ResourceManager( + $"{typeof(StringResources).Namespace}.Properties.Resources", + typeof(StringResources).GetTypeInfo().Assembly); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.TestingHelpers/TimeAdjustments.cs b/src/TestableIO.System.IO.Abstractions.TestingHelpers/TimeAdjustments.cs index 321de416e..cc7ed1532 100644 --- a/src/TestableIO.System.IO.Abstractions.TestingHelpers/TimeAdjustments.cs +++ b/src/TestableIO.System.IO.Abstractions.TestingHelpers/TimeAdjustments.cs @@ -1,30 +1,29 @@ -namespace System.IO.Abstractions.TestingHelpers +namespace System.IO.Abstractions.TestingHelpers; + +/// +/// Flags indicating which times to adjust for a . +/// +[Flags] +public enum TimeAdjustments { /// - /// Flags indicating which times to adjust for a . + /// Adjusts no times on the /// - [Flags] - public enum TimeAdjustments - { - /// - /// Adjusts no times on the - /// - None = 0, - /// - /// Adjusts the - /// - CreationTime = 1 << 0, - /// - /// Adjusts the - /// - LastAccessTime = 1 << 1, - /// - /// Adjusts the - /// - LastWriteTime = 1 << 2, - /// - /// Adjusts all times on the - /// - All = ~0 - } -} + None = 0, + /// + /// Adjusts the + /// + CreationTime = 1 << 0, + /// + /// Adjusts the + /// + LastAccessTime = 1 << 1, + /// + /// Adjusts the + /// + LastWriteTime = 1 << 2, + /// + /// Adjusts all times on the + /// + All = ~0 +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/Converters.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/Converters.cs index 8092cda01..39398177a 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/Converters.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/Converters.cs @@ -2,60 +2,59 @@ using System.Globalization; using System.Linq; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +internal static class Converters { - internal static class Converters - { - internal static IEnumerable WrapFileSystemInfos(this IEnumerable input, IFileSystem fileSystem) - => input.Select(info => WrapFileSystemInfo(fileSystem, info)); + internal static IEnumerable WrapFileSystemInfos(this IEnumerable input, IFileSystem fileSystem) + => input.Select(info => WrapFileSystemInfo(fileSystem, info)); - internal static FileSystemInfoBase[] WrapFileSystemInfos(this FileSystemInfo[] input, IFileSystem fileSystem) - => input.Select(info => WrapFileSystemInfo(fileSystem, info)).ToArray(); + internal static FileSystemInfoBase[] WrapFileSystemInfos(this FileSystemInfo[] input, IFileSystem fileSystem) + => input.Select(info => WrapFileSystemInfo(fileSystem, info)).ToArray(); - internal static FileSystemInfoBase WrapFileSystemInfo(this FileSystemInfo input, IFileSystem fileSystem) - => WrapFileSystemInfo(fileSystem, input); + internal static FileSystemInfoBase WrapFileSystemInfo(this FileSystemInfo input, IFileSystem fileSystem) + => WrapFileSystemInfo(fileSystem, input); - internal static IEnumerable WrapDirectories(this IEnumerable input, IFileSystem fileSystem) - => input.Select(info => WrapDirectoryInfo(fileSystem, info)); + internal static IEnumerable WrapDirectories(this IEnumerable input, IFileSystem fileSystem) + => input.Select(info => WrapDirectoryInfo(fileSystem, info)); - internal static DirectoryInfoBase[] WrapDirectories(this DirectoryInfo[] input, IFileSystem fileSystem) - => input.Select(info => WrapDirectoryInfo(fileSystem, info)).ToArray(); + internal static DirectoryInfoBase[] WrapDirectories(this DirectoryInfo[] input, IFileSystem fileSystem) + => input.Select(info => WrapDirectoryInfo(fileSystem, info)).ToArray(); - internal static IEnumerable WrapFiles(this IEnumerable input, IFileSystem fileSystem) - => input.Select(info => WrapFileInfo(fileSystem, info)); + internal static IEnumerable WrapFiles(this IEnumerable input, IFileSystem fileSystem) + => input.Select(info => WrapFileInfo(fileSystem, info)); - internal static FileInfoBase[] WrapFiles(this FileInfo[] input, IFileSystem fileSystem) - => input.Select(info => WrapFileInfo(fileSystem, info)).ToArray(); + internal static FileInfoBase[] WrapFiles(this FileInfo[] input, IFileSystem fileSystem) + => input.Select(info => WrapFileInfo(fileSystem, info)).ToArray(); - private static FileSystemInfoBase WrapFileSystemInfo(IFileSystem fileSystem, FileSystemInfo item) + private static FileSystemInfoBase WrapFileSystemInfo(IFileSystem fileSystem, FileSystemInfo item) + { + if (item is null) { - if (item is null) - { - return null; - } - - if (item is FileInfo fileInfo) - { - return WrapFileInfo(fileSystem, fileInfo); - } - else if (item is DirectoryInfo directoryInfo) - { - return WrapDirectoryInfo(fileSystem, directoryInfo); - } - else - { - throw new NotImplementedException(string.Format( - CultureInfo.InvariantCulture, - "The type {0} is not recognized by the System.IO.Abstractions library.", - item.GetType().AssemblyQualifiedName - )); - } + return null; } - private static FileInfoBase WrapFileInfo(IFileSystem fileSystem, FileInfo f) - => f is null ? null : new FileInfoWrapper(fileSystem, f); - - private static DirectoryInfoBase WrapDirectoryInfo(IFileSystem fileSystem, DirectoryInfo d) - => d is null ? null : new DirectoryInfoWrapper(fileSystem, d); + if (item is FileInfo fileInfo) + { + return WrapFileInfo(fileSystem, fileInfo); + } + else if (item is DirectoryInfo directoryInfo) + { + return WrapDirectoryInfo(fileSystem, directoryInfo); + } + else + { + throw new NotImplementedException(string.Format( + CultureInfo.InvariantCulture, + "The type {0} is not recognized by the System.IO.Abstractions library.", + item.GetType().AssemblyQualifiedName + )); + } } -} + + private static FileInfoBase WrapFileInfo(IFileSystem fileSystem, FileInfo f) + => f is null ? null : new FileInfoWrapper(fileSystem, f); + + private static DirectoryInfoBase WrapDirectoryInfo(IFileSystem fileSystem, DirectoryInfo d) + => d is null ? null : new DirectoryInfoWrapper(fileSystem, d); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryAclExtensions.cs index b1052dd8d..248442c63 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryAclExtensions.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryAclExtensions.cs @@ -1,67 +1,66 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class DirectoryAclExtensions { - /// - /// ACL (access control list) extension methods for . - /// - public static class DirectoryAclExtensions - { #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static void CreateDirectory(this IDirectory directory, - string path, - DirectorySecurity directorySecurity) - { - IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); - directoryInfo.Create(directorySecurity); - } + [SupportedOSPlatform("windows")] + public static void CreateDirectory(this IDirectory directory, + string path, + DirectorySecurity directorySecurity) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + directoryInfo.Create(directorySecurity); + } #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static DirectorySecurity GetAccessControl( - this IDirectory directory, string path) - { - IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); - return directoryInfo.GetAccessControl(); - } + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectory directory, string path) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + return directoryInfo.GetAccessControl(); + } #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static DirectorySecurity GetAccessControl( - this IDirectory directory, - string path, - AccessControlSections includeSections) - { - IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); - return directoryInfo.GetAccessControl(includeSections); - } + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectory directory, + string path, + AccessControlSections includeSections) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + return directoryInfo.GetAccessControl(includeSections); + } #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static void SetAccessControl(this IDirectory directory, - string path, - DirectorySecurity directorySecurity) - { - IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); - directoryInfo.SetAccessControl(directorySecurity); - } + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IDirectory directory, + string path, + DirectorySecurity directorySecurity) + { + IDirectoryInfo directoryInfo = directory.FileSystem.DirectoryInfo.New(path); + directoryInfo.SetAccessControl(directorySecurity); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryBase.cs index 5db0fef8b..c8583b3c7 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryBase.cs @@ -1,31 +1,31 @@ using System.Collections.Generic; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class DirectoryBase : IDirectory +public abstract class DirectoryBase : IDirectory +{ + /// + /// Base class for calling static methods of + /// + protected DirectoryBase(IFileSystem fileSystem) { - /// - /// Base class for calling static methods of - /// - protected DirectoryBase(IFileSystem fileSystem) - { - FileSystem = fileSystem; - } + FileSystem = fileSystem; + } - [Obsolete("This constructor only exists to support mocking libraries.", error: true)] - internal DirectoryBase() { } + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal DirectoryBase() { } - /// - /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. - /// - public IFileSystem FileSystem { get; } + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } - /// - public abstract IDirectoryInfo CreateDirectory(string path); + /// + public abstract IDirectoryInfo CreateDirectory(string path); #if FEATURE_UNIX_FILE_MODE /// @@ -41,63 +41,63 @@ internal DirectoryBase() { } /// public abstract IDirectoryInfo CreateTempSubdirectory(string prefix = null); #endif - /// - public abstract void Delete(string path); + /// + public abstract void Delete(string path); - /// - public abstract void Delete(string path, bool recursive); + /// + public abstract void Delete(string path, bool recursive); - /// - public abstract bool Exists(string path); + /// + public abstract bool Exists(string path); - /// - public abstract DateTime GetCreationTime(string path); + /// + public abstract DateTime GetCreationTime(string path); - /// - public abstract DateTime GetCreationTimeUtc(string path); + /// + public abstract DateTime GetCreationTimeUtc(string path); - /// - public abstract string GetCurrentDirectory(); + /// + public abstract string GetCurrentDirectory(); - /// - public abstract string[] GetDirectories(string path); + /// + public abstract string[] GetDirectories(string path); - /// - public abstract string[] GetDirectories(string path, string searchPattern); + /// + public abstract string[] GetDirectories(string path, string searchPattern); - /// - public abstract string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); + /// + public abstract string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// public abstract string[] GetDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract string GetDirectoryRoot(string path); + /// + public abstract string GetDirectoryRoot(string path); - /// - public abstract string[] GetFiles(string path); + /// + public abstract string[] GetFiles(string path); - /// - public abstract string[] GetFiles(string path, string searchPattern); + /// + public abstract string[] GetFiles(string path, string searchPattern); - /// - public abstract string[] GetFiles(string path, string searchPattern, SearchOption searchOption); + /// + public abstract string[] GetFiles(string path, string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// public abstract string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract string[] GetFileSystemEntries(string path); + /// + public abstract string[] GetFileSystemEntries(string path); - /// - public abstract string[] GetFileSystemEntries(string path, string searchPattern); + /// + public abstract string[] GetFileSystemEntries(string path, string searchPattern); - /// - public abstract string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption); + /// + public abstract string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// @@ -105,93 +105,92 @@ public abstract string[] GetFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract DateTime GetLastAccessTime(string path); + /// + public abstract DateTime GetLastAccessTime(string path); - /// - public abstract DateTime GetLastAccessTimeUtc(string path); + /// + public abstract DateTime GetLastAccessTimeUtc(string path); - /// - public abstract DateTime GetLastWriteTime(string path); + /// + public abstract DateTime GetLastWriteTime(string path); - /// - public abstract DateTime GetLastWriteTimeUtc(string path); + /// + public abstract DateTime GetLastWriteTimeUtc(string path); - /// - public abstract string[] GetLogicalDrives(); + /// + public abstract string[] GetLogicalDrives(); - /// - public abstract IDirectoryInfo GetParent(string path); + /// + public abstract IDirectoryInfo GetParent(string path); - /// - public abstract void Move(string sourceDirName, string destDirName); + /// + public abstract void Move(string sourceDirName, string destDirName); #if FEATURE_CREATE_SYMBOLIC_LINK /// public abstract IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); #endif - /// - public abstract void SetCreationTime(string path, DateTime creationTime); + /// + public abstract void SetCreationTime(string path, DateTime creationTime); - /// - public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); + /// + public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); - /// - public abstract void SetCurrentDirectory(string path); + /// + public abstract void SetCurrentDirectory(string path); - /// - public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); + /// + public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); - /// - public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); + /// + public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); - /// - public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); + /// + public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); - /// - public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); + /// + public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); - /// - public abstract IEnumerable EnumerateDirectories(string path); + /// + public abstract IEnumerable EnumerateDirectories(string path); - /// - public abstract IEnumerable EnumerateDirectories(string path, string searchPattern); + /// + public abstract IEnumerable EnumerateDirectories(string path, string searchPattern); - /// - public abstract IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption); + /// + public abstract IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// public abstract IEnumerable EnumerateDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract IEnumerable EnumerateFiles(string path); + /// + public abstract IEnumerable EnumerateFiles(string path); - /// - public abstract IEnumerable EnumerateFiles(string path, string searchPattern); + /// + public abstract IEnumerable EnumerateFiles(string path, string searchPattern); - /// - public abstract IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption); + /// + public abstract IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// public abstract IEnumerable EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract IEnumerable EnumerateFileSystemEntries(string path); + /// + public abstract IEnumerable EnumerateFileSystemEntries(string path); - /// - public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); + /// + public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern); - /// - public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption); + /// + public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// public abstract IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions); #endif - } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoAclExtensions.cs index 743ff7545..81c38f155 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoAclExtensions.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoAclExtensions.cs @@ -1,87 +1,86 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class DirectoryInfoAclExtensions { - /// - /// ACL (access control list) extension methods for . - /// - public static class DirectoryInfoAclExtensions - { #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static void Create(this IDirectoryInfo directoryInfo, - DirectorySecurity directorySecurity) + [SupportedOSPlatform("windows")] + public static void Create(this IDirectoryInfo directoryInfo, + DirectorySecurity directorySecurity) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + if (aclSupport == null) { - IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; - if (aclSupport == null) - { - throw new NotSupportedException("The directory info does not support ACL extensions"); - } - - directoryInfo.Create(); - aclSupport.SetAccessControl(directorySecurity); + throw new NotSupportedException("The directory info does not support ACL extensions"); } + directoryInfo.Create(); + aclSupport.SetAccessControl(directorySecurity); + } + #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static DirectorySecurity GetAccessControl( - this IDirectoryInfo directoryInfo) + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectoryInfo directoryInfo) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + var directorySecurity = aclSupport?.GetAccessControl() as DirectorySecurity; + if (aclSupport == null || directorySecurity == null) { - IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; - var directorySecurity = aclSupport?.GetAccessControl() as DirectorySecurity; - if (aclSupport == null || directorySecurity == null) - { - throw new NotSupportedException("The directory info does not support ACL extensions"); - } - - return directorySecurity; + throw new NotSupportedException("The directory info does not support ACL extensions"); } + return directorySecurity; + } + #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static DirectorySecurity GetAccessControl( - this IDirectoryInfo directoryInfo, - AccessControlSections includeSections) + [SupportedOSPlatform("windows")] + public static DirectorySecurity GetAccessControl( + this IDirectoryInfo directoryInfo, + AccessControlSections includeSections) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + var directorySecurity = aclSupport?.GetAccessControl((IFileSystemAclSupport.AccessControlSections) includeSections) as DirectorySecurity; + if (aclSupport == null || directorySecurity == null) { - IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; - var directorySecurity = aclSupport?.GetAccessControl((IFileSystemAclSupport.AccessControlSections) includeSections) as DirectorySecurity; - if (aclSupport == null || directorySecurity == null) - { - throw new NotSupportedException("The directory info does not support ACL extensions"); - } - - return directorySecurity; + throw new NotSupportedException("The directory info does not support ACL extensions"); } + return directorySecurity; + } + #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static void SetAccessControl(this IDirectoryInfo directoryInfo, - DirectorySecurity directorySecurity) + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IDirectoryInfo directoryInfo, + DirectorySecurity directorySecurity) + { + IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; + if (aclSupport == null) { - IFileSystemAclSupport aclSupport = directoryInfo as IFileSystemAclSupport; - if (aclSupport == null) - { - throw new NotSupportedException("The directory info does not support ACL extensions"); - } - - aclSupport.SetAccessControl(directorySecurity); + throw new NotSupportedException("The directory info does not support ACL extensions"); } + + aclSupport.SetAccessControl(directorySecurity); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoBase.cs index 48cc7b025..59e21cd0d 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoBase.cs @@ -1,136 +1,135 @@ using System.Collections.Generic; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class DirectoryInfoBase : FileSystemInfoBase, IDirectoryInfo +public abstract class DirectoryInfoBase : FileSystemInfoBase, IDirectoryInfo +{ + /// + /// Base class for calling methods of + /// + protected DirectoryInfoBase(IFileSystem fileSystem) : base(fileSystem) { - /// - /// Base class for calling methods of - /// - protected DirectoryInfoBase(IFileSystem fileSystem) : base(fileSystem) - { - } + } - [Obsolete("This constructor only exists to support mocking libraries.", error: true)] - internal DirectoryInfoBase() { } + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal DirectoryInfoBase() { } - /// - public abstract void Create(); + /// + public abstract void Create(); - /// - public abstract IDirectoryInfo CreateSubdirectory(string path); + /// + public abstract IDirectoryInfo CreateSubdirectory(string path); - /// - public abstract void Delete(bool recursive); + /// + public abstract void Delete(bool recursive); - /// - public abstract IEnumerable EnumerateDirectories(); + /// + public abstract IEnumerable EnumerateDirectories(); - /// - public abstract IEnumerable EnumerateDirectories(string searchPattern); + /// + public abstract IEnumerable EnumerateDirectories(string searchPattern); - /// - public abstract IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption); + /// + public abstract IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS - /// - public abstract IEnumerable EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions); + /// + public abstract IEnumerable EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract IEnumerable EnumerateFiles(); + /// + public abstract IEnumerable EnumerateFiles(); - /// - public abstract IEnumerable EnumerateFiles(string searchPattern); + /// + public abstract IEnumerable EnumerateFiles(string searchPattern); - /// - public abstract IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption); + /// + public abstract IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS - /// - public abstract IEnumerable EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions); + /// + public abstract IEnumerable EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract IEnumerable EnumerateFileSystemInfos(); + /// + public abstract IEnumerable EnumerateFileSystemInfos(); - /// - public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern); + /// + public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern); - /// - public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption); + /// + public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS - /// - public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); + /// + public abstract IEnumerable EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract IDirectoryInfo[] GetDirectories(); + /// + public abstract IDirectoryInfo[] GetDirectories(); - /// - public abstract IDirectoryInfo[] GetDirectories(string searchPattern); + /// + public abstract IDirectoryInfo[] GetDirectories(string searchPattern); - /// - public abstract IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption); + /// + public abstract IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS - /// - public abstract IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions); + /// + public abstract IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract IFileInfo[] GetFiles(); + /// + public abstract IFileInfo[] GetFiles(); - /// - public abstract IFileInfo[] GetFiles(string searchPattern); + /// + public abstract IFileInfo[] GetFiles(string searchPattern); - /// - public abstract IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption); + /// + public abstract IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS - /// - public abstract IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions); + /// + public abstract IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract IFileSystemInfo[] GetFileSystemInfos(); + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(); - /// - public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern); + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern); - /// - public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption); + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS - /// - public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); + /// + public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); #endif - /// - public abstract void MoveTo(string destDirName); + /// + public abstract void MoveTo(string destDirName); - /// - public abstract IDirectoryInfo Parent { get; } + /// + public abstract IDirectoryInfo Parent { get; } - /// - public abstract IDirectoryInfo Root { get; } + /// + public abstract IDirectoryInfo Root { get; } - /// - /// Implicitly converts a to a . - /// - public static implicit operator DirectoryInfoBase(DirectoryInfo directoryInfo) + /// + /// Implicitly converts a to a . + /// + public static implicit operator DirectoryInfoBase(DirectoryInfo directoryInfo) + { + if (directoryInfo == null) { - if (directoryInfo == null) - { - return null; - } - return new DirectoryInfoWrapper(new FileSystem(), directoryInfo); + return null; } + return new DirectoryInfoWrapper(new FileSystem(), directoryInfo); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoFactory.cs index dc872bf16..78beda1d8 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoFactory.cs @@ -1,40 +1,38 @@ -namespace System.IO.Abstractions -{ +namespace System.IO.Abstractions; #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - internal class DirectoryInfoFactory : IDirectoryInfoFactory - { - private readonly IFileSystem fileSystem; +internal class DirectoryInfoFactory : IDirectoryInfoFactory +{ + private readonly IFileSystem fileSystem; - /// - /// Base factory class for creating a - /// - public DirectoryInfoFactory(IFileSystem fileSystem) - { - this.fileSystem = fileSystem; - } + /// + /// Base factory class for creating a + /// + public DirectoryInfoFactory(IFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } - /// - public IFileSystem FileSystem - => fileSystem; + /// + public IFileSystem FileSystem + => fileSystem; - /// - public IDirectoryInfo New(string path) - { - var realDirectoryInfo = new DirectoryInfo(path); - return new DirectoryInfoWrapper(fileSystem, realDirectoryInfo); - } + /// + public IDirectoryInfo New(string path) + { + var realDirectoryInfo = new DirectoryInfo(path); + return new DirectoryInfoWrapper(fileSystem, realDirectoryInfo); + } - /// - public IDirectoryInfo Wrap(DirectoryInfo directoryInfo) + /// + public IDirectoryInfo Wrap(DirectoryInfo directoryInfo) + { + if (directoryInfo == null) { - if (directoryInfo == null) - { - return null; - } - - return new DirectoryInfoWrapper(fileSystem, directoryInfo); + return null; } + + return new DirectoryInfoWrapper(fileSystem, directoryInfo); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoWrapper.cs index f905a651e..6d2554534 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryInfoWrapper.cs @@ -3,23 +3,23 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class DirectoryInfoWrapper : DirectoryInfoBase, IFileSystemAclSupport - { - private readonly DirectoryInfo instance; +public class DirectoryInfoWrapper : DirectoryInfoBase, IFileSystemAclSupport +{ + private readonly DirectoryInfo instance; - /// - /// Wrapper class for calling methods of - /// - public DirectoryInfoWrapper(IFileSystem fileSystem, DirectoryInfo instance) : base(fileSystem) - { - this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); - } + /// + /// Wrapper class for calling methods of + /// + public DirectoryInfoWrapper(IFileSystem fileSystem, DirectoryInfo instance) : base(fileSystem) + { + this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); + } #if FEATURE_CREATE_SYMBOLIC_LINK /// @@ -29,17 +29,17 @@ public override void CreateAsSymbolicLink(string pathToTarget) } #endif - /// - public override void Delete() - { - instance.Delete(); - } + /// + public override void Delete() + { + instance.Delete(); + } - /// - public override void Refresh() - { - instance.Refresh(); - } + /// + public override void Refresh() + { + instance.Refresh(); + } #if FEATURE_CREATE_SYMBOLIC_LINK /// @@ -50,72 +50,72 @@ public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) } #endif - /// - public override FileAttributes Attributes - { - get { return instance.Attributes; } - set { instance.Attributes = value; } - } + /// + public override FileAttributes Attributes + { + get { return instance.Attributes; } + set { instance.Attributes = value; } + } - /// - public override DateTime CreationTime - { - get { return instance.CreationTime; } - set { instance.CreationTime = value; } - } + /// + public override DateTime CreationTime + { + get { return instance.CreationTime; } + set { instance.CreationTime = value; } + } - /// - public override DateTime CreationTimeUtc - { - get { return instance.CreationTimeUtc; } - set { instance.CreationTimeUtc = value; } - } + /// + public override DateTime CreationTimeUtc + { + get { return instance.CreationTimeUtc; } + set { instance.CreationTimeUtc = value; } + } - /// - public override bool Exists - { - get { return instance.Exists; } - } + /// + public override bool Exists + { + get { return instance.Exists; } + } - /// - public override string Extension - { - get { return instance.Extension; } - } + /// + public override string Extension + { + get { return instance.Extension; } + } - /// - public override string FullName - { - get { return instance.FullName; } - } + /// + public override string FullName + { + get { return instance.FullName; } + } - /// - public override DateTime LastAccessTime - { - get { return instance.LastAccessTime; } - set { instance.LastAccessTime = value; } - } + /// + public override DateTime LastAccessTime + { + get { return instance.LastAccessTime; } + set { instance.LastAccessTime = value; } + } - /// - public override DateTime LastAccessTimeUtc - { - get { return instance.LastAccessTimeUtc; } - set { instance.LastAccessTimeUtc = value; } - } + /// + public override DateTime LastAccessTimeUtc + { + get { return instance.LastAccessTimeUtc; } + set { instance.LastAccessTimeUtc = value; } + } - /// - public override DateTime LastWriteTime - { - get { return instance.LastWriteTime; } - set { instance.LastWriteTime = value; } - } + /// + public override DateTime LastWriteTime + { + get { return instance.LastWriteTime; } + set { instance.LastWriteTime = value; } + } - /// - public override DateTime LastWriteTimeUtc - { - get { return instance.LastWriteTimeUtc; } - set { instance.LastWriteTimeUtc = value; } - } + /// + public override DateTime LastWriteTimeUtc + { + get { return instance.LastWriteTimeUtc; } + set { instance.LastWriteTimeUtc = value; } + } #if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET /// @@ -125,47 +125,47 @@ public override string LinkTarget } #endif - /// - public override string Name - { - get { return instance.Name; } - } + /// + public override string Name + { + get { return instance.Name; } + } - /// - public override void Create() - { - instance.Create(); - } + /// + public override void Create() + { + instance.Create(); + } - /// - public override IDirectoryInfo CreateSubdirectory(string path) - { - return new DirectoryInfoWrapper(FileSystem, instance.CreateSubdirectory(path)); - } + /// + public override IDirectoryInfo CreateSubdirectory(string path) + { + return new DirectoryInfoWrapper(FileSystem, instance.CreateSubdirectory(path)); + } - /// - public override void Delete(bool recursive) - { - instance.Delete(recursive); - } + /// + public override void Delete(bool recursive) + { + instance.Delete(recursive); + } - /// - public override IEnumerable EnumerateDirectories() - { - return instance.EnumerateDirectories().Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); - } + /// + public override IEnumerable EnumerateDirectories() + { + return instance.EnumerateDirectories().Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); + } - /// - public override IEnumerable EnumerateDirectories(string searchPattern) - { - return instance.EnumerateDirectories(searchPattern).Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); - } + /// + public override IEnumerable EnumerateDirectories(string searchPattern) + { + return instance.EnumerateDirectories(searchPattern).Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); + } - /// - public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) - { - return instance.EnumerateDirectories(searchPattern, searchOption).Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); - } + /// + public override IEnumerable EnumerateDirectories(string searchPattern, SearchOption searchOption) + { + return instance.EnumerateDirectories(searchPattern, searchOption).Select(directoryInfo => new DirectoryInfoWrapper(FileSystem, directoryInfo)); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -175,23 +175,23 @@ public override IEnumerable EnumerateDirectories(string searchPa } #endif - /// - public override IEnumerable EnumerateFiles() - { - return instance.EnumerateFiles().Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); - } + /// + public override IEnumerable EnumerateFiles() + { + return instance.EnumerateFiles().Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); + } - /// - public override IEnumerable EnumerateFiles(string searchPattern) - { - return instance.EnumerateFiles(searchPattern).Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); - } + /// + public override IEnumerable EnumerateFiles(string searchPattern) + { + return instance.EnumerateFiles(searchPattern).Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); + } - /// - public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) - { - return instance.EnumerateFiles(searchPattern, searchOption).Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); - } + /// + public override IEnumerable EnumerateFiles(string searchPattern, SearchOption searchOption) + { + return instance.EnumerateFiles(searchPattern, searchOption).Select(fileInfo => new FileInfoWrapper(FileSystem, fileInfo)); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -201,23 +201,23 @@ public override IEnumerable EnumerateFiles(string searchPattern, Enum } #endif - /// - public override IEnumerable EnumerateFileSystemInfos() - { - return instance.EnumerateFileSystemInfos().WrapFileSystemInfos(FileSystem); - } + /// + public override IEnumerable EnumerateFileSystemInfos() + { + return instance.EnumerateFileSystemInfos().WrapFileSystemInfos(FileSystem); + } - /// - public override IEnumerable EnumerateFileSystemInfos(string searchPattern) - { - return instance.EnumerateFileSystemInfos(searchPattern).WrapFileSystemInfos(FileSystem); - } + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern) + { + return instance.EnumerateFileSystemInfos(searchPattern).WrapFileSystemInfos(FileSystem); + } - /// - public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return instance.EnumerateFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(FileSystem); - } + /// + public override IEnumerable EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return instance.EnumerateFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(FileSystem); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -227,23 +227,23 @@ public override IEnumerable EnumerateFileSystemInfos(string sea } #endif - /// - public override IDirectoryInfo[] GetDirectories() - { - return instance.GetDirectories().WrapDirectories(FileSystem); - } + /// + public override IDirectoryInfo[] GetDirectories() + { + return instance.GetDirectories().WrapDirectories(FileSystem); + } - /// - public override IDirectoryInfo[] GetDirectories(string searchPattern) - { - return instance.GetDirectories(searchPattern).WrapDirectories(FileSystem); - } + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern) + { + return instance.GetDirectories(searchPattern).WrapDirectories(FileSystem); + } - /// - public override IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) - { - return instance.GetDirectories(searchPattern, searchOption).WrapDirectories(FileSystem); - } + /// + public override IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) + { + return instance.GetDirectories(searchPattern, searchOption).WrapDirectories(FileSystem); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -253,23 +253,23 @@ public override IDirectoryInfo[] GetDirectories(string searchPattern, Enumeratio } #endif - /// - public override IFileInfo[] GetFiles() - { - return instance.GetFiles().WrapFiles(FileSystem); - } + /// + public override IFileInfo[] GetFiles() + { + return instance.GetFiles().WrapFiles(FileSystem); + } - /// - public override IFileInfo[] GetFiles(string searchPattern) - { - return instance.GetFiles(searchPattern).WrapFiles(FileSystem); - } + /// + public override IFileInfo[] GetFiles(string searchPattern) + { + return instance.GetFiles(searchPattern).WrapFiles(FileSystem); + } - /// - public override IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption) - { - return instance.GetFiles(searchPattern, searchOption).WrapFiles(FileSystem); - } + /// + public override IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption) + { + return instance.GetFiles(searchPattern, searchOption).WrapFiles(FileSystem); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -279,23 +279,23 @@ public override IFileInfo[] GetFiles(string searchPattern, EnumerationOptions en } #endif - /// - public override IFileSystemInfo[] GetFileSystemInfos() - { - return instance.GetFileSystemInfos().WrapFileSystemInfos(FileSystem); - } + /// + public override IFileSystemInfo[] GetFileSystemInfos() + { + return instance.GetFileSystemInfos().WrapFileSystemInfos(FileSystem); + } - /// - public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern) - { - return instance.GetFileSystemInfos(searchPattern).WrapFileSystemInfos(FileSystem); - } + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern) + { + return instance.GetFileSystemInfos(searchPattern).WrapFileSystemInfos(FileSystem); + } - /// - public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) - { - return instance.GetFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(FileSystem); - } + /// + public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) + { + return instance.GetFileSystemInfos(searchPattern, searchOption).WrapFileSystemInfos(FileSystem); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -305,64 +305,63 @@ public override IFileSystemInfo[] GetFileSystemInfos(string searchPattern, Enume } #endif - /// - public override void MoveTo(string destDirName) - { - instance.MoveTo(destDirName); - } + /// + public override void MoveTo(string destDirName) + { + instance.MoveTo(destDirName); + } - /// - public override IDirectoryInfo Parent + /// + public override IDirectoryInfo Parent + { + get { - get + if (instance.Parent == null) { - if (instance.Parent == null) - { - return null; - } - else - { - return new DirectoryInfoWrapper(FileSystem, instance.Parent); - } + return null; + } + else + { + return new DirectoryInfoWrapper(FileSystem, instance.Parent); } } + } - /// - public override IDirectoryInfo Root - => new DirectoryInfoWrapper(FileSystem, instance.Root); + /// + public override IDirectoryInfo Root + => new DirectoryInfoWrapper(FileSystem, instance.Root); - /// - public override string ToString() - { - return instance.ToString(); - } + /// + public override string ToString() + { + return instance.ToString(); + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl() - { - return instance.GetAccessControl(); - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return instance.GetAccessControl(); + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return instance.GetAccessControl((AccessControlSections)includeSections); + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + if (value is DirectorySecurity directorySecurity) { - return instance.GetAccessControl((AccessControlSections)includeSections); + this.instance.SetAccessControl(directorySecurity); } - - /// - [SupportedOSPlatform("windows")] - public void SetAccessControl(object value) + else { - if (value is DirectorySecurity directorySecurity) - { - this.instance.SetAccessControl(directorySecurity); - } - else - { - throw new ArgumentException("value must be of type `FileSecurity`"); - } + throw new ArgumentException("value must be of type `FileSecurity`"); } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryWrapper.cs index 72544a50b..2485366d5 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DirectoryWrapper.cs @@ -1,26 +1,26 @@ using System.Collections.Generic; using System.Runtime.Versioning; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class DirectoryWrapper : DirectoryBase +public class DirectoryWrapper : DirectoryBase +{ + /// + public DirectoryWrapper(IFileSystem fileSystem) : base(fileSystem) { - /// - public DirectoryWrapper(IFileSystem fileSystem) : base(fileSystem) - { - } + } - /// - public override IDirectoryInfo CreateDirectory(string path) - { - var directoryInfo = new DirectoryInfo(path); - directoryInfo.Create(); - return new DirectoryInfoWrapper(FileSystem, directoryInfo); - } + /// + public override IDirectoryInfo CreateDirectory(string path) + { + var directoryInfo = new DirectoryInfo(path); + directoryInfo.Create(); + return new DirectoryInfoWrapper(FileSystem, directoryInfo); + } #if FEATURE_UNIX_FILE_MODE /// @@ -49,59 +49,59 @@ public override IDirectoryInfo CreateTempSubdirectory(string prefix = null) Directory.CreateTempSubdirectory(prefix)); } #endif - /// - public override void Delete(string path) - { - Directory.Delete(path); - } + /// + public override void Delete(string path) + { + Directory.Delete(path); + } - /// - public override void Delete(string path, bool recursive) - { - Directory.Delete(path, recursive); - } + /// + public override void Delete(string path, bool recursive) + { + Directory.Delete(path, recursive); + } - /// - public override bool Exists(string path) - { - return Directory.Exists(path); - } + /// + public override bool Exists(string path) + { + return Directory.Exists(path); + } - /// - public override DateTime GetCreationTime(string path) - { - return Directory.GetCreationTime(path); - } + /// + public override DateTime GetCreationTime(string path) + { + return Directory.GetCreationTime(path); + } - /// - public override DateTime GetCreationTimeUtc(string path) - { - return Directory.GetCreationTimeUtc(path); - } + /// + public override DateTime GetCreationTimeUtc(string path) + { + return Directory.GetCreationTimeUtc(path); + } - /// - public override string GetCurrentDirectory() - { - return Directory.GetCurrentDirectory(); - } + /// + public override string GetCurrentDirectory() + { + return Directory.GetCurrentDirectory(); + } - /// - public override string[] GetDirectories(string path) - { - return Directory.GetDirectories(path); - } + /// + public override string[] GetDirectories(string path) + { + return Directory.GetDirectories(path); + } - /// - public override string[] GetDirectories(string path, string searchPattern) - { - return Directory.GetDirectories(path, searchPattern); - } + /// + public override string[] GetDirectories(string path, string searchPattern) + { + return Directory.GetDirectories(path, searchPattern); + } - /// - public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) - { - return Directory.GetDirectories(path, searchPattern, searchOption); - } + /// + public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) + { + return Directory.GetDirectories(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -111,29 +111,29 @@ public override string[] GetDirectories(string path, string searchPattern, Enume } #endif - /// - public override string GetDirectoryRoot(string path) - { - return Directory.GetDirectoryRoot(path); - } + /// + public override string GetDirectoryRoot(string path) + { + return Directory.GetDirectoryRoot(path); + } - /// - public override string[] GetFiles(string path) - { - return Directory.GetFiles(path); - } + /// + public override string[] GetFiles(string path) + { + return Directory.GetFiles(path); + } - /// - public override string[] GetFiles(string path, string searchPattern) - { - return Directory.GetFiles(path, searchPattern); - } + /// + public override string[] GetFiles(string path, string searchPattern) + { + return Directory.GetFiles(path, searchPattern); + } - /// - public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) - { - return Directory.GetFiles(path, searchPattern, searchOption); - } + /// + public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) + { + return Directory.GetFiles(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -143,23 +143,23 @@ public override string[] GetFiles(string path, string searchPattern, Enumeration } #endif - /// - public override string[] GetFileSystemEntries(string path) - { - return Directory.GetFileSystemEntries(path); - } + /// + public override string[] GetFileSystemEntries(string path) + { + return Directory.GetFileSystemEntries(path); + } - /// - public override string[] GetFileSystemEntries(string path, string searchPattern) - { - return Directory.GetFileSystemEntries(path, searchPattern); - } + /// + public override string[] GetFileSystemEntries(string path, string searchPattern) + { + return Directory.GetFileSystemEntries(path, searchPattern); + } - /// - public override string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) - { - return Directory.GetFileSystemEntries(path, searchPattern, searchOption); - } + /// + public override string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + return Directory.GetFileSystemEntries(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -169,55 +169,55 @@ public override string[] GetFileSystemEntries(string path, string searchPattern, } #endif - /// - public override DateTime GetLastAccessTime(string path) - { - return Directory.GetLastAccessTime(path); - } - - /// - public override DateTime GetLastAccessTimeUtc(string path) - { - return Directory.GetLastAccessTimeUtc(path); - } - - /// - public override DateTime GetLastWriteTime(string path) - { - return Directory.GetLastWriteTime(path); - } + /// + public override DateTime GetLastAccessTime(string path) + { + return Directory.GetLastAccessTime(path); + } - /// - public override DateTime GetLastWriteTimeUtc(string path) - { - return Directory.GetLastWriteTimeUtc(path); - } + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + return Directory.GetLastAccessTimeUtc(path); + } - /// - public override string[] GetLogicalDrives() - { - return Directory.GetLogicalDrives(); - } + /// + public override DateTime GetLastWriteTime(string path) + { + return Directory.GetLastWriteTime(path); + } - /// - public override IDirectoryInfo GetParent(string path) - { - var parent = Directory.GetParent(path); + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + return Directory.GetLastWriteTimeUtc(path); + } - if (parent == null) - { - return null; - } + /// + public override string[] GetLogicalDrives() + { + return Directory.GetLogicalDrives(); + } - return new DirectoryInfoWrapper(FileSystem, parent); - } + /// + public override IDirectoryInfo GetParent(string path) + { + var parent = Directory.GetParent(path); - /// - public override void Move(string sourceDirName, string destDirName) + if (parent == null) { - Directory.Move(sourceDirName, destDirName); + return null; } + return new DirectoryInfoWrapper(FileSystem, parent); + } + + /// + public override void Move(string sourceDirName, string destDirName) + { + Directory.Move(sourceDirName, destDirName); + } + #if FEATURE_CREATE_SYMBOLIC_LINK /// public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget) @@ -227,65 +227,65 @@ public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFi } #endif - /// - public override void SetCreationTime(string path, DateTime creationTime) - { - Directory.SetCreationTime(path, creationTime); - } + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + Directory.SetCreationTime(path, creationTime); + } - /// - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - Directory.SetCreationTimeUtc(path, creationTimeUtc); - } + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + Directory.SetCreationTimeUtc(path, creationTimeUtc); + } - /// - public override void SetCurrentDirectory(string path) - { - Directory.SetCurrentDirectory(path); - } + /// + public override void SetCurrentDirectory(string path) + { + Directory.SetCurrentDirectory(path); + } - /// - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - Directory.SetLastAccessTime(path, lastAccessTime); - } + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + Directory.SetLastAccessTime(path, lastAccessTime); + } - /// - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - Directory.SetLastAccessTimeUtc(path, lastAccessTimeUtc); - } + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + Directory.SetLastAccessTimeUtc(path, lastAccessTimeUtc); + } - /// - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - Directory.SetLastWriteTime(path, lastWriteTime); - } + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + Directory.SetLastWriteTime(path, lastWriteTime); + } - /// - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - Directory.SetLastWriteTimeUtc(path, lastWriteTimeUtc); - } + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + Directory.SetLastWriteTimeUtc(path, lastWriteTimeUtc); + } - /// - public override IEnumerable EnumerateDirectories(string path) - { - return Directory.EnumerateDirectories(path); - } + /// + public override IEnumerable EnumerateDirectories(string path) + { + return Directory.EnumerateDirectories(path); + } - /// - public override IEnumerable EnumerateDirectories(string path, string searchPattern) - { - return Directory.EnumerateDirectories(path, searchPattern); - } + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern) + { + return Directory.EnumerateDirectories(path, searchPattern); + } - /// - public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) - { - return Directory.EnumerateDirectories(path, searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateDirectories(string path, string searchPattern, SearchOption searchOption) + { + return Directory.EnumerateDirectories(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -295,23 +295,23 @@ public override IEnumerable EnumerateDirectories(string path, string sea } #endif - /// - public override IEnumerable EnumerateFiles(string path) - { - return Directory.EnumerateFiles(path); - } + /// + public override IEnumerable EnumerateFiles(string path) + { + return Directory.EnumerateFiles(path); + } - /// - public override IEnumerable EnumerateFiles(string path, string searchPattern) - { - return Directory.EnumerateFiles(path, searchPattern); - } + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern) + { + return Directory.EnumerateFiles(path, searchPattern); + } - /// - public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) - { - return Directory.EnumerateFiles(path, searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) + { + return Directory.EnumerateFiles(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -321,23 +321,23 @@ public override IEnumerable EnumerateFiles(string path, string searchPat } #endif - /// - public override IEnumerable EnumerateFileSystemEntries(string path) - { - return Directory.EnumerateFileSystemEntries(path); - } + /// + public override IEnumerable EnumerateFileSystemEntries(string path) + { + return Directory.EnumerateFileSystemEntries(path); + } - /// - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) - { - return Directory.EnumerateFileSystemEntries(path, searchPattern); - } + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern) + { + return Directory.EnumerateFileSystemEntries(path, searchPattern); + } - /// - public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) - { - return Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption); - } + /// + public override IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) + { + return Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption); + } #if FEATURE_ENUMERATION_OPTIONS /// @@ -346,5 +346,4 @@ public override IEnumerable EnumerateFileSystemEntries(string path, stri return Directory.EnumerateFileSystemEntries(path, searchPattern, enumerationOptions); } #endif - } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoBase.cs index a01699525..ef6629fdd 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoBase.cs @@ -1,65 +1,64 @@ -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class DriveInfoBase : IDriveInfo +public abstract class DriveInfoBase : IDriveInfo +{ + /// + /// Base class for calling methods of + /// + protected DriveInfoBase(IFileSystem fileSystem) { - /// - /// Base class for calling methods of - /// - protected DriveInfoBase(IFileSystem fileSystem) - { - FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); - } + FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + } - [Obsolete("This constructor only exists to support mocking libraries.", error: true)] - internal DriveInfoBase() { } + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal DriveInfoBase() { } - /// - /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. - /// - public IFileSystem FileSystem { get; } + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } - /// - public abstract long AvailableFreeSpace { get; } + /// + public abstract long AvailableFreeSpace { get; } - /// - public abstract string DriveFormat { get; } + /// + public abstract string DriveFormat { get; } - /// - public abstract DriveType DriveType { get; } + /// + public abstract DriveType DriveType { get; } - /// - public abstract bool IsReady { get; } + /// + public abstract bool IsReady { get; } - /// - public abstract string Name { get; } + /// + public abstract string Name { get; } - /// - public abstract IDirectoryInfo RootDirectory { get; } + /// + public abstract IDirectoryInfo RootDirectory { get; } - /// - public abstract long TotalFreeSpace { get; } + /// + public abstract long TotalFreeSpace { get; } - /// - public abstract long TotalSize { get; } + /// + public abstract long TotalSize { get; } - /// - public abstract string VolumeLabel { get; set; } + /// + public abstract string VolumeLabel { get; set; } - /// - /// Implicitly converts a to a . - /// - public static implicit operator DriveInfoBase(DriveInfo driveInfo) + /// + /// Implicitly converts a to a . + /// + public static implicit operator DriveInfoBase(DriveInfo driveInfo) + { + if (driveInfo == null) { - if (driveInfo == null) - { - return null; - } - - return new DriveInfoWrapper(new FileSystem(), driveInfo); + return null; } + + return new DriveInfoWrapper(new FileSystem(), driveInfo); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoFactory.cs index fc1b2bc04..a9ab7bf80 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoFactory.cs @@ -1,54 +1,52 @@ -namespace System.IO.Abstractions -{ +namespace System.IO.Abstractions; #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - internal class DriveInfoFactory : IDriveInfoFactory +internal class DriveInfoFactory : IDriveInfoFactory +{ + private readonly IFileSystem fileSystem; + + /// + /// Base factory class for creating a + /// + public DriveInfoFactory(IFileSystem fileSystem) { - private readonly IFileSystem fileSystem; + this.fileSystem = fileSystem; + } - /// - /// Base factory class for creating a - /// - public DriveInfoFactory(IFileSystem fileSystem) + /// + public IFileSystem FileSystem + => fileSystem; + + /// + public IDriveInfo[] GetDrives() + { + var driveInfos = DriveInfo.GetDrives(); + var driveInfoWrappers = new DriveInfoBase[driveInfos.Length]; + for (int index = 0; index < driveInfos.Length; index++) { - this.fileSystem = fileSystem; + var driveInfo = driveInfos[index]; + driveInfoWrappers[index] = new DriveInfoWrapper(fileSystem, driveInfo); } - /// - public IFileSystem FileSystem - => fileSystem; - - /// - public IDriveInfo[] GetDrives() - { - var driveInfos = DriveInfo.GetDrives(); - var driveInfoWrappers = new DriveInfoBase[driveInfos.Length]; - for (int index = 0; index < driveInfos.Length; index++) - { - var driveInfo = driveInfos[index]; - driveInfoWrappers[index] = new DriveInfoWrapper(fileSystem, driveInfo); - } + return driveInfoWrappers; + } - return driveInfoWrappers; - } + /// + public IDriveInfo New(string driveName) + { + var realDriveInfo = new DriveInfo(driveName); + return new DriveInfoWrapper(fileSystem, realDriveInfo); + } - /// - public IDriveInfo New(string driveName) + /// + public IDriveInfo Wrap(DriveInfo driveInfo) + { + if (driveInfo == null) { - var realDriveInfo = new DriveInfo(driveName); - return new DriveInfoWrapper(fileSystem, realDriveInfo); + return null; } - /// - public IDriveInfo Wrap(DriveInfo driveInfo) - { - if (driveInfo == null) - { - return null; - } - - return new DriveInfoWrapper(fileSystem, driveInfo); - } + return new DriveInfoWrapper(fileSystem, driveInfo); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoWrapper.cs index 5d3976382..b4f1eb9cd 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/DriveInfoWrapper.cs @@ -1,170 +1,169 @@ using System.Runtime.Versioning; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +/// +/// The wrapper for a . +/// +#if FEATURE_SERIALIZABLE +[Serializable] +#endif +public class DriveInfoWrapper : DriveInfoBase { /// - /// The wrapper for a . + /// The instance of the real . /// -#if FEATURE_SERIALIZABLE - [Serializable] -#endif - public class DriveInfoWrapper : DriveInfoBase - { - /// - /// The instance of the real . - /// - private readonly DriveInfo instance; + private readonly DriveInfo instance; - /// - /// Initializes a new instance of the class, which acts as a wrapper for a drive info. - /// - /// The underlying IFileSystem. - /// The drive info. - public DriveInfoWrapper(IFileSystem fileSystem, DriveInfo instance) : base(fileSystem) - { - this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); - } + /// + /// Initializes a new instance of the class, which acts as a wrapper for a drive info. + /// + /// The underlying IFileSystem. + /// The drive info. + public DriveInfoWrapper(IFileSystem fileSystem, DriveInfo instance) : base(fileSystem) + { + this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); + } - /// - /// Gets or sets the name of a drive, such as C:\. - /// - /// The name of the drive. - /// - /// This property is the name assigned to the drive, such as C:\ or E:\. - /// - public override string Name - { - get { return instance.Name; } - } + /// + /// Gets or sets the name of a drive, such as C:\. + /// + /// The name of the drive. + /// + /// This property is the name assigned to the drive, such as C:\ or E:\. + /// + public override string Name + { + get { return instance.Name; } + } - /// - /// Gets or sets the drive type, such as CD-ROM, removable, network, or fixed. - /// - /// One of the enumeration values that specifies a drive type. - /// - /// The DriveType property indicates whether a drive is one of the following: CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. - /// These values are described in the DriveType enumeration. - /// - public override DriveType DriveType - { - get { return instance.DriveType; } - } + /// + /// Gets or sets the drive type, such as CD-ROM, removable, network, or fixed. + /// + /// One of the enumeration values that specifies a drive type. + /// + /// The DriveType property indicates whether a drive is one of the following: CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. + /// These values are described in the DriveType enumeration. + /// + public override DriveType DriveType + { + get { return instance.DriveType; } + } - /// - /// Gets or sets the name of the file system, such as NTFS or FAT32. - /// - /// - /// Use DriveFormat to determine what formatting a drive uses. - /// - /// The name of the file system on the specified drive. - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override string DriveFormat - { - get { return instance.DriveFormat; } - } + /// + /// Gets or sets the name of the file system, such as NTFS or FAT32. + /// + /// + /// Use DriveFormat to determine what formatting a drive uses. + /// + /// The name of the file system on the specified drive. + /// Thrown if the access to the drive information is denied. + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override string DriveFormat + { + get { return instance.DriveFormat; } + } - /// - /// Gets or sets a value indicating whether a drive is ready. - /// - /// - /// if the drive is ready; if the drive is not ready. - /// - /// - /// IsReady indicates whether a drive is ready. - /// For example, it indicates whether a CD is in a CD drive or whether a removable storage device is ready for read/write operations. - /// If you do not test whether a drive is ready, and it is not ready, querying the drive using will raise an IOException. - /// Do not rely on IsReady to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and . - /// Between the time that your code checks IsReady and then accesses one of the other properties (even if the access occurs immediately after the check), - /// a drive may have been disconnected or a disk may have been removed. - /// - public override bool IsReady - { - get { return instance.IsReady; } - } + /// + /// Gets or sets a value indicating whether a drive is ready. + /// + /// + /// if the drive is ready; if the drive is not ready. + /// + /// + /// IsReady indicates whether a drive is ready. + /// For example, it indicates whether a CD is in a CD drive or whether a removable storage device is ready for read/write operations. + /// If you do not test whether a drive is ready, and it is not ready, querying the drive using will raise an IOException. + /// Do not rely on IsReady to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and . + /// Between the time that your code checks IsReady and then accesses one of the other properties (even if the access occurs immediately after the check), + /// a drive may have been disconnected or a disk may have been removed. + /// + public override bool IsReady + { + get { return instance.IsReady; } + } - /// - /// Gets or sets the amount of available free space on a drive, in bytes. - /// - /// The amount of free space available on the drive, in bytes. - /// - /// This property indicates the amount of free space available on the drive. - /// Note that this number may be different from the TotalFreeSpace number because this property takes into account disk quotas. - /// - /// Thrown if the access to the drive information is denied. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override long AvailableFreeSpace - { - get { return instance.AvailableFreeSpace; } - } + /// + /// Gets or sets the amount of available free space on a drive, in bytes. + /// + /// The amount of free space available on the drive, in bytes. + /// + /// This property indicates the amount of free space available on the drive. + /// Note that this number may be different from the TotalFreeSpace number because this property takes into account disk quotas. + /// + /// Thrown if the access to the drive information is denied. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override long AvailableFreeSpace + { + get { return instance.AvailableFreeSpace; } + } - /// - /// Gets or sets the total amount of free space available on a drive, in bytes. - /// - /// The total free space available on a drive, in bytes. - /// This property indicates the total amount of free space available on the drive, not just what is available to the current user. - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override long TotalFreeSpace - { - get { return instance.TotalFreeSpace; } - } + /// + /// Gets or sets the total amount of free space available on a drive, in bytes. + /// + /// The total free space available on a drive, in bytes. + /// This property indicates the total amount of free space available on the drive, not just what is available to the current user. + /// Thrown if the access to the drive information is denied. + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override long TotalFreeSpace + { + get { return instance.TotalFreeSpace; } + } - /// - /// Gets or sets the total size of storage space on a drive, in bytes. - /// - /// The total size of the drive, in bytes. - /// - /// This property indicates the total size of the drive in bytes, not just what is available to the current user. - /// - /// Thrown if the access to the drive information is denied. - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - public override long TotalSize - { - get { return instance.TotalSize; } - } + /// + /// Gets or sets the total size of storage space on a drive, in bytes. + /// + /// The total size of the drive, in bytes. + /// + /// This property indicates the total size of the drive in bytes, not just what is available to the current user. + /// + /// Thrown if the access to the drive information is denied. + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + public override long TotalSize + { + get { return instance.TotalSize; } + } - /// - /// Gets or sets the root directory of a drive. - /// - /// An object that contains the root directory of the drive. - public override IDirectoryInfo RootDirectory - { - get { return new DirectoryInfoWrapper(FileSystem, instance.RootDirectory); } - } + /// + /// Gets or sets the root directory of a drive. + /// + /// An object that contains the root directory of the drive. + public override IDirectoryInfo RootDirectory + { + get { return new DirectoryInfoWrapper(FileSystem, instance.RootDirectory); } + } - /// - /// Gets or sets the volume label of a drive. - /// - /// The volume label. - /// - /// The label length is determined by the operating system. For example, NTFS allows a volume label to be up to 32 characters long. Note that is a valid VolumeLabel. - /// - /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). - /// Thrown if the drive does not exist or is not mapped. - /// Thrown if the caller does not have the required permission. - /// - /// Thrown if the volume label is being set on a network or CD-ROM drive - /// -or- - /// Access to the drive information is denied. - /// - public override string VolumeLabel - { - get { return instance.VolumeLabel; } + /// + /// Gets or sets the volume label of a drive. + /// + /// The volume label. + /// + /// The label length is determined by the operating system. For example, NTFS allows a volume label to be up to 32 characters long. Note that is a valid VolumeLabel. + /// + /// Thrown if an I/O error occurred (for example, a disk error or a drive was not ready). + /// Thrown if the drive does not exist or is not mapped. + /// Thrown if the caller does not have the required permission. + /// + /// Thrown if the volume label is being set on a network or CD-ROM drive + /// -or- + /// Access to the drive information is denied. + /// + public override string VolumeLabel + { + get { return instance.VolumeLabel; } - [SupportedOSPlatform("windows")] + [SupportedOSPlatform("windows")] #pragma warning disable CA1416 - set { instance.VolumeLabel = value; } + set { instance.VolumeLabel = value; } #pragma warning restore CA1416 - } + } - /// - public override string ToString() - { - return instance.ToString(); - } + /// + public override string ToString() + { + return instance.ToString(); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileAclExtensions.cs index 805bca4df..8a2d4ed0f 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileAclExtensions.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileAclExtensions.cs @@ -1,53 +1,52 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class FileAclExtensions { - /// - /// ACL (access control list) extension methods for . - /// - public static class FileAclExtensions - { #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static FileSecurity GetAccessControl( - this IFile file, string path) - { - IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); - return fileInfo.GetAccessControl(); - } + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFile file, string path) + { + IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); + return fileInfo.GetAccessControl(); + } #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static FileSecurity GetAccessControl( - this IFile file, - string path, - AccessControlSections includeSections) - { - IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); - return fileInfo.GetAccessControl(includeSections); - } + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFile file, + string path, + AccessControlSections includeSections) + { + IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); + return fileInfo.GetAccessControl(includeSections); + } #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static void SetAccessControl(this IFile file, - string path, - FileSecurity fileSecurity) - { - IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); - fileInfo.SetAccessControl(fileSecurity); - } + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IFile file, + string path, + FileSecurity fileSecurity) + { + IFileInfo fileInfo = file.FileSystem.FileInfo.New(path); + fileInfo.SetAccessControl(fileSecurity); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.cs index 43aa10e43..bf32b5662 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileBase.cs @@ -2,29 +2,29 @@ using System.Text; using Microsoft.Win32.SafeHandles; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract partial class FileBase : IFile +public abstract partial class FileBase : IFile +{ + /// + /// Base class for calling static methods of + /// + protected FileBase(IFileSystem fileSystem) { - /// - /// Base class for calling static methods of - /// - protected FileBase(IFileSystem fileSystem) - { - FileSystem = fileSystem; - } - - [Obsolete("This constructor only exists to support mocking libraries.", error: true)] - internal FileBase() { } - - /// - /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. - /// - public IFileSystem FileSystem { get; } + FileSystem = fileSystem; + } + + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal FileBase() { } + + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } #if FEATURE_FILE_SPAN /// @@ -34,17 +34,17 @@ internal FileBase() { } public abstract void AppendAllBytes(string path, ReadOnlySpan bytes); #endif - /// - public abstract void AppendAllLines(string path, IEnumerable contents); + /// + public abstract void AppendAllLines(string path, IEnumerable contents); - /// - public abstract void AppendAllLines(string path, IEnumerable contents, Encoding encoding); + /// + public abstract void AppendAllLines(string path, IEnumerable contents, Encoding encoding); - /// - public abstract void AppendAllText(string path, string contents); + /// + public abstract void AppendAllText(string path, string contents); - /// - public abstract void AppendAllText(string path, string contents, Encoding encoding); + /// + public abstract void AppendAllText(string path, string contents, Encoding encoding); #if FEATURE_FILE_SPAN /// @@ -54,93 +54,93 @@ internal FileBase() { } public abstract void AppendAllText(string path, ReadOnlySpan contents, Encoding encoding); #endif - /// - public abstract StreamWriter AppendText(string path); + /// + public abstract StreamWriter AppendText(string path); - /// - public abstract void Copy(string sourceFileName, string destFileName); + /// + public abstract void Copy(string sourceFileName, string destFileName); - /// - public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); + /// + public abstract void Copy(string sourceFileName, string destFileName, bool overwrite); - /// - public abstract FileSystemStream Create(string path); + /// + public abstract FileSystemStream Create(string path); - /// - public abstract FileSystemStream Create(string path, int bufferSize); + /// + public abstract FileSystemStream Create(string path, int bufferSize); - /// - public abstract FileSystemStream Create(string path, int bufferSize, FileOptions options); + /// + public abstract FileSystemStream Create(string path, int bufferSize, FileOptions options); #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public abstract IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); + /// + public abstract IFileSystemInfo CreateSymbolicLink(string path, string pathToTarget); #endif - /// - public abstract StreamWriter CreateText(string path); + /// + public abstract StreamWriter CreateText(string path); - /// - public abstract void Decrypt(string path); + /// + public abstract void Decrypt(string path); - /// - public abstract void Delete(string path); + /// + public abstract void Delete(string path); - /// - public abstract void Encrypt(string path); + /// + public abstract void Encrypt(string path); - /// - public abstract bool Exists(string path); + /// + public abstract bool Exists(string path); - /// - public abstract FileAttributes GetAttributes(string path); + /// + public abstract FileAttributes GetAttributes(string path); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract FileAttributes GetAttributes(SafeFileHandle fileHandle); #endif - /// - public abstract DateTime GetCreationTime(string path); + /// + public abstract DateTime GetCreationTime(string path); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract DateTime GetCreationTime(SafeFileHandle fileHandle); #endif - /// - public abstract DateTime GetCreationTimeUtc(string path); + /// + public abstract DateTime GetCreationTimeUtc(string path); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract DateTime GetCreationTimeUtc(SafeFileHandle fileHandle); #endif - /// - public abstract DateTime GetLastAccessTime(string path); + /// + public abstract DateTime GetLastAccessTime(string path); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract DateTime GetLastAccessTime(SafeFileHandle fileHandle); #endif - /// - public abstract DateTime GetLastAccessTimeUtc(string path); + /// + public abstract DateTime GetLastAccessTimeUtc(string path); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract DateTime GetLastAccessTimeUtc(SafeFileHandle fileHandle); #endif - /// - public abstract DateTime GetLastWriteTime(string path); + /// + public abstract DateTime GetLastWriteTime(string path); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract DateTime GetLastWriteTime(SafeFileHandle fileHandle); #endif - /// - public abstract DateTime GetLastWriteTimeUtc(string path); + /// + public abstract DateTime GetLastWriteTimeUtc(string path); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -157,119 +157,119 @@ internal FileBase() { } public abstract UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle); #endif - /// - public abstract void Move(string sourceFileName, string destFileName); + /// + public abstract void Move(string sourceFileName, string destFileName); #if FEATURE_FILE_MOVE_WITH_OVERWRITE - /// - public abstract void Move(string sourceFileName, string destFileName, bool overwrite); + /// + public abstract void Move(string sourceFileName, string destFileName, bool overwrite); #endif - /// - public abstract FileSystemStream Open(string path, FileMode mode); + /// + public abstract FileSystemStream Open(string path, FileMode mode); - /// - public abstract FileSystemStream Open(string path, FileMode mode, FileAccess access); + /// + public abstract FileSystemStream Open(string path, FileMode mode, FileAccess access); - /// - public abstract FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share); + /// + public abstract FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share); #if FEATURE_FILESTREAM_OPTIONS - /// - public abstract FileSystemStream Open(string path, FileStreamOptions options); + /// + public abstract FileSystemStream Open(string path, FileStreamOptions options); #endif - /// - public abstract FileSystemStream OpenRead(string path); + /// + public abstract FileSystemStream OpenRead(string path); - /// - public abstract StreamReader OpenText(string path); + /// + public abstract StreamReader OpenText(string path); - /// - public abstract FileSystemStream OpenWrite(string path); + /// + public abstract FileSystemStream OpenWrite(string path); - /// - public abstract byte[] ReadAllBytes(string path); + /// + public abstract byte[] ReadAllBytes(string path); - /// - public abstract string[] ReadAllLines(string path); + /// + public abstract string[] ReadAllLines(string path); - /// - public abstract string[] ReadAllLines(string path, Encoding encoding); + /// + public abstract string[] ReadAllLines(string path, Encoding encoding); - /// - public abstract string ReadAllText(string path); + /// + public abstract string ReadAllText(string path); - /// - public abstract string ReadAllText(string path, Encoding encoding); + /// + public abstract string ReadAllText(string path, Encoding encoding); - /// - public abstract IEnumerable ReadLines(string path); + /// + public abstract IEnumerable ReadLines(string path); - /// - public abstract IEnumerable ReadLines(string path, Encoding encoding); + /// + public abstract IEnumerable ReadLines(string path, Encoding encoding); - /// - public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); + /// + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); - /// - public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + /// + public abstract void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public abstract IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); + /// + public abstract IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget); #endif - /// - public abstract void SetAttributes(string path, FileAttributes fileAttributes); + /// + public abstract void SetAttributes(string path, FileAttributes fileAttributes); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract void SetAttributes(SafeFileHandle fileHandle, FileAttributes fileAttributes); #endif - /// - public abstract void SetCreationTime(string path, DateTime creationTime); + /// + public abstract void SetCreationTime(string path, DateTime creationTime); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract void SetCreationTime(SafeFileHandle fileHandle, DateTime creationTime); #endif - /// - public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); + /// + public abstract void SetCreationTimeUtc(string path, DateTime creationTimeUtc); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract void SetCreationTimeUtc(SafeFileHandle fileHandle, DateTime creationTimeUtc); #endif - /// - public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); + /// + public abstract void SetLastAccessTime(string path, DateTime lastAccessTime); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract void SetLastAccessTime(SafeFileHandle fileHandle, DateTime lastAccessTime); #endif - /// - public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); + /// + public abstract void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract void SetLastAccessTimeUtc(SafeFileHandle fileHandle, DateTime lastAccessTimeUtc); #endif - /// - public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); + /// + public abstract void SetLastWriteTime(string path, DateTime lastWriteTime); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// public abstract void SetLastWriteTime(SafeFileHandle fileHandle, DateTime lastWriteTime); #endif - /// - public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); + /// + public abstract void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -286,31 +286,31 @@ internal FileBase() { } public abstract void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mode); #endif - /// - public abstract void WriteAllBytes(string path, byte[] bytes); + /// + public abstract void WriteAllBytes(string path, byte[] bytes); #if FEATURE_FILE_SPAN /// public abstract void WriteAllBytes(string path, ReadOnlySpan bytes); #endif - /// - public abstract void WriteAllLines(string path, IEnumerable contents); + /// + public abstract void WriteAllLines(string path, IEnumerable contents); - /// - public abstract void WriteAllLines(string path, IEnumerable contents, Encoding encoding); + /// + public abstract void WriteAllLines(string path, IEnumerable contents, Encoding encoding); - /// - public abstract void WriteAllLines(string path, string[] contents); + /// + public abstract void WriteAllLines(string path, string[] contents); - /// - public abstract void WriteAllLines(string path, string[] contents, Encoding encoding); + /// + public abstract void WriteAllLines(string path, string[] contents, Encoding encoding); - /// - public abstract void WriteAllText(string path, string contents); + /// + public abstract void WriteAllText(string path, string contents); - /// - public abstract void WriteAllText(string path, string contents, Encoding encoding); + /// + public abstract void WriteAllText(string path, string contents, Encoding encoding); #if FEATURE_FILE_SPAN /// @@ -319,5 +319,4 @@ internal FileBase() { } /// public abstract void WriteAllText(string path, ReadOnlySpan contents, Encoding encoding); #endif - } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoAclExtensions.cs index 69eb53942..84550e1ce 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoAclExtensions.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoAclExtensions.cs @@ -1,68 +1,67 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class FileInfoAclExtensions { - /// - /// ACL (access control list) extension methods for . - /// - public static class FileInfoAclExtensions - { #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static FileSecurity GetAccessControl( - this IFileInfo fileInfo) + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFileInfo fileInfo) + { + IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; + var fileSecurity = aclSupport?.GetAccessControl() as FileSecurity; + if (aclSupport == null || fileSecurity == null) { - IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; - var fileSecurity = aclSupport?.GetAccessControl() as FileSecurity; - if (aclSupport == null || fileSecurity == null) - { - throw new NotSupportedException("The file info does not support ACL extensions"); - } - - return fileSecurity; + throw new NotSupportedException("The file info does not support ACL extensions"); } + return fileSecurity; + } + #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static FileSecurity GetAccessControl( - this IFileInfo fileInfo, - AccessControlSections includeSections) + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl( + this IFileInfo fileInfo, + AccessControlSections includeSections) + { + IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; + var fileSecurity = aclSupport?.GetAccessControl((IFileSystemAclSupport.AccessControlSections)includeSections) as FileSecurity; + if (aclSupport == null || fileSecurity == null) { - IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; - var fileSecurity = aclSupport?.GetAccessControl((IFileSystemAclSupport.AccessControlSections)includeSections) as FileSecurity; - if (aclSupport == null || fileSecurity == null) - { - throw new NotSupportedException("The file info does not support ACL extensions"); - } - - return fileSecurity; + throw new NotSupportedException("The file info does not support ACL extensions"); } + return fileSecurity; + } + #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static void SetAccessControl(this IFileInfo fileInfo, - FileSecurity fileSecurity) + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this IFileInfo fileInfo, + FileSecurity fileSecurity) + { + IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; + if (aclSupport == null) { - IFileSystemAclSupport aclSupport = fileInfo as IFileSystemAclSupport; - if (aclSupport == null) - { - throw new NotSupportedException("The file info does not support ACL extensions"); - } - - aclSupport.SetAccessControl(fileSecurity); + throw new NotSupportedException("The file info does not support ACL extensions"); } + + aclSupport.SetAccessControl(fileSecurity); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoBase.cs index dcde4879c..6057d3043 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoBase.cs @@ -1,102 +1,101 @@ -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class FileInfoBase : FileSystemInfoBase, IFileInfo +public abstract class FileInfoBase : FileSystemInfoBase, IFileInfo +{ + /// + /// Base class for calling methods of + /// + protected FileInfoBase(IFileSystem fileSystem) : base(fileSystem) { - /// - /// Base class for calling methods of - /// - protected FileInfoBase(IFileSystem fileSystem) : base(fileSystem) - { - } + } - [Obsolete("This constructor only exists to support mocking libraries.", error: true)] - internal FileInfoBase() { } + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal FileInfoBase() { } - /// - public abstract StreamWriter AppendText(); + /// + public abstract StreamWriter AppendText(); - /// - public abstract IFileInfo CopyTo(string destFileName); + /// + public abstract IFileInfo CopyTo(string destFileName); - /// - public abstract IFileInfo CopyTo(string destFileName, bool overwrite); + /// + public abstract IFileInfo CopyTo(string destFileName, bool overwrite); - /// - public abstract FileSystemStream Create(); + /// + public abstract FileSystemStream Create(); - /// - public abstract StreamWriter CreateText(); + /// + public abstract StreamWriter CreateText(); - /// - public abstract void Decrypt(); + /// + public abstract void Decrypt(); - /// - public abstract void Encrypt(); + /// + public abstract void Encrypt(); - /// - public abstract void MoveTo(string destFileName); + /// + public abstract void MoveTo(string destFileName); #if FEATURE_FILE_MOVE_WITH_OVERWRITE - /// - public abstract void MoveTo(string destFileName, bool overwrite); + /// + public abstract void MoveTo(string destFileName, bool overwrite); #endif - /// - public abstract FileSystemStream Open(FileMode mode); + /// + public abstract FileSystemStream Open(FileMode mode); - /// - public abstract FileSystemStream Open(FileMode mode, FileAccess access); + /// + public abstract FileSystemStream Open(FileMode mode, FileAccess access); - /// - public abstract FileSystemStream Open(FileMode mode, FileAccess access, FileShare share); + /// + public abstract FileSystemStream Open(FileMode mode, FileAccess access, FileShare share); #if FEATURE_FILESTREAM_OPTIONS - /// - public abstract FileSystemStream Open(FileStreamOptions options); + /// + public abstract FileSystemStream Open(FileStreamOptions options); #endif - /// - public abstract FileSystemStream OpenRead(); + /// + public abstract FileSystemStream OpenRead(); - /// - public abstract StreamReader OpenText(); + /// + public abstract StreamReader OpenText(); - /// - public abstract FileSystemStream OpenWrite(); + /// + public abstract FileSystemStream OpenWrite(); - /// - public abstract IFileInfo Replace(string destinationFileName, string destinationBackupFileName); + /// + public abstract IFileInfo Replace(string destinationFileName, string destinationBackupFileName); - /// - public abstract IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); + /// + public abstract IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); - /// - public abstract IDirectoryInfo Directory { get; } + /// + public abstract IDirectoryInfo Directory { get; } - /// - public abstract string DirectoryName { get; } + /// + public abstract string DirectoryName { get; } - /// - public abstract bool IsReadOnly { get; set; } + /// + public abstract bool IsReadOnly { get; set; } - /// - public abstract long Length { get; } + /// + public abstract long Length { get; } - /// - /// Implicitly converts a to a . - /// - public static implicit operator FileInfoBase(FileInfo fileInfo) + /// + /// Implicitly converts a to a . + /// + public static implicit operator FileInfoBase(FileInfo fileInfo) + { + if (fileInfo == null) { - if (fileInfo == null) - { - return null; - } - - return new FileInfoWrapper(new FileSystem(), fileInfo); + return null; } + + return new FileInfoWrapper(new FileSystem(), fileInfo); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoFactory.cs index f4e2b3a58..06ad00aa7 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoFactory.cs @@ -1,41 +1,39 @@ -namespace System.IO.Abstractions -{ +namespace System.IO.Abstractions; #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - internal class FileInfoFactory : IFileInfoFactory - { - private readonly IFileSystem fileSystem; +internal class FileInfoFactory : IFileInfoFactory +{ + private readonly IFileSystem fileSystem; - /// - /// Base factory class for creating a - /// - public FileInfoFactory(IFileSystem fileSystem) - { - this.fileSystem = fileSystem; - } + /// + /// Base factory class for creating a + /// + public FileInfoFactory(IFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } - /// - public IFileSystem FileSystem - => fileSystem; + /// + public IFileSystem FileSystem + => fileSystem; - /// - public IFileInfo New(string fileName) - { - var realFileInfo = new FileInfo(fileName); - return new FileInfoWrapper(fileSystem, realFileInfo); - } + /// + public IFileInfo New(string fileName) + { + var realFileInfo = new FileInfo(fileName); + return new FileInfoWrapper(fileSystem, realFileInfo); + } - /// - public IFileInfo Wrap(FileInfo fileInfo) + /// + public IFileInfo Wrap(FileInfo fileInfo) + { + if (fileInfo == null) { - if (fileInfo == null) - { - return null; - } - - return new FileInfoWrapper(fileSystem, fileInfo); + return null; } + + return new FileInfoWrapper(fileSystem, fileInfo); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoWrapper.cs index 34b953a15..7192055b0 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileInfoWrapper.cs @@ -1,305 +1,304 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class FileInfoWrapper : FileInfoBase, IFileSystemAclSupport - { - private readonly FileInfo instance; +public class FileInfoWrapper : FileInfoBase, IFileSystemAclSupport +{ + private readonly FileInfo instance; - /// - /// Wrapper class for calling methods of - /// - public FileInfoWrapper(IFileSystem fileSystem, FileInfo instance) : base(fileSystem) - { - this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); - } + /// + /// Wrapper class for calling methods of + /// + public FileInfoWrapper(IFileSystem fileSystem, FileInfo instance) : base(fileSystem) + { + this.instance = instance ?? throw new ArgumentNullException(nameof(instance)); + } #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public override void CreateAsSymbolicLink(string pathToTarget) - { - instance.CreateAsSymbolicLink(pathToTarget); - } + /// + public override void CreateAsSymbolicLink(string pathToTarget) + { + instance.CreateAsSymbolicLink(pathToTarget); + } #endif - /// - public override void Delete() - { - instance.Delete(); - } + /// + public override void Delete() + { + instance.Delete(); + } - /// - public override void Refresh() - { - instance.Refresh(); - } + /// + public override void Refresh() + { + instance.Refresh(); + } #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) - { - return instance.ResolveLinkTarget(returnFinalTarget) - .WrapFileSystemInfo(FileSystem); - } + /// + public override IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget) + { + return instance.ResolveLinkTarget(returnFinalTarget) + .WrapFileSystemInfo(FileSystem); + } #endif - /// - public override FileAttributes Attributes - { - get { return instance.Attributes; } - set { instance.Attributes = value; } - } + /// + public override FileAttributes Attributes + { + get { return instance.Attributes; } + set { instance.Attributes = value; } + } - /// - public override DateTime CreationTime - { - get { return instance.CreationTime; } - set { instance.CreationTime = value; } - } + /// + public override DateTime CreationTime + { + get { return instance.CreationTime; } + set { instance.CreationTime = value; } + } - /// - public override DateTime CreationTimeUtc - { - get { return instance.CreationTimeUtc; } - set { instance.CreationTimeUtc = value; } - } + /// + public override DateTime CreationTimeUtc + { + get { return instance.CreationTimeUtc; } + set { instance.CreationTimeUtc = value; } + } - /// - public override bool Exists - { - get { return instance.Exists; } - } + /// + public override bool Exists + { + get { return instance.Exists; } + } - /// - public override string Extension - { - get { return instance.Extension; } - } + /// + public override string Extension + { + get { return instance.Extension; } + } - /// - public override string FullName - { - get { return instance.FullName; } - } + /// + public override string FullName + { + get { return instance.FullName; } + } - /// - public override DateTime LastAccessTime - { - get { return instance.LastAccessTime; } - set { instance.LastAccessTime = value; } - } + /// + public override DateTime LastAccessTime + { + get { return instance.LastAccessTime; } + set { instance.LastAccessTime = value; } + } - /// - public override DateTime LastAccessTimeUtc - { - get { return instance.LastAccessTimeUtc; } - set { instance.LastAccessTimeUtc = value; } - } + /// + public override DateTime LastAccessTimeUtc + { + get { return instance.LastAccessTimeUtc; } + set { instance.LastAccessTimeUtc = value; } + } - /// - public override DateTime LastWriteTime - { - get { return instance.LastWriteTime; } - set { instance.LastWriteTime = value; } - } + /// + public override DateTime LastWriteTime + { + get { return instance.LastWriteTime; } + set { instance.LastWriteTime = value; } + } - /// - public override DateTime LastWriteTimeUtc - { - get { return instance.LastWriteTimeUtc; } - set { instance.LastWriteTimeUtc = value; } - } + /// + public override DateTime LastWriteTimeUtc + { + get { return instance.LastWriteTimeUtc; } + set { instance.LastWriteTimeUtc = value; } + } #if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET - /// - public override string LinkTarget - { - get { return instance.LinkTarget; } - } + /// + public override string LinkTarget + { + get { return instance.LinkTarget; } + } #endif - /// - public override string Name - { - get { return instance.Name; } - } + /// + public override string Name + { + get { return instance.Name; } + } - /// - public override StreamWriter AppendText() - { - return instance.AppendText(); - } + /// + public override StreamWriter AppendText() + { + return instance.AppendText(); + } - /// - public override IFileInfo CopyTo(string destFileName) - { - return new FileInfoWrapper(FileSystem, instance.CopyTo(destFileName)); - } + /// + public override IFileInfo CopyTo(string destFileName) + { + return new FileInfoWrapper(FileSystem, instance.CopyTo(destFileName)); + } - /// - public override IFileInfo CopyTo(string destFileName, bool overwrite) - { - return new FileInfoWrapper(FileSystem, instance.CopyTo(destFileName, overwrite)); - } + /// + public override IFileInfo CopyTo(string destFileName, bool overwrite) + { + return new FileInfoWrapper(FileSystem, instance.CopyTo(destFileName, overwrite)); + } - /// - public override FileSystemStream Create() - { - return new FileStreamWrapper(instance.Create()); - } + /// + public override FileSystemStream Create() + { + return new FileStreamWrapper(instance.Create()); + } - /// - public override StreamWriter CreateText() - { - return instance.CreateText(); - } + /// + public override StreamWriter CreateText() + { + return instance.CreateText(); + } - /// - [SupportedOSPlatform("windows")] - public override void Decrypt() - { - instance.Decrypt(); - } + /// + [SupportedOSPlatform("windows")] + public override void Decrypt() + { + instance.Decrypt(); + } - /// - [SupportedOSPlatform("windows")] - public override void Encrypt() - { - instance.Encrypt(); - } + /// + [SupportedOSPlatform("windows")] + public override void Encrypt() + { + instance.Encrypt(); + } - /// - public override void MoveTo(string destFileName) - { - instance.MoveTo(destFileName); - } + /// + public override void MoveTo(string destFileName) + { + instance.MoveTo(destFileName); + } #if FEATURE_FILE_MOVE_WITH_OVERWRITE - /// - public override void MoveTo(string destFileName, bool overwrite) - { - instance.MoveTo(destFileName, overwrite); - } + /// + public override void MoveTo(string destFileName, bool overwrite) + { + instance.MoveTo(destFileName, overwrite); + } #endif - /// - public override FileSystemStream Open(FileMode mode) - { - return new FileStreamWrapper(instance.Open(mode)); - } + /// + public override FileSystemStream Open(FileMode mode) + { + return new FileStreamWrapper(instance.Open(mode)); + } - /// - public override FileSystemStream Open(FileMode mode, FileAccess access) - { - return new FileStreamWrapper(instance.Open(mode, access)); - } + /// + public override FileSystemStream Open(FileMode mode, FileAccess access) + { + return new FileStreamWrapper(instance.Open(mode, access)); + } - /// - public override FileSystemStream Open(FileMode mode, FileAccess access, FileShare share) - { - return new FileStreamWrapper(instance.Open(mode, access, share)); - } + /// + public override FileSystemStream Open(FileMode mode, FileAccess access, FileShare share) + { + return new FileStreamWrapper(instance.Open(mode, access, share)); + } #if FEATURE_FILESTREAM_OPTIONS - /// - public override FileSystemStream Open(FileStreamOptions options) - { - return new FileStreamWrapper(instance.Open(options)); - } + /// + public override FileSystemStream Open(FileStreamOptions options) + { + return new FileStreamWrapper(instance.Open(options)); + } #endif - /// - public override FileSystemStream OpenRead() - { - return new FileStreamWrapper(instance.OpenRead()); - } + /// + public override FileSystemStream OpenRead() + { + return new FileStreamWrapper(instance.OpenRead()); + } - /// - public override StreamReader OpenText() - { - return instance.OpenText(); - } + /// + public override StreamReader OpenText() + { + return instance.OpenText(); + } - /// - public override FileSystemStream OpenWrite() - { - return new FileStreamWrapper(instance.OpenWrite()); - } + /// + public override FileSystemStream OpenWrite() + { + return new FileStreamWrapper(instance.OpenWrite()); + } - /// - public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName) - { - return new FileInfoWrapper(FileSystem, instance.Replace(destinationFileName, destinationBackupFileName)); - } + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName) + { + return new FileInfoWrapper(FileSystem, instance.Replace(destinationFileName, destinationBackupFileName)); + } - /// - public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) - { - return new FileInfoWrapper(FileSystem, instance.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors)); - } + /// + public override IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + return new FileInfoWrapper(FileSystem, instance.Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors)); + } - /// - public override IDirectoryInfo Directory - { - get { return new DirectoryInfoWrapper(FileSystem, instance.Directory); } - } + /// + public override IDirectoryInfo Directory + { + get { return new DirectoryInfoWrapper(FileSystem, instance.Directory); } + } - /// - public override string DirectoryName - { - get { return instance.DirectoryName; } - } + /// + public override string DirectoryName + { + get { return instance.DirectoryName; } + } - /// - public override bool IsReadOnly - { - get { return instance.IsReadOnly; } - set { instance.IsReadOnly = value; } - } + /// + public override bool IsReadOnly + { + get { return instance.IsReadOnly; } + set { instance.IsReadOnly = value; } + } - /// - public override long Length - { - get { return instance.Length; } - } + /// + public override long Length + { + get { return instance.Length; } + } - /// - public override string ToString() - { - return instance.ToString(); - } + /// + public override string ToString() + { + return instance.ToString(); + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl() - { - return instance.GetAccessControl(); - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return instance.GetAccessControl(); + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + return instance.GetAccessControl((AccessControlSections)includeSections); + } + + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + if (value is FileSecurity fileSecurity) { - return instance.GetAccessControl((AccessControlSections)includeSections); + this.instance.SetAccessControl(fileSecurity); } - - /// - [SupportedOSPlatform("windows")] - public void SetAccessControl(object value) + else { - if (value is FileSecurity fileSecurity) - { - this.instance.SetAccessControl(fileSecurity); - } - else - { - throw new ArgumentException("value must be of type `FileSecurity`"); - } + throw new ArgumentException("value must be of type `FileSecurity`"); } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamAclExtensions.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamAclExtensions.cs index 9d9da9fb5..06d126519 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamAclExtensions.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamAclExtensions.cs @@ -1,47 +1,46 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +/// +/// ACL (access control list) extension methods for . +/// +public static class FileStreamAclExtensions { - /// - /// ACL (access control list) extension methods for . - /// - public static class FileStreamAclExtensions - { #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static FileSecurity GetAccessControl(this FileSystemStream fileStream) + [SupportedOSPlatform("windows")] + public static FileSecurity GetAccessControl(this FileSystemStream fileStream) + { + IFileSystemAclSupport aclSupport = fileStream as IFileSystemAclSupport; + var fileSecurity = aclSupport?.GetAccessControl() as FileSecurity; + if (aclSupport == null || fileSecurity == null) { - IFileSystemAclSupport aclSupport = fileStream as IFileSystemAclSupport; - var fileSecurity = aclSupport?.GetAccessControl() as FileSecurity; - if (aclSupport == null || fileSecurity == null) - { - throw new NotSupportedException("The file stream does not support ACL extensions"); - } - - return fileSecurity; + throw new NotSupportedException("The file stream does not support ACL extensions"); } + return fileSecurity; + } + #if FEATURE_FILE_SYSTEM_ACL_EXTENSIONS - /// + /// #else /// #endif - [SupportedOSPlatform("windows")] - public static void SetAccessControl(this FileSystemStream fileStream, - FileSecurity fileSecurity) + [SupportedOSPlatform("windows")] + public static void SetAccessControl(this FileSystemStream fileStream, + FileSecurity fileSecurity) + { + IFileSystemAclSupport aclSupport = fileStream as IFileSystemAclSupport; + if (aclSupport == null) { - IFileSystemAclSupport aclSupport = fileStream as IFileSystemAclSupport; - if (aclSupport == null) - { - throw new NotSupportedException("The file info does not support ACL extensions"); - } - - aclSupport.SetAccessControl(fileSecurity); + throw new NotSupportedException("The file info does not support ACL extensions"); } + + aclSupport.SetAccessControl(fileSecurity); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamFactory.cs index f114d84bf..05599230f 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamFactory.cs @@ -1,70 +1,68 @@ using Microsoft.Win32.SafeHandles; -namespace System.IO.Abstractions -{ +namespace System.IO.Abstractions; #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - internal sealed class FileStreamFactory : IFileStreamFactory +internal sealed class FileStreamFactory : IFileStreamFactory +{ + /// + /// Base factory class for creating a + /// + public FileStreamFactory(IFileSystem fileSystem) { - /// - /// Base factory class for creating a - /// - public FileStreamFactory(IFileSystem fileSystem) - { - FileSystem = fileSystem; - } + FileSystem = fileSystem; + } - /// - public IFileSystem FileSystem { get; } + /// + public IFileSystem FileSystem { get; } - /// - public FileSystemStream New(SafeFileHandle handle, FileAccess access) - => new FileStreamWrapper(new FileStream(handle, access)); + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access) + => new FileStreamWrapper(new FileStream(handle, access)); - /// - public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize) - => new FileStreamWrapper(new FileStream(handle, access, bufferSize)); + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize) + => new FileStreamWrapper(new FileStream(handle, access, bufferSize)); - /// - public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) - => new FileStreamWrapper(new FileStream(handle, access, bufferSize, isAsync)); + /// + public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) + => new FileStreamWrapper(new FileStream(handle, access, bufferSize, isAsync)); - /// - public FileSystemStream New(string path, FileMode mode) - => new FileStreamWrapper(new FileStream(path, mode)); + /// + public FileSystemStream New(string path, FileMode mode) + => new FileStreamWrapper(new FileStream(path, mode)); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access) - => new FileStreamWrapper(new FileStream(path, mode, access)); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access) + => new FileStreamWrapper(new FileStream(path, mode, access)); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share) - => new FileStreamWrapper(new FileStream(path, mode, access, share)); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share) + => new FileStreamWrapper(new FileStream(path, mode, access, share)); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) - => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize)); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) + => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize)); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) - => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize, useAsync)); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) + => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize, useAsync)); - /// - public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, - FileOptions options) - => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize, options)); + /// + public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, + FileOptions options) + => new FileStreamWrapper(new FileStream(path, mode, access, share, bufferSize, options)); #if FEATURE_FILESTREAM_OPTIONS - /// - public FileSystemStream New(string path, FileStreamOptions options) - => new FileStreamWrapper(new FileStream(path, options)); + /// + public FileSystemStream New(string path, FileStreamOptions options) + => new FileStreamWrapper(new FileStream(path, options)); #endif - /// - public FileSystemStream Wrap(FileStream fileStream) - => new FileStreamWrapper(fileStream); - } + /// + public FileSystemStream Wrap(FileStream fileStream) + => new FileStreamWrapper(fileStream); } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamWrapper.cs index 2d5755b8a..074251262 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileStreamWrapper.cs @@ -1,49 +1,48 @@ using System.Runtime.Versioning; using System.Security.AccessControl; -namespace System.IO.Abstractions +namespace System.IO.Abstractions; + +internal sealed class FileStreamWrapper : FileSystemStream, IFileSystemAclSupport { - internal sealed class FileStreamWrapper : FileSystemStream, IFileSystemAclSupport - { - private readonly FileStream fileStream; + private readonly FileStream fileStream; - public FileStreamWrapper(FileStream fileStream) - : base(fileStream, fileStream.Name, fileStream.IsAsync) + public FileStreamWrapper(FileStream fileStream) + : base(fileStream, fileStream.Name, fileStream.IsAsync) - { - this.fileStream = fileStream; - } + { + this.fileStream = fileStream; + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl() - { - return fileStream.GetAccessControl(); - } + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl() + { + return fileStream.GetAccessControl(); + } + + /// + [SupportedOSPlatform("windows")] + public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + { + throw new NotSupportedException("GetAccessControl with includeSections is not supported for FileStreams"); + } - /// - [SupportedOSPlatform("windows")] - public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections) + /// + [SupportedOSPlatform("windows")] + public void SetAccessControl(object value) + { + if (value is FileSecurity fileSecurity) { - throw new NotSupportedException("GetAccessControl with includeSections is not supported for FileStreams"); + this.fileStream.SetAccessControl(fileSecurity); } - - /// - [SupportedOSPlatform("windows")] - public void SetAccessControl(object value) + else { - if (value is FileSecurity fileSecurity) - { - this.fileStream.SetAccessControl(fileSecurity); - } - else - { - throw new ArgumentException("value must be of type `FileSecurity`"); - } + throw new ArgumentException("value must be of type `FileSecurity`"); } - - /// - public override void Flush(bool flushToDisk) - => fileStream.Flush(flushToDisk); } + + /// + public override void Flush(bool flushToDisk) + => fileStream.Flush(flushToDisk); } \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystem.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystem.cs index 1e9cfca2b..816df7ccd 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystem.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystem.cs @@ -1,50 +1,49 @@ -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class FileSystem : FileSystemBase +public class FileSystem : FileSystemBase +{ + /// + public FileSystem() { - /// - public FileSystem() - { - DriveInfo = new DriveInfoFactory(this); - DirectoryInfo = new DirectoryInfoFactory(this); - FileInfo = new FileInfoFactory(this); - FileVersionInfo = new FileVersionInfoFactory(this); - Path = new PathWrapper(this); - File = new FileWrapper(this); - Directory = new DirectoryWrapper(this); - FileStream = new FileStreamFactory(this); - FileSystemWatcher = new FileSystemWatcherFactory(this); - } - - /// - public override IDirectory Directory { get; } - - /// - public override IFile File { get; } - - /// - public override IFileInfoFactory FileInfo { get; } - - /// - public override IFileVersionInfoFactory FileVersionInfo { get; } - - /// - public override IFileStreamFactory FileStream { get; } - - /// - public override IPath Path { get; } - - /// - public override IDirectoryInfoFactory DirectoryInfo { get; } - - /// - public override IDriveInfoFactory DriveInfo { get; } - - /// - public override IFileSystemWatcherFactory FileSystemWatcher { get; } + DriveInfo = new DriveInfoFactory(this); + DirectoryInfo = new DirectoryInfoFactory(this); + FileInfo = new FileInfoFactory(this); + FileVersionInfo = new FileVersionInfoFactory(this); + Path = new PathWrapper(this); + File = new FileWrapper(this); + Directory = new DirectoryWrapper(this); + FileStream = new FileStreamFactory(this); + FileSystemWatcher = new FileSystemWatcherFactory(this); } -} + + /// + public override IDirectory Directory { get; } + + /// + public override IFile File { get; } + + /// + public override IFileInfoFactory FileInfo { get; } + + /// + public override IFileVersionInfoFactory FileVersionInfo { get; } + + /// + public override IFileStreamFactory FileStream { get; } + + /// + public override IPath Path { get; } + + /// + public override IDirectoryInfoFactory DirectoryInfo { get; } + + /// + public override IDriveInfoFactory DriveInfo { get; } + + /// + public override IFileSystemWatcherFactory FileSystemWatcher { get; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemBase.cs index b851d9eaa..9a151ccac 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemBase.cs @@ -1,36 +1,35 @@ -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class FileSystemBase : IFileSystem - { - /// - public abstract IDirectory Directory { get; } +public abstract class FileSystemBase : IFileSystem +{ + /// + public abstract IDirectory Directory { get; } - /// - public abstract IFile File { get; } + /// + public abstract IFile File { get; } - /// - public abstract IFileInfoFactory FileInfo { get; } + /// + public abstract IFileInfoFactory FileInfo { get; } - /// - public abstract IFileVersionInfoFactory FileVersionInfo { get; } + /// + public abstract IFileVersionInfoFactory FileVersionInfo { get; } - /// - public abstract IFileStreamFactory FileStream { get; } + /// + public abstract IFileStreamFactory FileStream { get; } - /// - public abstract IPath Path { get; } + /// + public abstract IPath Path { get; } - /// - public abstract IDirectoryInfoFactory DirectoryInfo { get; } + /// + public abstract IDirectoryInfoFactory DirectoryInfo { get; } - /// - public abstract IDriveInfoFactory DriveInfo { get; } + /// + public abstract IDriveInfoFactory DriveInfo { get; } - /// - public abstract IFileSystemWatcherFactory FileSystemWatcher { get; } - } -} + /// + public abstract IFileSystemWatcherFactory FileSystemWatcher { get; } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemInfoBase.cs index b98a89ffe..7156c1e5d 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemInfoBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemInfoBase.cs @@ -1,82 +1,82 @@ using System.Runtime.Versioning; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class FileSystemInfoBase : IFileSystemInfo +public abstract class FileSystemInfoBase : IFileSystemInfo +{ + /// + /// Base class for calling methods of + /// + protected FileSystemInfoBase(IFileSystem fileSystem) { - /// - /// Base class for calling methods of - /// - protected FileSystemInfoBase(IFileSystem fileSystem) - { - FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); - } + FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + } - [Obsolete("This constructor only exists to support mocking libraries.", error: true)] - internal FileSystemInfoBase() { } + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal FileSystemInfoBase() { } - /// - /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. - /// - public IFileSystem FileSystem { get; } + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public abstract void CreateAsSymbolicLink(string pathToTarget); + /// + public abstract void CreateAsSymbolicLink(string pathToTarget); #endif - /// - public abstract void Delete(); + /// + public abstract void Delete(); - /// - public abstract void Refresh(); + /// + public abstract void Refresh(); #if FEATURE_CREATE_SYMBOLIC_LINK - /// - public abstract IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget); + /// + public abstract IFileSystemInfo ResolveLinkTarget(bool returnFinalTarget); #endif - /// - public abstract FileAttributes Attributes { get; set; } + /// + public abstract FileAttributes Attributes { get; set; } - /// - public abstract DateTime CreationTime { get; set; } + /// + public abstract DateTime CreationTime { get; set; } - /// - public abstract DateTime CreationTimeUtc { get; set; } + /// + public abstract DateTime CreationTimeUtc { get; set; } - /// - public abstract bool Exists { get; } + /// + public abstract bool Exists { get; } - /// - public abstract string Extension { get; } + /// + public abstract string Extension { get; } - /// - public abstract string FullName { get; } + /// + public abstract string FullName { get; } - /// - public abstract DateTime LastAccessTime { get; set; } + /// + public abstract DateTime LastAccessTime { get; set; } - /// - public abstract DateTime LastAccessTimeUtc { get; set; } + /// + public abstract DateTime LastAccessTimeUtc { get; set; } - /// - public abstract DateTime LastWriteTime { get; set; } + /// + public abstract DateTime LastWriteTime { get; set; } - /// - public abstract DateTime LastWriteTimeUtc { get; set; } + /// + public abstract DateTime LastWriteTimeUtc { get; set; } #if FEATURE_FILE_SYSTEM_INFO_LINK_TARGET - /// - public abstract string LinkTarget { get; } + /// + public abstract string LinkTarget { get; } #endif - /// - public abstract string Name { get; } + /// + public abstract string Name { get; } #if FEATURE_UNIX_FILE_MODE /// @@ -86,5 +86,4 @@ public UnixFileMode UnixFileMode [UnsupportedOSPlatform("windows")] set; } #endif - } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherBase.cs index f44ed657e..a51189121 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherBase.cs @@ -1,146 +1,145 @@ using System.ComponentModel; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class FileSystemWatcherBase : IFileSystemWatcher - { - /// - public abstract IFileSystem FileSystem { get; } +public abstract class FileSystemWatcherBase : IFileSystemWatcher +{ + /// + public abstract IFileSystem FileSystem { get; } - /// - public abstract bool IncludeSubdirectories { get; set; } + /// + public abstract bool IncludeSubdirectories { get; set; } - /// - public abstract IContainer Container { get; } + /// + public abstract IContainer Container { get; } - /// - public abstract bool EnableRaisingEvents { get; set; } + /// + public abstract bool EnableRaisingEvents { get; set; } - /// - public abstract string Filter { get; set; } + /// + public abstract string Filter { get; set; } #if FEATURE_FILE_SYSTEM_WATCHER_FILTERS - /// - public abstract Collections.ObjectModel.Collection Filters { get; } + /// + public abstract Collections.ObjectModel.Collection Filters { get; } #endif - /// - public abstract int InternalBufferSize { get; set; } + /// + public abstract int InternalBufferSize { get; set; } - /// - public abstract NotifyFilters NotifyFilter { get; set; } + /// + public abstract NotifyFilters NotifyFilter { get; set; } - /// - public abstract string Path { get; set; } + /// + public abstract string Path { get; set; } - /// - public abstract ISite Site { get; set; } + /// + public abstract ISite Site { get; set; } - /// - public abstract ISynchronizeInvoke SynchronizingObject { get; set; } + /// + public abstract ISynchronizeInvoke SynchronizingObject { get; set; } - /// - public virtual event FileSystemEventHandler Changed; + /// + public virtual event FileSystemEventHandler Changed; - /// - public virtual event FileSystemEventHandler Created; + /// + public virtual event FileSystemEventHandler Created; - /// - public virtual event FileSystemEventHandler Deleted; + /// + public virtual event FileSystemEventHandler Deleted; - /// - public virtual event ErrorEventHandler Error; + /// + public virtual event ErrorEventHandler Error; - /// - public virtual event RenamedEventHandler Renamed; + /// + public virtual event RenamedEventHandler Renamed; - /// - public abstract void BeginInit(); + /// + public abstract void BeginInit(); - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } - /// - public abstract void EndInit(); + /// + public abstract void EndInit(); - /// - public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType); + /// + public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType); - /// - public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout); + /// + public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout); #if FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN /// public abstract IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout); #endif - /// - /// Implicitly converts a to a . - /// - public static implicit operator FileSystemWatcherBase(FileSystemWatcher watcher) + /// + /// Implicitly converts a to a . + /// + public static implicit operator FileSystemWatcherBase(FileSystemWatcher watcher) + { + if (watcher == null) { - if (watcher == null) - { - return null; - } - - return new FileSystemWatcherWrapper(new FileSystem(), watcher); + return null; } - /// - /// Callback executed during - /// - public virtual void Dispose(bool disposing) - { - // do nothing - } + return new FileSystemWatcherWrapper(new FileSystem(), watcher); + } - /// - /// Invokes the event. - /// - protected void OnCreated(object sender, FileSystemEventArgs args) - { - Created?.Invoke(sender, args); - } + /// + /// Callback executed during + /// + public virtual void Dispose(bool disposing) + { + // do nothing + } - /// - /// Invokes the event. - /// - protected void OnChanged(object sender, FileSystemEventArgs args) - { - Changed?.Invoke(sender, args); - } + /// + /// Invokes the event. + /// + protected void OnCreated(object sender, FileSystemEventArgs args) + { + Created?.Invoke(sender, args); + } - /// - /// Invokes the event. - /// - protected void OnDeleted(object sender, FileSystemEventArgs args) - { - Deleted?.Invoke(sender, args); - } + /// + /// Invokes the event. + /// + protected void OnChanged(object sender, FileSystemEventArgs args) + { + Changed?.Invoke(sender, args); + } - /// - /// Invokes the event. - /// - protected void OnRenamed(object sender, RenamedEventArgs args) - { - Renamed?.Invoke(sender, args); - } + /// + /// Invokes the event. + /// + protected void OnDeleted(object sender, FileSystemEventArgs args) + { + Deleted?.Invoke(sender, args); + } - /// - /// Invokes the event. - /// - protected void OnError(object sender, ErrorEventArgs args) - { - Error?.Invoke(sender, args); - } + /// + /// Invokes the event. + /// + protected void OnRenamed(object sender, RenamedEventArgs args) + { + Renamed?.Invoke(sender, args); + } + + /// + /// Invokes the event. + /// + protected void OnError(object sender, ErrorEventArgs args) + { + Error?.Invoke(sender, args); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherFactory.cs index dbd47ad5b..662483524 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherFactory.cs @@ -1,43 +1,42 @@ -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class FileSystemWatcherFactory : IFileSystemWatcherFactory +public class FileSystemWatcherFactory : IFileSystemWatcherFactory +{ + /// + /// Base factory class for creating a + /// + public FileSystemWatcherFactory(IFileSystem fileSystem) { - /// - /// Base factory class for creating a - /// - public FileSystemWatcherFactory(IFileSystem fileSystem) - { - FileSystem = fileSystem; - } + FileSystem = fileSystem; + } - /// - public IFileSystem FileSystem { get; } + /// + public IFileSystem FileSystem { get; } - /// - public IFileSystemWatcher New() - => new FileSystemWatcherWrapper(FileSystem); + /// + public IFileSystemWatcher New() + => new FileSystemWatcherWrapper(FileSystem); - /// - public IFileSystemWatcher New(string path) - => new FileSystemWatcherWrapper(FileSystem, path); + /// + public IFileSystemWatcher New(string path) + => new FileSystemWatcherWrapper(FileSystem, path); - /// - public IFileSystemWatcher New(string path, string filter) - => new FileSystemWatcherWrapper(FileSystem, path, filter); + /// + public IFileSystemWatcher New(string path, string filter) + => new FileSystemWatcherWrapper(FileSystem, path, filter); - /// - public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + /// + public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + { + if (fileSystemWatcher == null) { - if (fileSystemWatcher == null) - { - return null; - } - - return new FileSystemWatcherWrapper(FileSystem, fileSystemWatcher); + return null; } + + return new FileSystemWatcherWrapper(FileSystem, fileSystemWatcher); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherWrapper.cs index 5900b75c5..69af6ae6b 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileSystemWatcherWrapper.cs @@ -1,78 +1,78 @@ using System.ComponentModel; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class FileSystemWatcherWrapper : FileSystemWatcherBase - { +public class FileSystemWatcherWrapper : FileSystemWatcherBase +{ #if FEATURE_SERIALIZABLE - [NonSerialized] + [NonSerialized] #endif - private readonly FileSystemWatcher watcher; + private readonly FileSystemWatcher watcher; - /// - public FileSystemWatcherWrapper(IFileSystem fileSystem) - : this(fileSystem, new FileSystemWatcher()) - { - // do nothing - } + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem) + : this(fileSystem, new FileSystemWatcher()) + { + // do nothing + } - /// - public FileSystemWatcherWrapper(IFileSystem fileSystem, string path) - : this(fileSystem, new FileSystemWatcher(path)) - { - // do nothing - } + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem, string path) + : this(fileSystem, new FileSystemWatcher(path)) + { + // do nothing + } - /// - public FileSystemWatcherWrapper(IFileSystem fileSystem, string path, string filter) - : this(fileSystem, new FileSystemWatcher(path, filter)) - { - // do nothing - } + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem, string path, string filter) + : this(fileSystem, new FileSystemWatcher(path, filter)) + { + // do nothing + } - /// - public FileSystemWatcherWrapper(IFileSystem fileSystem, FileSystemWatcher watcher) - { - FileSystem = fileSystem; - this.watcher = watcher ?? throw new ArgumentNullException(nameof(watcher)); - this.watcher.Created += OnCreated; - this.watcher.Changed += OnChanged; - this.watcher.Deleted += OnDeleted; - this.watcher.Error += OnError; - this.watcher.Renamed += OnRenamed; - } + /// + public FileSystemWatcherWrapper(IFileSystem fileSystem, FileSystemWatcher watcher) + { + FileSystem = fileSystem; + this.watcher = watcher ?? throw new ArgumentNullException(nameof(watcher)); + this.watcher.Created += OnCreated; + this.watcher.Changed += OnChanged; + this.watcher.Deleted += OnDeleted; + this.watcher.Error += OnError; + this.watcher.Renamed += OnRenamed; + } - /// - public override IFileSystem FileSystem { get; } + /// + public override IFileSystem FileSystem { get; } - /// - public override bool IncludeSubdirectories - { - get { return watcher.IncludeSubdirectories; } - set { watcher.IncludeSubdirectories = value; } - } + /// + public override bool IncludeSubdirectories + { + get { return watcher.IncludeSubdirectories; } + set { watcher.IncludeSubdirectories = value; } + } - /// - public override IContainer Container - => watcher.Container; + /// + public override IContainer Container + => watcher.Container; - /// - public override bool EnableRaisingEvents - { - get { return watcher.EnableRaisingEvents; } - set { watcher.EnableRaisingEvents = value; } - } + /// + public override bool EnableRaisingEvents + { + get { return watcher.EnableRaisingEvents; } + set { watcher.EnableRaisingEvents = value; } + } - /// - public override string Filter - { - get { return watcher.Filter; } - set { watcher.Filter = value; } - } + /// + public override string Filter + { + get { return watcher.Filter; } + set { watcher.Filter = value; } + } #if FEATURE_FILE_SYSTEM_WATCHER_FILTERS /// @@ -82,133 +82,132 @@ public override Collections.ObjectModel.Collection Filters } #endif - /// - public override int InternalBufferSize - { - get { return watcher.InternalBufferSize; } - set { watcher.InternalBufferSize = value; } - } + /// + public override int InternalBufferSize + { + get { return watcher.InternalBufferSize; } + set { watcher.InternalBufferSize = value; } + } - /// - public override NotifyFilters NotifyFilter - { - get { return watcher.NotifyFilter; } - set { watcher.NotifyFilter = value; } - } + /// + public override NotifyFilters NotifyFilter + { + get { return watcher.NotifyFilter; } + set { watcher.NotifyFilter = value; } + } - /// - public override string Path - { - get { return watcher.Path; } - set { watcher.Path = value; } - } + /// + public override string Path + { + get { return watcher.Path; } + set { watcher.Path = value; } + } - /// - public override ISite Site - { - get { return watcher.Site; } - set { watcher.Site = value; } - } + /// + public override ISite Site + { + get { return watcher.Site; } + set { watcher.Site = value; } + } - /// - public override ISynchronizeInvoke SynchronizingObject - { - get { return watcher.SynchronizingObject; } - set { watcher.SynchronizingObject = value; } - } + /// + public override ISynchronizeInvoke SynchronizingObject + { + get { return watcher.SynchronizingObject; } + set { watcher.SynchronizingObject = value; } + } - /// - public override void BeginInit() - { - watcher.BeginInit(); - } + /// + public override void BeginInit() + { + watcher.BeginInit(); + } - /// - public override void Dispose(bool disposing) + /// + public override void Dispose(bool disposing) + { + if (disposing) { - if (disposing) - { - watcher.Created -= OnCreated; - watcher.Changed -= OnChanged; - watcher.Deleted -= OnDeleted; - watcher.Error -= OnError; - watcher.Renamed -= OnRenamed; - watcher.Dispose(); - } - - base.Dispose(disposing); + watcher.Created -= OnCreated; + watcher.Changed -= OnChanged; + watcher.Deleted -= OnDeleted; + watcher.Error -= OnError; + watcher.Renamed -= OnRenamed; + watcher.Dispose(); } + base.Dispose(disposing); + } + + /// + public override void EndInit() + { + watcher.EndInit(); + } + + /// + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) + { + return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType)); + } + + /// + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) + { + return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType, timeout)); + } + +#if FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN /// - public override void EndInit() + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout) { - watcher.EndInit(); + return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType, timeout)); } +#endif - /// - public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) + private readonly struct WaitForChangedResultWrapper + : IWaitForChangedResult, IEquatable + { + private readonly WaitForChangedResult instance; + + public WaitForChangedResultWrapper(WaitForChangedResult instance) { - return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType)); + this.instance = instance; } - /// - public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) + /// + public WatcherChangeTypes ChangeType + => instance.ChangeType; + + /// + public string Name + => instance.Name; + + /// + public string OldName + => instance.OldName; + + /// + public bool TimedOut + => instance.TimedOut; + + /// + public bool Equals(WaitForChangedResultWrapper other) { - return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType, timeout)); + return instance.Equals(other.instance); } -#if FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN - /// - public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout) + /// + public override bool Equals(object obj) { - return new WaitForChangedResultWrapper(watcher.WaitForChanged(changeType, timeout)); + return obj is WaitForChangedResultWrapper other + && Equals(other); } -#endif - private readonly struct WaitForChangedResultWrapper - : IWaitForChangedResult, IEquatable + /// + public override int GetHashCode() { - private readonly WaitForChangedResult instance; - - public WaitForChangedResultWrapper(WaitForChangedResult instance) - { - this.instance = instance; - } - - /// - public WatcherChangeTypes ChangeType - => instance.ChangeType; - - /// - public string Name - => instance.Name; - - /// - public string OldName - => instance.OldName; - - /// - public bool TimedOut - => instance.TimedOut; - - /// - public bool Equals(WaitForChangedResultWrapper other) - { - return instance.Equals(other.instance); - } - - /// - public override bool Equals(object obj) - { - return obj is WaitForChangedResultWrapper other - && Equals(other); - } - - /// - public override int GetHashCode() - { - return instance.GetHashCode(); - } + return instance.GetHashCode(); } } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoBase.cs index ff817905a..9545833f2 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoBase.cs @@ -1,108 +1,107 @@ using System.Diagnostics; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class FileVersionInfoBase : IFileVersionInfo - { - /// - public abstract string Comments { get; } +public abstract class FileVersionInfoBase : IFileVersionInfo +{ + /// + public abstract string Comments { get; } - /// - public abstract string CompanyName { get; } + /// + public abstract string CompanyName { get; } - /// - public abstract int FileBuildPart { get; } + /// + public abstract int FileBuildPart { get; } - /// - public abstract string FileDescription { get; } + /// + public abstract string FileDescription { get; } - /// - public abstract int FileMajorPart { get; } + /// + public abstract int FileMajorPart { get; } - /// - public abstract int FileMinorPart { get; } + /// + public abstract int FileMinorPart { get; } - /// - public abstract string FileName { get; } + /// + public abstract string FileName { get; } - /// - public abstract int FilePrivatePart { get; } + /// + public abstract int FilePrivatePart { get; } - /// - public abstract string FileVersion { get; } + /// + public abstract string FileVersion { get; } - /// - public abstract string InternalName { get; } + /// + public abstract string InternalName { get; } - /// - public abstract bool IsDebug { get; } + /// + public abstract bool IsDebug { get; } - /// - public abstract bool IsPatched { get; } + /// + public abstract bool IsPatched { get; } - /// - public abstract bool IsPrivateBuild { get; } + /// + public abstract bool IsPrivateBuild { get; } - /// - public abstract bool IsPreRelease { get; } + /// + public abstract bool IsPreRelease { get; } - /// - public abstract bool IsSpecialBuild { get; } + /// + public abstract bool IsSpecialBuild { get; } - /// - public abstract string Language { get; } + /// + public abstract string Language { get; } - /// - public abstract string LegalCopyright { get; } + /// + public abstract string LegalCopyright { get; } - /// - public abstract string LegalTrademarks { get; } + /// + public abstract string LegalTrademarks { get; } - /// - public abstract string OriginalFilename { get; } + /// + public abstract string OriginalFilename { get; } - /// - public abstract string PrivateBuild { get; } + /// + public abstract string PrivateBuild { get; } - /// - public abstract int ProductBuildPart { get; } + /// + public abstract int ProductBuildPart { get; } - /// - public abstract int ProductMajorPart { get; } + /// + public abstract int ProductMajorPart { get; } - /// - public abstract int ProductMinorPart { get; } + /// + public abstract int ProductMinorPart { get; } - /// - public abstract string ProductName { get; } + /// + public abstract string ProductName { get; } - /// - public abstract int ProductPrivatePart { get; } + /// + public abstract int ProductPrivatePart { get; } - /// - public abstract string ProductVersion { get; } + /// + public abstract string ProductVersion { get; } - /// - public abstract string SpecialBuild { get; } + /// + public abstract string SpecialBuild { get; } - /// - /// Implicitly converts a to a . - /// - public static implicit operator FileVersionInfoBase(FileVersionInfo fileVersionInfo) + /// + /// Implicitly converts a to a . + /// + public static implicit operator FileVersionInfoBase(FileVersionInfo fileVersionInfo) + { + if (fileVersionInfo == null) { - if (fileVersionInfo == null) - { - return null; - } - - return new FileVersionInfoWrapper(fileVersionInfo); + return null; } - /// - public new abstract string ToString(); + return new FileVersionInfoWrapper(fileVersionInfo); } -} + + /// + public new abstract string ToString(); +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoFactory.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoFactory.cs index 457cf3978..d9def793e 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoFactory.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoFactory.cs @@ -1,29 +1,27 @@ -namespace System.IO.Abstractions -{ +namespace System.IO.Abstractions; #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - internal class FileVersionInfoFactory : IFileVersionInfoFactory - { - private readonly IFileSystem fileSystem; +internal class FileVersionInfoFactory : IFileVersionInfoFactory +{ + private readonly IFileSystem fileSystem; - /// - /// Base factory class for creating a - /// - public FileVersionInfoFactory(IFileSystem fileSystem) - { - this.fileSystem = fileSystem; - } + /// + /// Base factory class for creating a + /// + public FileVersionInfoFactory(IFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } - /// - public IFileSystem FileSystem => fileSystem; + /// + public IFileSystem FileSystem => fileSystem; - /// - public IFileVersionInfo GetVersionInfo(string fileName) - { - Diagnostics.FileVersionInfo fileVersionInfo = Diagnostics.FileVersionInfo.GetVersionInfo(fileName); + /// + public IFileVersionInfo GetVersionInfo(string fileName) + { + Diagnostics.FileVersionInfo fileVersionInfo = Diagnostics.FileVersionInfo.GetVersionInfo(fileName); - return new FileVersionInfoWrapper(fileVersionInfo); - } + return new FileVersionInfoWrapper(fileVersionInfo); } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoWrapper.cs index 999864475..4e677f460 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileVersionInfoWrapper.cs @@ -1,187 +1,186 @@ using System.Diagnostics; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class FileVersionInfoWrapper : FileVersionInfoBase - { - private readonly FileVersionInfo instance; - - /// - public FileVersionInfoWrapper(FileVersionInfo fileVersionInfo) - { - instance = fileVersionInfo; - } - - /// - public override string Comments - { - get { return instance.Comments; } - } - - /// - public override string CompanyName - { - get { return instance.CompanyName; } - } - - /// - public override int FileBuildPart - { - get { return instance.FileBuildPart; } - } - - /// - public override string FileDescription - { - get { return instance.FileDescription; } - } - - /// - public override int FileMajorPart - { - get { return instance.FileMajorPart; } - } - - /// - public override int FileMinorPart - { - get { return instance.FileMinorPart; } - } - - /// - public override string FileName - { - get { return instance.FileName; } - } - - /// - public override int FilePrivatePart - { - get { return instance.FilePrivatePart; } - } - - /// - public override string FileVersion - { - get { return instance.FileVersion; } - } - - /// - public override string InternalName - { - get { return instance.InternalName; } - } - - /// - public override bool IsDebug - { - get { return instance.IsDebug; } - } - - /// - public override bool IsPatched - { - get { return instance.IsPatched; } - } - - /// - public override bool IsPrivateBuild - { - get { return instance.IsPrivateBuild; } - } - - /// - public override bool IsPreRelease - { - get { return instance.IsPreRelease; } - } - - /// - public override bool IsSpecialBuild - { - get { return instance.IsSpecialBuild; } - } - - /// - public override string Language - { - get { return instance.Language; } - } - - /// - public override string LegalCopyright - { - get { return instance.LegalCopyright; } - } - - /// - public override string LegalTrademarks - { - get { return instance.LegalTrademarks; } - } - - /// - public override string OriginalFilename - { - get { return instance.OriginalFilename; } - } - - /// - public override string PrivateBuild - { - get { return instance.PrivateBuild; } - } - - /// - public override int ProductBuildPart - { - get { return instance.ProductBuildPart; } - } - - /// - public override int ProductMajorPart - { - get { return instance.ProductMajorPart; } - } - - /// - public override int ProductMinorPart - { - get { return instance.ProductMinorPart; } - } - - /// - public override string ProductName - { - get { return instance.ProductName; } - } - - /// - public override int ProductPrivatePart - { - get { return instance.ProductPrivatePart; } - } - - /// - public override string ProductVersion - { - get { return instance.ProductVersion; } - } - - /// - public override string SpecialBuild - { - get { return instance.SpecialBuild; } - } - - /// - public override string ToString() - { - return instance.ToString(); - } - } -} +public class FileVersionInfoWrapper : FileVersionInfoBase +{ + private readonly FileVersionInfo instance; + + /// + public FileVersionInfoWrapper(FileVersionInfo fileVersionInfo) + { + instance = fileVersionInfo; + } + + /// + public override string Comments + { + get { return instance.Comments; } + } + + /// + public override string CompanyName + { + get { return instance.CompanyName; } + } + + /// + public override int FileBuildPart + { + get { return instance.FileBuildPart; } + } + + /// + public override string FileDescription + { + get { return instance.FileDescription; } + } + + /// + public override int FileMajorPart + { + get { return instance.FileMajorPart; } + } + + /// + public override int FileMinorPart + { + get { return instance.FileMinorPart; } + } + + /// + public override string FileName + { + get { return instance.FileName; } + } + + /// + public override int FilePrivatePart + { + get { return instance.FilePrivatePart; } + } + + /// + public override string FileVersion + { + get { return instance.FileVersion; } + } + + /// + public override string InternalName + { + get { return instance.InternalName; } + } + + /// + public override bool IsDebug + { + get { return instance.IsDebug; } + } + + /// + public override bool IsPatched + { + get { return instance.IsPatched; } + } + + /// + public override bool IsPrivateBuild + { + get { return instance.IsPrivateBuild; } + } + + /// + public override bool IsPreRelease + { + get { return instance.IsPreRelease; } + } + + /// + public override bool IsSpecialBuild + { + get { return instance.IsSpecialBuild; } + } + + /// + public override string Language + { + get { return instance.Language; } + } + + /// + public override string LegalCopyright + { + get { return instance.LegalCopyright; } + } + + /// + public override string LegalTrademarks + { + get { return instance.LegalTrademarks; } + } + + /// + public override string OriginalFilename + { + get { return instance.OriginalFilename; } + } + + /// + public override string PrivateBuild + { + get { return instance.PrivateBuild; } + } + + /// + public override int ProductBuildPart + { + get { return instance.ProductBuildPart; } + } + + /// + public override int ProductMajorPart + { + get { return instance.ProductMajorPart; } + } + + /// + public override int ProductMinorPart + { + get { return instance.ProductMinorPart; } + } + + /// + public override string ProductName + { + get { return instance.ProductName; } + } + + /// + public override int ProductPrivatePart + { + get { return instance.ProductPrivatePart; } + } + + /// + public override string ProductVersion + { + get { return instance.ProductVersion; } + } + + /// + public override string SpecialBuild + { + get { return instance.SpecialBuild; } + } + + /// + public override string ToString() + { + return instance.ToString(); + } +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.cs index 12cc91fe8..d240ee059 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/FileWrapper.cs @@ -3,18 +3,18 @@ using System.Text; using Microsoft.Win32.SafeHandles; -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public partial class FileWrapper : FileBase +public partial class FileWrapper : FileBase +{ + /// + public FileWrapper(IFileSystem fileSystem) : base(fileSystem) { - /// - public FileWrapper(IFileSystem fileSystem) : base(fileSystem) - { - } + } #if FEATURE_FILE_SPAN /// @@ -30,30 +30,30 @@ public override void AppendAllBytes(string path, ReadOnlySpan bytes) } #endif - /// - public override void AppendAllLines(string path, IEnumerable contents) - { - File.AppendAllLines(path, contents); - } + /// + public override void AppendAllLines(string path, IEnumerable contents) + { + File.AppendAllLines(path, contents); + } - /// - public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) - { - File.AppendAllLines(path, contents, encoding); - } + /// + public override void AppendAllLines(string path, IEnumerable contents, Encoding encoding) + { + File.AppendAllLines(path, contents, encoding); + } - /// - public override void AppendAllText(string path, string contents) - { - File.AppendAllText(path, contents); - } + /// + public override void AppendAllText(string path, string contents) + { + File.AppendAllText(path, contents); + } - /// - public override void AppendAllText(string path, string contents, Encoding encoding) - { - File.AppendAllText(path, contents, encoding); - } + /// + public override void AppendAllText(string path, string contents, Encoding encoding) + { + File.AppendAllText(path, contents, encoding); + } #if FEATURE_FILE_SPAN /// @@ -69,41 +69,41 @@ public override void AppendAllText(string path, ReadOnlySpan contents, Enc } #endif - /// - public override StreamWriter AppendText(string path) - { - return File.AppendText(path); - } + /// + public override StreamWriter AppendText(string path) + { + return File.AppendText(path); + } - /// - public override void Copy(string sourceFileName, string destFileName) - { - File.Copy(sourceFileName, destFileName); - } + /// + public override void Copy(string sourceFileName, string destFileName) + { + File.Copy(sourceFileName, destFileName); + } - /// - public override void Copy(string sourceFileName, string destFileName, bool overwrite) - { - File.Copy(sourceFileName, destFileName, overwrite); - } + /// + public override void Copy(string sourceFileName, string destFileName, bool overwrite) + { + File.Copy(sourceFileName, destFileName, overwrite); + } - /// - public override FileSystemStream Create(string path) - { - return new FileStreamWrapper(File.Create(path)); - } + /// + public override FileSystemStream Create(string path) + { + return new FileStreamWrapper(File.Create(path)); + } - /// - public override FileSystemStream Create(string path, int bufferSize) - { - return new FileStreamWrapper(File.Create(path, bufferSize)); - } + /// + public override FileSystemStream Create(string path, int bufferSize) + { + return new FileStreamWrapper(File.Create(path, bufferSize)); + } - /// - public override FileSystemStream Create(string path, int bufferSize, FileOptions options) - { - return new FileStreamWrapper(File.Create(path, bufferSize, options)); - } + /// + public override FileSystemStream Create(string path, int bufferSize, FileOptions options) + { + return new FileStreamWrapper(File.Create(path, bufferSize, options)); + } #if FEATURE_CREATE_SYMBOLIC_LINK /// @@ -113,43 +113,43 @@ public override IFileSystemInfo CreateSymbolicLink(string path, string pathToTar .WrapFileSystemInfo(FileSystem); } #endif - /// - public override StreamWriter CreateText(string path) - { - return File.CreateText(path); - } + /// + public override StreamWriter CreateText(string path) + { + return File.CreateText(path); + } - /// - [SupportedOSPlatform("windows")] - public override void Decrypt(string path) - { - File.Decrypt(path); - } + /// + [SupportedOSPlatform("windows")] + public override void Decrypt(string path) + { + File.Decrypt(path); + } - /// - public override void Delete(string path) - { - File.Delete(path); - } + /// + public override void Delete(string path) + { + File.Delete(path); + } - /// - [SupportedOSPlatform("windows")] - public override void Encrypt(string path) - { - File.Encrypt(path); - } + /// + [SupportedOSPlatform("windows")] + public override void Encrypt(string path) + { + File.Encrypt(path); + } - /// - public override bool Exists(string path) - { - return File.Exists(path); - } + /// + public override bool Exists(string path) + { + return File.Exists(path); + } - /// - public override FileAttributes GetAttributes(string path) - { - return File.GetAttributes(path); - } + /// + public override FileAttributes GetAttributes(string path) + { + return File.GetAttributes(path); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -159,11 +159,11 @@ public override FileAttributes GetAttributes(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetCreationTime(string path) - { - return File.GetCreationTime(path); - } + /// + public override DateTime GetCreationTime(string path) + { + return File.GetCreationTime(path); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -173,11 +173,11 @@ public override DateTime GetCreationTime(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetCreationTimeUtc(string path) - { - return File.GetCreationTimeUtc(path); - } + /// + public override DateTime GetCreationTimeUtc(string path) + { + return File.GetCreationTimeUtc(path); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -187,11 +187,11 @@ public override DateTime GetCreationTimeUtc(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastAccessTime(string path) - { - return File.GetLastAccessTime(path); - } + /// + public override DateTime GetLastAccessTime(string path) + { + return File.GetLastAccessTime(path); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -201,11 +201,11 @@ public override DateTime GetLastAccessTime(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastAccessTimeUtc(string path) - { - return File.GetLastAccessTimeUtc(path); - } + /// + public override DateTime GetLastAccessTimeUtc(string path) + { + return File.GetLastAccessTimeUtc(path); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -215,11 +215,11 @@ public override DateTime GetLastAccessTimeUtc(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastWriteTime(string path) - { - return File.GetLastWriteTime(path); - } + /// + public override DateTime GetLastWriteTime(string path) + { + return File.GetLastWriteTime(path); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -229,11 +229,11 @@ public override DateTime GetLastWriteTime(SafeFileHandle fileHandle) } #endif - /// - public override DateTime GetLastWriteTimeUtc(string path) - { - return File.GetLastWriteTimeUtc(path); - } + /// + public override DateTime GetLastWriteTimeUtc(string path) + { + return File.GetLastWriteTimeUtc(path); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -261,11 +261,11 @@ public override UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle) } #endif - /// - public override void Move(string sourceFileName, string destFileName) - { - File.Move(sourceFileName, destFileName); - } + /// + public override void Move(string sourceFileName, string destFileName) + { + File.Move(sourceFileName, destFileName); + } #if FEATURE_FILE_MOVE_WITH_OVERWRITE /// @@ -276,23 +276,23 @@ public override void Move(string sourceFileName, string destFileName, bool overw #endif - /// - public override FileSystemStream Open(string path, FileMode mode) - { - return new FileStreamWrapper(File.Open(path, mode)); - } + /// + public override FileSystemStream Open(string path, FileMode mode) + { + return new FileStreamWrapper(File.Open(path, mode)); + } - /// - public override FileSystemStream Open(string path, FileMode mode, FileAccess access) - { - return new FileStreamWrapper(File.Open(path, mode, access)); - } + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access) + { + return new FileStreamWrapper(File.Open(path, mode, access)); + } - /// - public override FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share) - { - return new FileStreamWrapper(File.Open(path, mode, access, share)); - } + /// + public override FileSystemStream Open(string path, FileMode mode, FileAccess access, FileShare share) + { + return new FileStreamWrapper(File.Open(path, mode, access, share)); + } #if FEATURE_FILESTREAM_OPTIONS /// @@ -302,77 +302,77 @@ public override FileSystemStream Open(string path, FileStreamOptions options) } #endif - /// - public override FileSystemStream OpenRead(string path) - { - return new FileStreamWrapper(File.OpenRead(path)); - } + /// + public override FileSystemStream OpenRead(string path) + { + return new FileStreamWrapper(File.OpenRead(path)); + } - /// - public override StreamReader OpenText(string path) - { - return File.OpenText(path); - } + /// + public override StreamReader OpenText(string path) + { + return File.OpenText(path); + } - /// - public override FileSystemStream OpenWrite(string path) - { - return new FileStreamWrapper(File.OpenWrite(path)); - } + /// + public override FileSystemStream OpenWrite(string path) + { + return new FileStreamWrapper(File.OpenWrite(path)); + } - /// - public override byte[] ReadAllBytes(string path) - { - return File.ReadAllBytes(path); - } + /// + public override byte[] ReadAllBytes(string path) + { + return File.ReadAllBytes(path); + } - /// - public override string[] ReadAllLines(string path) - { - return File.ReadAllLines(path); - } + /// + public override string[] ReadAllLines(string path) + { + return File.ReadAllLines(path); + } - /// - public override string[] ReadAllLines(string path, Encoding encoding) - { - return File.ReadAllLines(path, encoding); - } + /// + public override string[] ReadAllLines(string path, Encoding encoding) + { + return File.ReadAllLines(path, encoding); + } - /// - public override string ReadAllText(string path) - { - return File.ReadAllText(path); - } + /// + public override string ReadAllText(string path) + { + return File.ReadAllText(path); + } - /// - public override string ReadAllText(string path, Encoding encoding) - { - return File.ReadAllText(path, encoding); - } + /// + public override string ReadAllText(string path, Encoding encoding) + { + return File.ReadAllText(path, encoding); + } - /// - public override IEnumerable ReadLines(string path) - { - return File.ReadLines(path); - } + /// + public override IEnumerable ReadLines(string path) + { + return File.ReadLines(path); + } - /// - public override IEnumerable ReadLines(string path, Encoding encoding) - { - return File.ReadLines(path, encoding); - } + /// + public override IEnumerable ReadLines(string path, Encoding encoding) + { + return File.ReadLines(path, encoding); + } - /// - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) - { - File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); - } + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) + { + File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); + } - /// - public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) - { - File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); - } + /// + public override void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) + { + File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); + } #if FEATURE_CREATE_SYMBOLIC_LINK /// @@ -383,11 +383,11 @@ public override IFileSystemInfo ResolveLinkTarget(string linkPath, bool returnFi } #endif - /// - public override void SetAttributes(string path, FileAttributes fileAttributes) - { - File.SetAttributes(path, fileAttributes); - } + /// + public override void SetAttributes(string path, FileAttributes fileAttributes) + { + File.SetAttributes(path, fileAttributes); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -397,11 +397,11 @@ public override void SetAttributes(SafeFileHandle fileHandle, FileAttributes fil } #endif - /// - public override void SetCreationTime(string path, DateTime creationTime) - { - File.SetCreationTime(path, creationTime); - } + /// + public override void SetCreationTime(string path, DateTime creationTime) + { + File.SetCreationTime(path, creationTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -411,11 +411,11 @@ public override void SetCreationTime(SafeFileHandle fileHandle, DateTime creatio } #endif - /// - public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) - { - File.SetCreationTimeUtc(path, creationTimeUtc); - } + /// + public override void SetCreationTimeUtc(string path, DateTime creationTimeUtc) + { + File.SetCreationTimeUtc(path, creationTimeUtc); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -425,11 +425,11 @@ public override void SetCreationTimeUtc(SafeFileHandle fileHandle, DateTime crea } #endif - /// - public override void SetLastAccessTime(string path, DateTime lastAccessTime) - { - File.SetLastAccessTime(path, lastAccessTime); - } + /// + public override void SetLastAccessTime(string path, DateTime lastAccessTime) + { + File.SetLastAccessTime(path, lastAccessTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -439,11 +439,11 @@ public override void SetLastAccessTime(SafeFileHandle fileHandle, DateTime lastA } #endif - /// - public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) - { - File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); - } + /// + public override void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) + { + File.SetLastAccessTimeUtc(path, lastAccessTimeUtc); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -453,11 +453,11 @@ public override void SetLastAccessTimeUtc(SafeFileHandle fileHandle, DateTime la } #endif - /// - public override void SetLastWriteTime(string path, DateTime lastWriteTime) - { - File.SetLastWriteTime(path, lastWriteTime); - } + /// + public override void SetLastWriteTime(string path, DateTime lastWriteTime) + { + File.SetLastWriteTime(path, lastWriteTime); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -467,11 +467,11 @@ public override void SetLastWriteTime(SafeFileHandle fileHandle, DateTime lastWr } #endif - /// - public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) - { - File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); - } + /// + public override void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) + { + File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); + } #if FEATURE_FILE_ATTRIBUTES_VIA_HANDLE /// @@ -499,39 +499,39 @@ public override void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mod } #endif - /// - /// Creates a new file, writes the specified byte array to the file, and then closes the file. - /// If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The bytes to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. - /// - public override void WriteAllBytes(string path, byte[] bytes) - { - File.WriteAllBytes(path, bytes); - } + /// + /// Creates a new file, writes the specified byte array to the file, and then closes the file. + /// If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The bytes to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file. + /// + public override void WriteAllBytes(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + } #if FEATURE_FILE_SPAN /// @@ -541,244 +541,244 @@ public override void WriteAllBytes(string path, ReadOnlySpan bytes) } #endif - /// - /// Creates a new file, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. - /// - /// - public override void WriteAllLines(string path, IEnumerable contents) - { - File.WriteAllLines(path, contents); - } + /// + /// Creates a new file, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create the contents for a collection class that takes an in its constructor, such as a , , or a class. + /// + /// + public override void WriteAllLines(string path, IEnumerable contents) + { + File.WriteAllLines(path, contents); + } - /// - /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. - /// - /// The file to write to. - /// The lines to write to the file. - /// The character encoding to use. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either , , or is . - /// The specified path is invalid (for example, it is on an unmapped drive). - /// The file specified in was not found. - /// An I/O error occurred while opening the file. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// You can use this method to create a file that contains the following: - /// - /// - /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. - /// - /// - /// The contents of a collection that implements an of strings. - /// - /// - /// - /// - public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) - { - File.WriteAllLines(path, contents, encoding); - } + /// + /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. + /// + /// The file to write to. + /// The lines to write to the file. + /// The character encoding to use. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either , , or is . + /// The specified path is invalid (for example, it is on an unmapped drive). + /// The file specified in was not found. + /// An I/O error occurred while opening the file. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// You can use this method to create a file that contains the following: + /// + /// + /// The results of a LINQ to Objects query on the lines of a file, as obtained by using the ReadLines method. + /// + /// + /// The contents of a collection that implements an of strings. + /// + /// + /// + /// + public override void WriteAllLines(string path, IEnumerable contents, Encoding encoding) + { + File.WriteAllLines(path, contents, encoding); + } - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents) - { - File.WriteAllLines(path, contents); - } + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents) + { + File.WriteAllLines(path, contents); + } - /// - /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. - /// - /// The file to write to. - /// The string array to write to the file. - /// An object that represents the character encoding applied to the string array. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// Either or is . - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// - /// If the target file already exists, it is overwritten. - /// - /// - /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, - /// and then closes the file. - /// - /// - public override void WriteAllLines(string path, string[] contents, Encoding encoding) - { - File.WriteAllLines(path, contents, encoding); - } + /// + /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. + /// + /// The file to write to. + /// The string array to write to the file. + /// An object that represents the character encoding applied to the string array. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// Either or is . + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// + /// If the target file already exists, it is overwritten. + /// + /// + /// Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, + /// and then closes the file. + /// + /// + public override void WriteAllLines(string path, string[] contents, Encoding encoding) + { + File.WriteAllLines(path, contents, encoding); + } - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. - /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. - /// - /// - public override void WriteAllText(string path, string contents) - { - File.WriteAllText(path, contents); - } + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the method will return an empty byte array. + /// If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the method overload with encoding. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file, and then closes the file. + /// + /// + public override void WriteAllText(string path, string contents) + { + File.WriteAllText(path, contents); + } - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. - /// - /// The file to write to. - /// The string to write to the file. - /// The encoding to apply to the string. - /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . - /// is or contents is empty. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. - /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. - /// - /// The specified path is invalid (for example, it is on an unmapped drive). - /// An I/O error occurred while opening the file. - /// - /// path specified a file that is read-only. - /// -or- - /// This operation is not supported on the current platform. - /// -or- - /// path specified a directory. - /// -or- - /// The caller does not have the required permission. - /// - /// The file specified in was not found. - /// is in an invalid format. - /// The caller does not have the required permission. - /// - /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. - /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. - /// - public override void WriteAllText(string path, string contents, Encoding encoding) - { - File.WriteAllText(path, contents, encoding); - } + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. + /// + /// The file to write to. + /// The string to write to the file. + /// The encoding to apply to the string. + /// is a zero-length string, contains only white space, or contains one or more invalid characters as defined by . + /// is or contents is empty. + /// + /// The specified path, file name, or both exceed the system-defined maximum length. + /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. + /// + /// The specified path is invalid (for example, it is on an unmapped drive). + /// An I/O error occurred while opening the file. + /// + /// path specified a file that is read-only. + /// -or- + /// This operation is not supported on the current platform. + /// -or- + /// path specified a directory. + /// -or- + /// The caller does not have the required permission. + /// + /// The file specified in was not found. + /// is in an invalid format. + /// The caller does not have the required permission. + /// + /// Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. + /// The file handle is guaranteed to be closed by this method, even if exceptions are raised. + /// + public override void WriteAllText(string path, string contents, Encoding encoding) + { + File.WriteAllText(path, contents, encoding); + } #if FEATURE_FILE_SPAN /// @@ -793,5 +793,4 @@ public override void WriteAllText(string path, ReadOnlySpan contents, Enco File.WriteAllText(path, contents, encoding); } #endif - } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/PathBase.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/PathBase.cs index 31981d7a9..341123b65 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/PathBase.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/PathBase.cs @@ -1,188 +1,187 @@ -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public abstract class PathBase : IPath +public abstract class PathBase : IPath +{ + /// + /// Base class for calling static methods of + /// + protected PathBase(IFileSystem fileSystem) { - /// - /// Base class for calling static methods of - /// - protected PathBase(IFileSystem fileSystem) - { - this.FileSystem = fileSystem; - } + this.FileSystem = fileSystem; + } - [Obsolete("This constructor only exists to support mocking libraries.", error: true)] - internal PathBase() { } + [Obsolete("This constructor only exists to support mocking libraries.", error: true)] + internal PathBase() { } - /// - /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. - /// - public IFileSystem FileSystem { get; } + /// + /// Exposes the underlying filesystem implementation. This is useful for implementing extension methods. + /// + public IFileSystem FileSystem { get; } - /// - public abstract char AltDirectorySeparatorChar { get; } + /// + public abstract char AltDirectorySeparatorChar { get; } - /// - public abstract char DirectorySeparatorChar { get; } + /// + public abstract char DirectorySeparatorChar { get; } - /// - [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] - public abstract char[] InvalidPathChars { get; } + /// + [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public abstract char[] InvalidPathChars { get; } - /// - public abstract char PathSeparator { get; } + /// + public abstract char PathSeparator { get; } - /// - public abstract char VolumeSeparatorChar { get; } + /// + public abstract char VolumeSeparatorChar { get; } - /// - public abstract string ChangeExtension(string path, string extension); + /// + public abstract string ChangeExtension(string path, string extension); - /// - public abstract string Combine(params string[] paths); + /// + public abstract string Combine(params string[] paths); #if FEATURE_PATH_SPAN /// public abstract string Combine(params ReadOnlySpan paths); #endif - /// - public abstract string Combine(string path1, string path2); + /// + public abstract string Combine(string path1, string path2); - /// - public abstract string Combine(string path1, string path2, string path3); + /// + public abstract string Combine(string path1, string path2, string path3); - /// - public abstract string Combine(string path1, string path2, string path3, string path4); + /// + public abstract string Combine(string path1, string path2, string path3, string path4); #if FEATURE_PATH_EXISTS - /// - public abstract bool Exists(string path); + /// + public abstract bool Exists(string path); #endif - /// - public abstract string GetDirectoryName(string path); + /// + public abstract string GetDirectoryName(string path); - /// - public abstract string GetExtension(string path); + /// + public abstract string GetExtension(string path); - /// - public abstract string GetFileName(string path); + /// + public abstract string GetFileName(string path); - /// - public abstract string GetFileNameWithoutExtension(string path); + /// + public abstract string GetFileNameWithoutExtension(string path); - /// - public abstract string GetFullPath(string path); + /// + public abstract string GetFullPath(string path); #if FEATURE_ADVANCED_PATH_OPERATIONS - /// - public abstract string GetFullPath(string path, string basePath); + /// + public abstract string GetFullPath(string path, string basePath); #endif - /// - public abstract char[] GetInvalidFileNameChars(); + /// + public abstract char[] GetInvalidFileNameChars(); - /// - public abstract char[] GetInvalidPathChars(); + /// + public abstract char[] GetInvalidPathChars(); - /// - public abstract string GetPathRoot(string path); + /// + public abstract string GetPathRoot(string path); - /// - public abstract string GetRandomFileName(); + /// + public abstract string GetRandomFileName(); - /// - public abstract string GetTempFileName(); + /// + public abstract string GetTempFileName(); - /// - public abstract string GetTempPath(); + /// + public abstract string GetTempPath(); - /// - public abstract bool HasExtension(string path); + /// + public abstract bool HasExtension(string path); - /// - public abstract bool IsPathRooted(string path); + /// + public abstract bool IsPathRooted(string path); #if FEATURE_ADVANCED_PATH_OPERATIONS - /// - public abstract bool IsPathFullyQualified(string path); + /// + public abstract bool IsPathFullyQualified(string path); - /// - public abstract string GetRelativePath(string relativeTo, string path); + /// + public abstract string GetRelativePath(string relativeTo, string path); #endif #if FEATURE_PATH_JOIN_WITH_SPAN - /// - public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2); + /// + public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2); - /// - public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3); + /// + public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3); #if FEATURE_PATH_SPAN /// public abstract string Join(params ReadOnlySpan paths); #endif - /// - public abstract bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, Span destination, out int charsWritten); + /// + public abstract bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, Span destination, out int charsWritten); - /// - public abstract bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten); + /// + public abstract bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten); #endif #if FEATURE_ADVANCED_PATH_OPERATIONS - /// - public abstract bool HasExtension(ReadOnlySpan path); - /// - public abstract bool IsPathFullyQualified(ReadOnlySpan path); - /// - public abstract bool IsPathRooted(ReadOnlySpan path); - /// - public abstract ReadOnlySpan GetDirectoryName(ReadOnlySpan path); - /// - public abstract ReadOnlySpan GetExtension(ReadOnlySpan path); - /// - public abstract ReadOnlySpan GetFileName(ReadOnlySpan path); - /// - public abstract ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path); - /// - public abstract ReadOnlySpan GetPathRoot(ReadOnlySpan path); + /// + public abstract bool HasExtension(ReadOnlySpan path); + /// + public abstract bool IsPathFullyQualified(ReadOnlySpan path); + /// + public abstract bool IsPathRooted(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetDirectoryName(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetExtension(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetFileName(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path); + /// + public abstract ReadOnlySpan GetPathRoot(ReadOnlySpan path); #endif #if FEATURE_PATH_JOIN_WITH_PARAMS - /// - public abstract string Join(params string[] paths); + /// + public abstract string Join(params string[] paths); - /// - public abstract string Join(string path1, string path2); - /// + /// + public abstract string Join(string path1, string path2); + /// - public abstract string Join(string path1, string path2, string path3); + public abstract string Join(string path1, string path2, string path3); #endif #if FEATURE_ENDS_IN_DIRECTORY_SEPARATOR - /// - public abstract bool EndsInDirectorySeparator(ReadOnlySpan path); - /// - public abstract bool EndsInDirectorySeparator(string path); - /// - public abstract ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path); - - /// - public abstract string TrimEndingDirectorySeparator(string path); + /// + public abstract bool EndsInDirectorySeparator(ReadOnlySpan path); + /// + public abstract bool EndsInDirectorySeparator(string path); + /// + public abstract ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path); + + /// + public abstract string TrimEndingDirectorySeparator(string path); #endif #if FEATURE_PATH_JOIN_WITH_FOUR_PATHS - /// - public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, ReadOnlySpan path4); - /// - public abstract string Join(string path1, string path2, string path3, string path4); + /// + public abstract string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, ReadOnlySpan path4); + /// + public abstract string Join(string path1, string path2, string path3, string path4); #endif - } -} +} \ No newline at end of file diff --git a/src/TestableIO.System.IO.Abstractions.Wrappers/PathWrapper.cs b/src/TestableIO.System.IO.Abstractions.Wrappers/PathWrapper.cs index 6470c5509..2c6789210 100644 --- a/src/TestableIO.System.IO.Abstractions.Wrappers/PathWrapper.cs +++ b/src/TestableIO.System.IO.Abstractions.Wrappers/PathWrapper.cs @@ -1,327 +1,326 @@ -namespace System.IO.Abstractions -{ - /// +namespace System.IO.Abstractions; + +/// #if FEATURE_SERIALIZABLE - [Serializable] +[Serializable] #endif - public class PathWrapper : PathBase - { - /// - public PathWrapper(IFileSystem fileSystem) : base(fileSystem) - { - } - - /// - public override char AltDirectorySeparatorChar - { - get { return Path.AltDirectorySeparatorChar; } - } - - /// - public override char DirectorySeparatorChar - { - get { return Path.DirectorySeparatorChar; } - } - - /// - [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] - public override char[] InvalidPathChars - { - get { return Path.InvalidPathChars; } - } - - /// - public override char PathSeparator - { - get { return Path.PathSeparator; } - } - - /// - public override char VolumeSeparatorChar - { - get { return Path.VolumeSeparatorChar; } - } - - /// - public override string ChangeExtension(string path, string extension) - { - return Path.ChangeExtension(path, extension); - } - - /// - public override string Combine(params string[] paths) - { - return Path.Combine(paths); - } +public class PathWrapper : PathBase +{ + /// + public PathWrapper(IFileSystem fileSystem) : base(fileSystem) + { + } + + /// + public override char AltDirectorySeparatorChar + { + get { return Path.AltDirectorySeparatorChar; } + } + + /// + public override char DirectorySeparatorChar + { + get { return Path.DirectorySeparatorChar; } + } + + /// + [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] + public override char[] InvalidPathChars + { + get { return Path.InvalidPathChars; } + } + + /// + public override char PathSeparator + { + get { return Path.PathSeparator; } + } + + /// + public override char VolumeSeparatorChar + { + get { return Path.VolumeSeparatorChar; } + } + + /// + public override string ChangeExtension(string path, string extension) + { + return Path.ChangeExtension(path, extension); + } + + /// + public override string Combine(params string[] paths) + { + return Path.Combine(paths); + } #if FEATURE_PATH_SPAN - /// - public override string Combine(params ReadOnlySpan paths) - { - return Path.Combine(paths); - } + /// + public override string Combine(params ReadOnlySpan paths) + { + return Path.Combine(paths); + } #endif - /// - public override string Combine(string path1, string path2) - { - return Path.Combine(path1, path2); - } + /// + public override string Combine(string path1, string path2) + { + return Path.Combine(path1, path2); + } - /// - public override string Combine(string path1, string path2, string path3) - { - return Path.Combine(path1, path2, path3); - } + /// + public override string Combine(string path1, string path2, string path3) + { + return Path.Combine(path1, path2, path3); + } - /// - public override string Combine(string path1, string path2, string path3, string path4) - { - return Path.Combine(path1, path2, path3, path4); - } + /// + public override string Combine(string path1, string path2, string path3, string path4) + { + return Path.Combine(path1, path2, path3, path4); + } #if FEATURE_PATH_EXISTS - /// - public override bool Exists(string path) - { - return Path.Exists(path); - } + /// + public override bool Exists(string path) + { + return Path.Exists(path); + } #endif - /// - public override string GetDirectoryName(string path) - { - return Path.GetDirectoryName(path); - } - - /// - public override string GetExtension(string path) - { - return Path.GetExtension(path); - } - - /// - public override string GetFileName(string path) - { - return Path.GetFileName(path); - } - - /// - public override string GetFileNameWithoutExtension(string path) - { - return Path.GetFileNameWithoutExtension(path); - } - - /// - public override string GetFullPath(string path) - { - return Path.GetFullPath(path); - } + /// + public override string GetDirectoryName(string path) + { + return Path.GetDirectoryName(path); + } + + /// + public override string GetExtension(string path) + { + return Path.GetExtension(path); + } + + /// + public override string GetFileName(string path) + { + return Path.GetFileName(path); + } + + /// + public override string GetFileNameWithoutExtension(string path) + { + return Path.GetFileNameWithoutExtension(path); + } + + /// + public override string GetFullPath(string path) + { + return Path.GetFullPath(path); + } # if FEATURE_ADVANCED_PATH_OPERATIONS - /// - public override string GetFullPath(string path, string basePath) - { - return Path.GetFullPath(path, basePath); - } + /// + public override string GetFullPath(string path, string basePath) + { + return Path.GetFullPath(path, basePath); + } #endif - /// - public override char[] GetInvalidFileNameChars() - { - return Path.GetInvalidFileNameChars(); - } - - /// - public override char[] GetInvalidPathChars() - { - return Path.GetInvalidPathChars(); - } - - /// - public override string GetPathRoot(string path) - { - return Path.GetPathRoot(path); - } - - /// - public override string GetRandomFileName() - { - return Path.GetRandomFileName(); - } - - /// - public override string GetTempFileName() - { - return Path.GetTempFileName(); - } - - /// - public override string GetTempPath() - { - return Path.GetTempPath(); - } - - /// - public override bool HasExtension(string path) - { - return Path.HasExtension(path); - } + /// + public override char[] GetInvalidFileNameChars() + { + return Path.GetInvalidFileNameChars(); + } + + /// + public override char[] GetInvalidPathChars() + { + return Path.GetInvalidPathChars(); + } + + /// + public override string GetPathRoot(string path) + { + return Path.GetPathRoot(path); + } + + /// + public override string GetRandomFileName() + { + return Path.GetRandomFileName(); + } + + /// + public override string GetTempFileName() + { + return Path.GetTempFileName(); + } + + /// + public override string GetTempPath() + { + return Path.GetTempPath(); + } + + /// + public override bool HasExtension(string path) + { + return Path.HasExtension(path); + } #if FEATURE_ADVANCED_PATH_OPERATIONS - /// - public override bool IsPathFullyQualified(string path) - { - return Path.IsPathFullyQualified(path); - } - - /// - public override string GetRelativePath(string relativeTo, string path) - { - return Path.GetRelativePath(relativeTo, path); - } + /// + public override bool IsPathFullyQualified(string path) + { + return Path.IsPathFullyQualified(path); + } + + /// + public override string GetRelativePath(string relativeTo, string path) + { + return Path.GetRelativePath(relativeTo, path); + } #endif #if FEATURE_PATH_JOIN_WITH_SPAN - /// - public override string Join(ReadOnlySpan path1, ReadOnlySpan path2) => - Path.Join(path1, path2); + /// + public override string Join(ReadOnlySpan path1, ReadOnlySpan path2) => + Path.Join(path1, path2); - /// - public override string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3) => - Path.Join(path1, path2, path3); + /// + public override string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3) => + Path.Join(path1, path2, path3); #if FEATURE_PATH_SPAN - /// - public override string Join(params ReadOnlySpan paths) - { - return Path.Join(paths); - } + /// + public override string Join(params ReadOnlySpan paths) + { + return Path.Join(paths); + } #endif - /// - public override bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten) => - Path.TryJoin(path1, path2, destination, out charsWritten); + /// + public override bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten) => + Path.TryJoin(path1, path2, destination, out charsWritten); - /// - public override bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, Span destination, out int charsWritten) => - Path.TryJoin(path1, path2, path3, destination, out charsWritten); + /// + public override bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, Span destination, out int charsWritten) => + Path.TryJoin(path1, path2, path3, destination, out charsWritten); #endif - /// - public override bool IsPathRooted(string path) - { - return Path.IsPathRooted(path); - } + /// + public override bool IsPathRooted(string path) + { + return Path.IsPathRooted(path); + } #if FEATURE_ENDS_IN_DIRECTORY_SEPARATOR - /// - public override bool EndsInDirectorySeparator(ReadOnlySpan path) - { - return Path.EndsInDirectorySeparator(path); - } - - /// - public override bool EndsInDirectorySeparator(string path) - { - return Path.EndsInDirectorySeparator(path); - } - - /// - public override ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path) - { - return Path.TrimEndingDirectorySeparator(path); - } - - /// - public override string TrimEndingDirectorySeparator(string path) - { - return Path.TrimEndingDirectorySeparator(path); - } + /// + public override bool EndsInDirectorySeparator(ReadOnlySpan path) + { + return Path.EndsInDirectorySeparator(path); + } + + /// + public override bool EndsInDirectorySeparator(string path) + { + return Path.EndsInDirectorySeparator(path); + } + + /// + public override ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path) + { + return Path.TrimEndingDirectorySeparator(path); + } + + /// + public override string TrimEndingDirectorySeparator(string path) + { + return Path.TrimEndingDirectorySeparator(path); + } #endif #if FEATURE_ADVANCED_PATH_OPERATIONS - /// - public override bool HasExtension(ReadOnlySpan path) - { - return Path.HasExtension(path); - } - - /// - public override bool IsPathFullyQualified(ReadOnlySpan path) - { - return Path.IsPathFullyQualified(path); - } - - /// - public override bool IsPathRooted(ReadOnlySpan path) - { - return Path.IsPathRooted(path); - } - - /// - public override ReadOnlySpan GetDirectoryName(ReadOnlySpan path) - { - return Path.GetDirectoryName(path); - } - - /// - public override ReadOnlySpan GetExtension(ReadOnlySpan path) - { - return Path.GetExtension(path); - } - - /// - public override ReadOnlySpan GetFileName(ReadOnlySpan path) - { - return Path.GetFileName(path); - } - - /// - public override ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path) - { - return Path.GetFileNameWithoutExtension(path); - } - - /// - public override ReadOnlySpan GetPathRoot(ReadOnlySpan path) - { - return Path.GetPathRoot(path); - } + /// + public override bool HasExtension(ReadOnlySpan path) + { + return Path.HasExtension(path); + } + + /// + public override bool IsPathFullyQualified(ReadOnlySpan path) + { + return Path.IsPathFullyQualified(path); + } + + /// + public override bool IsPathRooted(ReadOnlySpan path) + { + return Path.IsPathRooted(path); + } + + /// + public override ReadOnlySpan GetDirectoryName(ReadOnlySpan path) + { + return Path.GetDirectoryName(path); + } + + /// + public override ReadOnlySpan GetExtension(ReadOnlySpan path) + { + return Path.GetExtension(path); + } + + /// + public override ReadOnlySpan GetFileName(ReadOnlySpan path) + { + return Path.GetFileName(path); + } + + /// + public override ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path) + { + return Path.GetFileNameWithoutExtension(path); + } + + /// + public override ReadOnlySpan GetPathRoot(ReadOnlySpan path) + { + return Path.GetPathRoot(path); + } #endif #if FEATURE_PATH_JOIN_WITH_FOUR_PATHS - /// - public override string Join(string path1, string path2, string path3, string path4) - { - return Path.Join(path1, path2, path3, path4); - } - - /// - public override string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, ReadOnlySpan path4) - { - return Path.Join(path1, path2, path3, path4); - } + /// + public override string Join(string path1, string path2, string path3, string path4) + { + return Path.Join(path1, path2, path3, path4); + } + + /// + public override string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, ReadOnlySpan path4) + { + return Path.Join(path1, path2, path3, path4); + } #endif #if FEATURE_PATH_JOIN_WITH_PARAMS - /// - public override string Join(string path1, string path2) - { - return Path.Join(path1, path2); - } - - /// - public override string Join(string path1, string path2, string path3) - { - return Path.Join(path1, path2, path3); - } - - /// - public override string Join(params string[] paths) - { - return Path.Join(paths); - } -#endif + /// + public override string Join(string path1, string path2) + { + return Path.Join(path1, path2); + } + + /// + public override string Join(string path1, string path2, string path3) + { + return Path.Join(path1, path2, path3); } -} + + /// + public override string Join(params string[] paths) + { + return Path.Join(paths); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/ApiParityTests.cs b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/ApiParityTests.cs index 4daceb63f..8c93d0c63 100644 --- a/tests/TestableIO.System.IO.Abstractions.Parity.Tests/ApiParityTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Parity.Tests/ApiParityTests.cs @@ -7,120 +7,120 @@ using NUnit.Framework; using static System.Reflection.BindingFlags; -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class ApiParityTests { - [TestFixture] - public class ApiParityTests + [Test] + public async Task File() => + await AssertParity( + typeof(File), + typeof(FileBase) + ); + + [Test] + public async Task FileInfo() => + await AssertParity( + typeof(FileInfo), + typeof(FileInfoBase) + ); + + [Test] + public async Task FileVersionInfo() => + await AssertParity( + typeof(Diagnostics.FileVersionInfo), + typeof(FileVersionInfoBase) + ); + + [Test] + public async Task Directory() => + await AssertParity( + typeof(Directory), + typeof(DirectoryBase) + ); + + [Test] + public async Task DirectoryInfo() => + await AssertParity( + typeof(DirectoryInfo), + typeof(DirectoryInfoBase) + ); + + [Test] + public async Task DriveInfo() => + await AssertParity( + typeof(DriveInfo), + typeof(DriveInfoBase) + ); + + [Test] + public async Task Path() => + await AssertParity( + typeof(Path), + typeof(PathBase) + ); + + [Test] + public async Task FileSystemWatcher() => + await AssertParity( + typeof(FileSystemWatcher), + typeof(FileSystemWatcherBase) + ); + + private async Task AssertParity(Type referenceType, Type abstractionType) { - [Test] - public async Task File() => - await AssertParity( - typeof(File), - typeof(FileBase) - ); - - [Test] - public async Task FileInfo() => - await AssertParity( - typeof(FileInfo), - typeof(FileInfoBase) - ); - - [Test] - public async Task FileVersionInfo() => - await AssertParity( - typeof(Diagnostics.FileVersionInfo), - typeof(FileVersionInfoBase) - ); - - [Test] - public async Task Directory() => - await AssertParity( - typeof(Directory), - typeof(DirectoryBase) - ); - - [Test] - public async Task DirectoryInfo() => - await AssertParity( - typeof(DirectoryInfo), - typeof(DirectoryInfoBase) - ); - - [Test] - public async Task DriveInfo() => - await AssertParity( - typeof(DriveInfo), - typeof(DriveInfoBase) - ); - - [Test] - public async Task Path() => - await AssertParity( - typeof(Path), - typeof(PathBase) - ); - - [Test] - public async Task FileSystemWatcher() => - await AssertParity( - typeof(FileSystemWatcher), - typeof(FileSystemWatcherBase) - ); - - private async Task AssertParity(Type referenceType, Type abstractionType) - { - static IEnumerable GetMembers(Type type) => type - .GetMembers(bindingAttr: Instance | Static | Public | FlattenHierarchy) - .Select(x => x.ToString()) - .OrderBy(x => x, StringComparer.Ordinal); - var referenceMembers = GetMembers(referenceType) - .Select(x => x.Replace("System.IO.FileStream", "System.IO.Abstractions.FileSystemStream")) - .Select(x => x.Replace("System.IO.Abstractions.FileSystemStreamOptions", "System.IO.FileStreamOptions")) - .Select(x => x.Replace("System.IO.FileSystemInfo", "System.IO.Abstractions.IFileSystemInfo")) - .Select(x => x.Replace("System.IO.FileInfo", "System.IO.Abstractions.IFileInfo")) - .Select(x => x.Replace("System.IO.DirectoryInfo", "System.IO.Abstractions.IDirectoryInfo")) - .Select(x => x.Replace("System.IO.DriveInfo", "System.IO.Abstractions.IDriveInfo")) - .Select(x => x.Replace("System.IO.WaitForChangedResult", "System.IO.Abstractions.IWaitForChangedResult")) - .Where(x => x != "System.Diagnostics.FileVersionInfo GetVersionInfo(System.String)"); - var abstractionMembers = GetMembers(abstractionType) - .Where(x => !x.Contains("op_Implicit")) - .Where(x => x != "System.IO.Abstractions.IFileSystem get_FileSystem()") - .Where(x => x != "System.IO.Abstractions.IFileSystem FileSystem"); - var diff = new ApiDiff( - extraMembers: abstractionMembers.Except(referenceMembers), - missingMembers: referenceMembers.Except(abstractionMembers) - ); - - var serializedDiff = JsonSerializer.Serialize(diff, SerializerOptions); - - var snapshotPath = IO.Path.GetFullPath("../../../__snapshots__/"); - var fileName = $"ApiParityTests.{referenceType.Name}_{snapshotSuffix}.snap"; - var fileContent = IO.File.ReadAllText(IO.Path.Combine(snapshotPath, fileName)); - - await That(fileContent).IsEqualTo(serializedDiff) - .IgnoringNewlineStyle() - .IgnoringTrailingWhiteSpace(); - } + static IEnumerable GetMembers(Type type) => type + .GetMembers(bindingAttr: Instance | Static | Public | FlattenHierarchy) + .Select(x => x.ToString()) + .OrderBy(x => x, StringComparer.Ordinal); + var referenceMembers = GetMembers(referenceType) + .Select(x => x.Replace("System.IO.FileStream", "System.IO.Abstractions.FileSystemStream")) + .Select(x => x.Replace("System.IO.Abstractions.FileSystemStreamOptions", "System.IO.FileStreamOptions")) + .Select(x => x.Replace("System.IO.FileSystemInfo", "System.IO.Abstractions.IFileSystemInfo")) + .Select(x => x.Replace("System.IO.FileInfo", "System.IO.Abstractions.IFileInfo")) + .Select(x => x.Replace("System.IO.DirectoryInfo", "System.IO.Abstractions.IDirectoryInfo")) + .Select(x => x.Replace("System.IO.DriveInfo", "System.IO.Abstractions.IDriveInfo")) + .Select(x => x.Replace("System.IO.WaitForChangedResult", "System.IO.Abstractions.IWaitForChangedResult")) + .Where(x => x != "System.Diagnostics.FileVersionInfo GetVersionInfo(System.String)"); + var abstractionMembers = GetMembers(abstractionType) + .Where(x => !x.Contains("op_Implicit")) + .Where(x => x != "System.IO.Abstractions.IFileSystem get_FileSystem()") + .Where(x => x != "System.IO.Abstractions.IFileSystem FileSystem"); + var diff = new ApiDiff( + extraMembers: abstractionMembers.Except(referenceMembers), + missingMembers: referenceMembers.Except(abstractionMembers) + ); + + var serializedDiff = JsonSerializer.Serialize(diff, SerializerOptions); + + var snapshotPath = IO.Path.GetFullPath("../../../__snapshots__/"); + var fileName = $"ApiParityTests.{referenceType.Name}_{snapshotSuffix}.snap"; + var fileContent = IO.File.ReadAllText(IO.Path.Combine(snapshotPath, fileName)); + + await That(fileContent).IsEqualTo(serializedDiff) + .IgnoringNewlineStyle() + .IgnoringTrailingWhiteSpace(); + } - private static JsonSerializerOptions SerializerOptions = new() - { - WriteIndented = true - }; + private static JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true + }; - private readonly struct ApiDiff + private readonly struct ApiDiff + { + public ApiDiff(IEnumerable extraMembers, IEnumerable missingMembers) { - public ApiDiff(IEnumerable extraMembers, IEnumerable missingMembers) - { - ExtraMembers = extraMembers.ToArray(); - MissingMembers = missingMembers.ToArray(); - - } + ExtraMembers = extraMembers.ToArray(); + MissingMembers = missingMembers.ToArray(); - public string[] ExtraMembers { get; } - public string[] MissingMembers { get; } } + public string[] ExtraMembers { get; } + public string[] MissingMembers { get; } + } + #if NET472 private const string snapshotSuffix = ".NET Framework 4.7.2"; #elif NET6_0 @@ -128,9 +128,8 @@ public ApiDiff(IEnumerable extraMembers, IEnumerable missingMemb #elif NET8_0 private const string snapshotSuffix = ".NET 8.0"; #elif NET9_0 - private const string snapshotSuffix = ".NET 9.0"; + private const string snapshotSuffix = ".NET 9.0"; #else #error Unknown target framework. #endif - } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryArgumentPathTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryArgumentPathTests.cs index 30bad46b0..6865f153c 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryArgumentPathTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryArgumentPathTests.cs @@ -2,44 +2,43 @@ using System.Security.AccessControl; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockDirectoryArgumentPathTests { - public class MockDirectoryArgumentPathTests + private static IEnumerable> GetFileSystemActionsForArgumentNullException() { - private static IEnumerable> GetFileSystemActionsForArgumentNullException() + yield return ds => ds.Delete(null); + yield return ds => ds.Delete(null, true); + yield return ds => ds.CreateDirectory(null); + if (MockUnixSupport.IsWindowsPlatform()) { - yield return ds => ds.Delete(null); - yield return ds => ds.Delete(null, true); - yield return ds => ds.CreateDirectory(null); - if (MockUnixSupport.IsWindowsPlatform()) - { #pragma warning disable CA1416 - yield return ds => ds.CreateDirectory(null, new DirectorySecurity()); + yield return ds => ds.CreateDirectory(null, new DirectorySecurity()); #pragma warning restore CA1416 - } - yield return ds => ds.SetCreationTime(null, DateTime.Now); - yield return ds => ds.SetCreationTimeUtc(null, DateTime.Now); - yield return ds => ds.SetLastAccessTime(null, DateTime.Now); - yield return ds => ds.SetLastAccessTimeUtc(null, DateTime.Now); - yield return ds => ds.SetLastWriteTime(null, DateTime.Now); - yield return ds => ds.SetLastWriteTimeUtc(null, DateTime.Now); - yield return ds => ds.EnumerateDirectories(null); - yield return ds => ds.EnumerateDirectories(null, "foo"); - yield return ds => ds.EnumerateDirectories(null, "foo", SearchOption.AllDirectories); } + yield return ds => ds.SetCreationTime(null, DateTime.Now); + yield return ds => ds.SetCreationTimeUtc(null, DateTime.Now); + yield return ds => ds.SetLastAccessTime(null, DateTime.Now); + yield return ds => ds.SetLastAccessTimeUtc(null, DateTime.Now); + yield return ds => ds.SetLastWriteTime(null, DateTime.Now); + yield return ds => ds.SetLastWriteTimeUtc(null, DateTime.Now); + yield return ds => ds.EnumerateDirectories(null); + yield return ds => ds.EnumerateDirectories(null, "foo"); + yield return ds => ds.EnumerateDirectories(null, "foo", SearchOption.AllDirectories); + } - [TestCaseSource(nameof(GetFileSystemActionsForArgumentNullException))] - public async Task Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) - { - // Arrange - var fileSystem = new MockFileSystem(); + [TestCaseSource(nameof(GetFileSystemActionsForArgumentNullException))] + public async Task Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action wrapped = () => action(fileSystem.Directory); + // Act + Action wrapped = () => action(fileSystem.Directory); - // Assert - var exception = await That(wrapped).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } + // Assert + var exception = await That(wrapped).Throws(); + await That(exception.ParamName).IsEqualTo("path"); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryGetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryGetAccessControlTests.cs index cd0e1b381..5e6d1724f 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryGetAccessControlTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryGetAccessControlTests.cs @@ -3,66 +3,65 @@ using System.Security.AccessControl; using System.Runtime.Versioning; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockDirectoryGetAccessControlTests { - using XFS = MockUnixSupport; - [TestFixture] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - [SupportedOSPlatform("windows")] - public class MockDirectoryGetAccessControlTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockDirectory_GetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockDirectory_GetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.Directory.GetAccessControl(path); + // Act + Action action = () => fileSystem.Directory.GetAccessControl(path); - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockDirectory_GetAccessControl_ShouldThrowDirectoryNotFoundExceptionIfDirectoryDoesNotExistInMockData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var expectedDirectoryName = XFS.Path(@"c:\a"); + [Test] + public async Task MockDirectory_GetAccessControl_ShouldThrowDirectoryNotFoundExceptionIfDirectoryDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedDirectoryName = XFS.Path(@"c:\a"); - // Act - Action action = () => fileSystem.Directory.GetAccessControl(expectedDirectoryName); + // Act + Action action = () => fileSystem.Directory.GetAccessControl(expectedDirectoryName); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockDirectory_GetAccessControl_ShouldReturnAccessControlOfDirectoryData() - { - // Arrange - var expectedDirectorySecurity = new DirectorySecurity(); - expectedDirectorySecurity.SetAccessRuleProtection(false, false); + [Test] + public async Task MockDirectory_GetAccessControl_ShouldReturnAccessControlOfDirectoryData() + { + // Arrange + var expectedDirectorySecurity = new DirectorySecurity(); + expectedDirectorySecurity.SetAccessRuleProtection(false, false); - var filePath = XFS.Path(@"c:\a\"); - var fileData = new MockDirectoryData() - { - AccessControl = expectedDirectorySecurity, - }; + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData() + { + AccessControl = expectedDirectorySecurity, + }; - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); - // Act - var directorySecurity = fileSystem.Directory.GetAccessControl(filePath); + // Act + var directorySecurity = fileSystem.Directory.GetAccessControl(filePath); - // Assert - await That(directorySecurity).IsEqualTo(expectedDirectorySecurity); - } + // Assert + await That(directorySecurity).IsEqualTo(expectedDirectorySecurity); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoAccessControlTests.cs index c57c0a1d5..f76169d47 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoAccessControlTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoAccessControlTests.cs @@ -4,62 +4,61 @@ using System.Security.AccessControl; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockDirectoryInfoAccessControlTests { - [TestFixture] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - [SupportedOSPlatform("windows")] - public class MockDirectoryInfoAccessControlTests + [Test] + public async Task MockDirectoryInfo_GetAccessControl_ShouldReturnAccessControlOfDirectoryData() { - [Test] - public async Task MockDirectoryInfo_GetAccessControl_ShouldReturnAccessControlOfDirectoryData() + // Arrange + var expectedDirectorySecurity = new DirectorySecurity(); + expectedDirectorySecurity.SetAccessRuleProtection(false, false); + + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData() { - // Arrange - var expectedDirectorySecurity = new DirectorySecurity(); - expectedDirectorySecurity.SetAccessRuleProtection(false, false); + AccessControl = expectedDirectorySecurity, + }; - var filePath = XFS.Path(@"c:\a\"); - var fileData = new MockDirectoryData() - { - AccessControl = expectedDirectorySecurity, - }; + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + var directorInfo = fileSystem.DirectoryInfo.New(filePath); - var directorInfo = fileSystem.DirectoryInfo.New(filePath); + // Act + var directorySecurity = directorInfo.GetAccessControl(); - // Act - var directorySecurity = directorInfo.GetAccessControl(); + // Assert + await That(directorySecurity).IsEqualTo(expectedDirectorySecurity); + } - // Assert - await That(directorySecurity).IsEqualTo(expectedDirectorySecurity); - } + [Test] + public async Task MockDirectoryInfo_SetAccessControl_ShouldSetAccessControlOfDirectoryData() + { + // Arrange + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData(); - [Test] - public async Task MockDirectoryInfo_SetAccessControl_ShouldSetAccessControlOfDirectoryData() + var fileSystem = new MockFileSystem(new Dictionary() { - // Arrange - var filePath = XFS.Path(@"c:\a\"); - var fileData = new MockDirectoryData(); - - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + { filePath, fileData } + }); - var directorInfo = fileSystem.DirectoryInfo.New(filePath); + var directorInfo = fileSystem.DirectoryInfo.New(filePath); - // Act - var expectedAccessControl = new DirectorySecurity(); - expectedAccessControl.SetAccessRuleProtection(false, false); - directorInfo.SetAccessControl(expectedAccessControl); + // Act + var expectedAccessControl = new DirectorySecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + directorInfo.SetAccessControl(expectedAccessControl); - // Assert - var accessControl = directorInfo.GetAccessControl(); - await That(accessControl).IsEqualTo(expectedAccessControl); - } + // Assert + var accessControl = directorInfo.GetAccessControl(); + await That(accessControl).IsEqualTo(expectedAccessControl); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoFactoryTests.cs index 8f77eecc0..58a3aa9ae 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoFactoryTests.cs @@ -1,29 +1,28 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockDirectoryInfoFactoryTests { - [TestFixture] - public class MockDirectoryInfoFactoryTests + [Test] + public async Task MockDirectoryInfoFactory_Wrap_WithNull_ShouldReturnNull() { - [Test] - public async Task MockDirectoryInfoFactory_Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new MockFileSystem(); + var fileSystem = new MockFileSystem(); - var result = fileSystem.DirectoryInfo.Wrap(null); + var result = fileSystem.DirectoryInfo.Wrap(null); - await That(result).IsNull(); - } + await That(result).IsNull(); + } - [Test] - public async Task MockDirectoryInfoFactory_Wrap_ShouldKeepNameAndFullName() - { - var fs = new MockFileSystem(); - var directoryInfo = new DirectoryInfo(@"C:\subfolder\file"); - var wrappedDirectoryInfo = fs.DirectoryInfo.Wrap(directoryInfo); + [Test] + public async Task MockDirectoryInfoFactory_Wrap_ShouldKeepNameAndFullName() + { + var fs = new MockFileSystem(); + var directoryInfo = new DirectoryInfo(@"C:\subfolder\file"); + var wrappedDirectoryInfo = fs.DirectoryInfo.Wrap(directoryInfo); - await That(wrappedDirectoryInfo.FullName).IsEqualTo(directoryInfo.FullName); - await That(wrappedDirectoryInfo.Name).IsEqualTo(directoryInfo.Name); - } + await That(wrappedDirectoryInfo.FullName).IsEqualTo(directoryInfo.FullName); + await That(wrappedDirectoryInfo.Name).IsEqualTo(directoryInfo.Name); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoSymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoSymlinkTests.cs index 0360d5e27..c54dfe471 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoSymlinkTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoSymlinkTests.cs @@ -4,66 +4,65 @@ using System.Security.AccessControl; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; - [TestFixture] - public class MockDirectoryInfoSymlinkTests - { +using XFS = MockUnixSupport; + +[TestFixture] +public class MockDirectoryInfoSymlinkTests +{ #if FEATURE_CREATE_SYMBOLIC_LINK - [Test] - public async Task MockDirectoryInfo_ResolveLinkTarget_ShouldReturnPathOfTargetLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); - var result = fileSystem.DirectoryInfo.New("foo").ResolveLinkTarget(false); + var result = fileSystem.DirectoryInfo.New("foo").ResolveLinkTarget(false); - await That(result.Name).IsEqualTo("bar"); - } + await That(result.Name).IsEqualTo("bar"); + } - [Test] - public async Task MockDirectoryInfo_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - fileSystem.Directory.CreateSymbolicLink("foo", "bar"); - fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); - var result = fileSystem.DirectoryInfo.New("foo1").ResolveLinkTarget(true); + var result = fileSystem.DirectoryInfo.New("foo1").ResolveLinkTarget(true); - await That(result.Name).IsEqualTo("bar"); - } + await That(result.Name).IsEqualTo("bar"); + } - [Test] - public async Task MockDirectoryInfo_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - fileSystem.Directory.CreateSymbolicLink("foo", "bar"); - fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); - var result = fileSystem.DirectoryInfo.New("foo1").ResolveLinkTarget(false); + var result = fileSystem.DirectoryInfo.New("foo1").ResolveLinkTarget(false); - await That(result.Name).IsEqualTo("foo"); - } + await That(result.Name).IsEqualTo("foo"); + } - [Test] - public async Task MockDirectoryInfo_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() - { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + [Test] + public async Task MockDirectoryInfo_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); - await That(() => - { - fileSystem.DirectoryInfo.New("bar").ResolveLinkTarget(false); - }).Throws(); - } -#endif + await That(() => + { + fileSystem.DirectoryInfo.New("bar").ResolveLinkTarget(false); + }).Throws(); } +#endif } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoTests.cs index 6de29b9eb..bed4d6702 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryInfoTests.cs @@ -3,229 +3,229 @@ using System.Security.AccessControl; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; - [TestFixture] - public class MockDirectoryInfoTests +[TestFixture] +public class MockDirectoryInfoTests +{ + public static IEnumerable MockDirectoryInfo_GetExtension_Cases { - public static IEnumerable MockDirectoryInfo_GetExtension_Cases + get { - get - { - yield return new object[] { XFS.Path(@"c:\temp") }; - yield return new object[] { XFS.Path(@"c:\temp\") }; - } + yield return new object[] { XFS.Path(@"c:\temp") }; + yield return new object[] { XFS.Path(@"c:\temp\") }; } + } - [TestCaseSource(nameof(MockDirectoryInfo_GetExtension_Cases))] - public async Task MockDirectoryInfo_GetExtension_ShouldReturnEmptyString(string directoryPath) - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary()); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + [TestCaseSource(nameof(MockDirectoryInfo_GetExtension_Cases))] + public async Task MockDirectoryInfo_GetExtension_ShouldReturnEmptyString(string directoryPath) + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary()); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - // Act - var result = directoryInfo.Extension; + // Act + var result = directoryInfo.Extension; - // Assert - await That(result).IsEmpty(); - } + // Assert + await That(result).IsEmpty(); + } - public static IEnumerable MockDirectoryInfo_Exists_Cases + public static IEnumerable MockDirectoryInfo_Exists_Cases + { + get { - get - { - yield return new object[] { XFS.Path(@"c:\temp\folder"), true }; - yield return new object[] { XFS.Path(@"c:\temp\folder\notExistant"), false }; - } + yield return new object[] { XFS.Path(@"c:\temp\folder"), true }; + yield return new object[] { XFS.Path(@"c:\temp\folder\notExistant"), false }; } + } - [TestCaseSource(nameof(MockDirectoryInfo_Exists_Cases))] - public async Task MockDirectoryInfo_Exists(string path, bool expected) + [TestCaseSource(nameof(MockDirectoryInfo_Exists_Cases))] + public async Task MockDirectoryInfo_Exists(string path, bool expected) + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - {XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World")} - }); - var directoryInfo = new MockDirectoryInfo(fileSystem, path); + {XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World")} + }); + var directoryInfo = new MockDirectoryInfo(fileSystem, path); - var result = directoryInfo.Exists; + var result = directoryInfo.Exists; - await That(result).IsEqualTo(expected); - } + await That(result).IsEqualTo(expected); + } - [Test] - public async Task MockDirectoryInfo_Attributes_ShouldReturnMinusOneForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); - FileAttributes expected = (FileAttributes)(-1); + [Test] + public async Task MockDirectoryInfo_Attributes_ShouldReturnMinusOneForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + FileAttributes expected = (FileAttributes)(-1); - await That(directoryInfo.Attributes).IsEqualTo(expected); - } + await That(directoryInfo.Attributes).IsEqualTo(expected); + } - [Test] - public async Task MockDirectoryInfo_Attributes_Clear_ShouldRemainDirectory() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\existing\directory"); - fileSystem.Directory.CreateDirectory(path); - var directoryInfo = fileSystem.DirectoryInfo.New(path); - directoryInfo.Attributes = 0; - - await That(fileSystem.File.Exists(path)).IsFalse(); - await That(directoryInfo.Attributes).IsEqualTo(FileAttributes.Directory); - } + [Test] + public async Task MockDirectoryInfo_Attributes_Clear_ShouldRemainDirectory() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\existing\directory"); + fileSystem.Directory.CreateDirectory(path); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + directoryInfo.Attributes = 0; + + await That(fileSystem.File.Exists(path)).IsFalse(); + await That(directoryInfo.Attributes).IsEqualTo(FileAttributes.Directory); + } - [Test] - public async Task MockDirectoryInfo_Attributes_SetterShouldThrowDirectoryNotFoundExceptionOnNonExistingFileOrDirectory() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + [Test] + public async Task MockDirectoryInfo_Attributes_SetterShouldThrowDirectoryNotFoundExceptionOnNonExistingFileOrDirectory() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - await That(() => directoryInfo.Attributes = FileAttributes.Hidden).Throws(); - } + await That(() => directoryInfo.Attributes = FileAttributes.Hidden).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.UNCPaths)] - public async Task MockDirectoryInfo_GetFiles_ShouldWorkWithUNCPath() + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectoryInfo_GetFiles_ShouldWorkWithUNCPath() + { + var fileName = XFS.Path(@"\\unc\folder\file.txt"); + var directoryName = XFS.Path(@"\\unc\folder"); + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - var fileName = XFS.Path(@"\\unc\folder\file.txt"); - var directoryName = XFS.Path(@"\\unc\folder"); - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - {fileName, ""} - }); + {fileName, ""} + }); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryName); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryName); - // Act - var files = directoryInfo.GetFiles(); + // Act + var files = directoryInfo.GetFiles(); - // Assert - await That(files[0].FullName).IsEqualTo(fileName); - } + // Assert + await That(files[0].FullName).IsEqualTo(fileName); + } - [Test] - [WindowsOnly(WindowsSpecifics.UNCPaths)] - public async Task MockDirectoryInfo_GetFiles_ShouldWorkWithUNCPath_WhenCurrentDirectoryIsUnc() + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectoryInfo_GetFiles_ShouldWorkWithUNCPath_WhenCurrentDirectoryIsUnc() + { + var fileName = XFS.Path(@"\\unc\folder\file.txt"); + var directoryName = XFS.Path(@"\\unc\folder"); + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - var fileName = XFS.Path(@"\\unc\folder\file.txt"); - var directoryName = XFS.Path(@"\\unc\folder"); - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - {fileName, ""} - }); + {fileName, ""} + }); - fileSystem.Directory.SetCurrentDirectory(directoryName); + fileSystem.Directory.SetCurrentDirectory(directoryName); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryName); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryName); - // Act - var files = directoryInfo.GetFiles(); + // Act + var files = directoryInfo.GetFiles(); - // Assert - await That(files[0].FullName).IsEqualTo(fileName); - } + // Assert + await That(files[0].FullName).IsEqualTo(fileName); + } - [Test] - public async Task MockDirectoryInfo_FullName_ShouldReturnFullNameWithoutIncludingTrailingPathDelimiter() + [Test] + public async Task MockDirectoryInfo_FullName_ShouldReturnFullNameWithoutIncludingTrailingPathDelimiter() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary { - { - XFS.Path(@"c:\temp\folder\file.txt"), - new MockFileData("Hello World") - } - }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + XFS.Path(@"c:\temp\folder\file.txt"), + new MockFileData("Hello World") + } + }); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.FullName; + var result = directoryInfo.FullName; - await That(result).IsEqualTo(XFS.Path(@"c:\temp\folder")); - } + await That(result).IsEqualTo(XFS.Path(@"c:\temp\folder")); + } - [Test] - public async Task MockDirectoryInfo_GetFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() + [Test] + public async Task MockDirectoryInfo_GetFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } - }); + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } + }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.GetFileSystemInfos(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.GetFileSystemInfos(); - await That(result.Length).IsEqualTo(2); - } + await That(result.Length).IsEqualTo(2); + } - [Test] - public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() + [Test] + public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnBothDirectoriesAndFiles() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } - }); + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() } + }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.EnumerateFileSystemInfos().ToArray(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.EnumerateFileSystemInfos().ToArray(); - await That(result.Length).IsEqualTo(2); - } + await That(result.Length).IsEqualTo(2); + } - [Test] - public async Task MockDirectoryInfo_GetFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() + [Test] + public async Task MockDirectoryInfo_GetFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, - { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } - }); + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, + { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } + }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.GetFileSystemInfos("f*"); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.GetFileSystemInfos("f*"); - await That(result.Length).IsEqualTo(2); - } + await That(result.Length).IsEqualTo(2); + } - [Test] - public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() + [Test] + public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPattern() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, - { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } - }); + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, + { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } + }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - var result = directoryInfo.EnumerateFileSystemInfos("f*", SearchOption.AllDirectories).ToArray(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + var result = directoryInfo.EnumerateFileSystemInfos("f*", SearchOption.AllDirectories).ToArray(); - await That(result.Length).IsEqualTo(2); - } + await That(result.Length).IsEqualTo(2); + } - [Test] - public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPatternRecursive() + [Test] + public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirectoriesAndNamesWithSearchPatternRecursive() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("") }, - { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, - { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } - }); + { XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("") }, + { XFS.Path(@"c:\temp\folder\folder"), new MockDirectoryData() }, + { XFS.Path(@"c:\temp\folder\older"), new MockDirectoryData() } + }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\")); - var result = directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories).ToArray(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\")); + var result = directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories).ToArray(); - await That(result.Length).IsEqualTo(5); - } + await That(result.Length).IsEqualTo(5); + } #if FEATURE_ENUMERATION_OPTIONS [Test] @@ -251,475 +251,474 @@ public async Task MockDirectoryInfo_EnumerateFileSystemInfos_ShouldReturnDirecto } #endif - [Test] - public async Task MockDirectoryInfo_GetParent_ShouldReturnDirectoriesAndNamesWithSearchPattern() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\a\b\c")); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\a\b\c")); + [Test] + public async Task MockDirectoryInfo_GetParent_ShouldReturnDirectoriesAndNamesWithSearchPattern() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\a\b\c")); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\a\b\c")); - // Act - var result = directoryInfo.Parent; + // Act + var result = directoryInfo.Parent; - // Assert - await That(result.FullName).IsEqualTo(XFS.Path(@"c:\a\b")); - } + // Assert + await That(result.FullName).IsEqualTo(XFS.Path(@"c:\a\b")); + } - [Test] - public async Task MockDirectoryInfo_EnumerateFiles_ShouldReturnAllFiles() + [Test] + public async Task MockDirectoryInfo_EnumerateFiles_ShouldReturnAllFiles() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - //Files "above" in folder we're querying - { XFS.Path(@"c:\temp\a.txt"), "" }, + //Files "above" in folder we're querying + { XFS.Path(@"c:\temp\a.txt"), "" }, - //Files in the folder we're querying - { XFS.Path(@"c:\temp\folder\b.txt"), "" }, - { XFS.Path(@"c:\temp\folder\c.txt"), "" }, + //Files in the folder we're querying + { XFS.Path(@"c:\temp\folder\b.txt"), "" }, + { XFS.Path(@"c:\temp\folder\c.txt"), "" }, - //Files "below" the folder we're querying - { XFS.Path(@"c:\temp\folder\deeper\d.txt"), "" } - }); + //Files "below" the folder we're querying + { XFS.Path(@"c:\temp\folder\deeper\d.txt"), "" } + }); - // Act - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + // Act + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - // Assert - await That(directoryInfo.EnumerateFiles().ToList().Select(x => x.Name).ToArray()).IsEqualTo(new[] { "b.txt", "c.txt" }); - } + // Assert + await That(directoryInfo.EnumerateFiles().ToList().Select(x => x.Name).ToArray()).IsEqualTo(new[] { "b.txt", "c.txt" }); + } - [Test] - public async Task MockDirectoryInfo_EnumerateDirectories_ShouldReturnAllDirectories() + [Test] + public async Task MockDirectoryInfo_EnumerateDirectories_ShouldReturnAllDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - //A file we want to ignore entirely - { XFS.Path(@"c:\temp\folder\a.txt"), "" }, + //A file we want to ignore entirely + { XFS.Path(@"c:\temp\folder\a.txt"), "" }, - //Some files in sub folders (which we also want to ignore entirely) - { XFS.Path(@"c:\temp\folder\b\file.txt"), "" }, - { XFS.Path(@"c:\temp\folder\c\other.txt"), "" }, - }); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); + //Some files in sub folders (which we also want to ignore entirely) + { XFS.Path(@"c:\temp\folder\b\file.txt"), "" }, + { XFS.Path(@"c:\temp\folder\c\other.txt"), "" }, + }); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\folder")); - // Act - var directories = directoryInfo.EnumerateDirectories().Select(a => a.Name).ToArray(); + // Act + var directories = directoryInfo.EnumerateDirectories().Select(a => a.Name).ToArray(); - // Assert - await That(directories).IsEqualTo(new[] { "b", "c" }); - } + // Assert + await That(directories).IsEqualTo(new[] { "b", "c" }); + } - [TestCase(@"\\unc\folder", @"\\unc\folder")] - [TestCase(@"\\unc/folder\\foo", @"\\unc\folder\foo")] - [WindowsOnly(WindowsSpecifics.UNCPaths)] - public async Task MockDirectoryInfo_FullName_ShouldReturnNormalizedUNCPath(string directoryPath, string expectedFullName) - { - // Arrange - directoryPath = XFS.Path(directoryPath); - expectedFullName = XFS.Path(expectedFullName); - var fileSystem = new MockFileSystem(new Dictionary()); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + [TestCase(@"\\unc\folder", @"\\unc\folder")] + [TestCase(@"\\unc/folder\\foo", @"\\unc\folder\foo")] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectoryInfo_FullName_ShouldReturnNormalizedUNCPath(string directoryPath, string expectedFullName) + { + // Arrange + directoryPath = XFS.Path(directoryPath); + expectedFullName = XFS.Path(expectedFullName); + var fileSystem = new MockFileSystem(new Dictionary()); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - // Act - var actualFullName = directoryInfo.FullName; + // Act + var actualFullName = directoryInfo.FullName; - // Assert - await That(actualFullName).IsEqualTo(expectedFullName); - } + // Assert + await That(actualFullName).IsEqualTo(expectedFullName); + } - [TestCase(@"c:\temp\\folder", @"c:\temp\folder")] - [TestCase(@"c:\temp//folder", @"c:\temp\folder")] - [TestCase(@"c:\temp//\\///folder", @"c:\temp\folder")] - public async Task MockDirectoryInfo_FullName_ShouldReturnNormalizedPath(string directoryPath, string expectedFullName) - { - // Arrange - directoryPath = XFS.Path(directoryPath); - expectedFullName = XFS.Path(expectedFullName); - var fileSystem = new MockFileSystem(new Dictionary()); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + [TestCase(@"c:\temp\\folder", @"c:\temp\folder")] + [TestCase(@"c:\temp//folder", @"c:\temp\folder")] + [TestCase(@"c:\temp//\\///folder", @"c:\temp\folder")] + public async Task MockDirectoryInfo_FullName_ShouldReturnNormalizedPath(string directoryPath, string expectedFullName) + { + // Arrange + directoryPath = XFS.Path(directoryPath); + expectedFullName = XFS.Path(expectedFullName); + var fileSystem = new MockFileSystem(new Dictionary()); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - // Act - var actualFullName = directoryInfo.FullName; + // Act + var actualFullName = directoryInfo.FullName; - // Assert - await That(actualFullName).IsEqualTo(expectedFullName); - } + // Assert + await That(actualFullName).IsEqualTo(expectedFullName); + } - [TestCase(@"c:\temp\folder ", @"c:\temp\folder")] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockDirectoryInfo_FullName_ShouldReturnPathWithTrimmedTrailingSpaces(string directoryPath, string expectedFullName) - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + [TestCase(@"c:\temp\folder ", @"c:\temp\folder")] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectoryInfo_FullName_ShouldReturnPathWithTrimmedTrailingSpaces(string directoryPath, string expectedFullName) + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - // Act - var actualFullName = directoryInfo.FullName; + // Act + var actualFullName = directoryInfo.FullName; - // Assert - await That(actualFullName).IsEqualTo(expectedFullName); - } + // Assert + await That(actualFullName).IsEqualTo(expectedFullName); + } - [Test] - public async Task MockDirectoryInfo_MoveTo_ShouldUpdateFullName() - { - // Arrange - var path = XFS.Path(@"c:\source"); - var destination = XFS.Path(@"c:\destination"); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(path); - var directoryInfo = fileSystem.DirectoryInfo.New(path); - - // Act - directoryInfo.MoveTo(destination); - - // Assert - await That(directoryInfo.FullName).IsEqualTo(destination); - } + [Test] + public async Task MockDirectoryInfo_MoveTo_ShouldUpdateFullName() + { + // Arrange + var path = XFS.Path(@"c:\source"); + var destination = XFS.Path(@"c:\destination"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(path); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + + // Act + directoryInfo.MoveTo(destination); + + // Assert + await That(directoryInfo.FullName).IsEqualTo(destination); + } - [TestCase(@"c:\temp\\folder ", @"folder")] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockDirectoryInfo_Name_ShouldReturnNameWithTrimmedTrailingSpaces(string directoryPath, string expectedName) - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + [TestCase(@"c:\temp\\folder ", @"folder")] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectoryInfo_Name_ShouldReturnNameWithTrimmedTrailingSpaces(string directoryPath, string expectedName) + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - // Act - var actualName = directoryInfo.Name; + // Act + var actualName = directoryInfo.Name; - // Assert - await That(actualName).IsEqualTo(expectedName); - } + // Assert + await That(actualName).IsEqualTo(expectedName); + } - [TestCase(@"c:\", @"c:\")] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockDirectoryInfo_Name_ShouldReturnPathRoot_IfDirectoryPathIsPathRoot(string directoryPath, string expectedName) - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); + [TestCase(@"c:\", @"c:\")] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectoryInfo_Name_ShouldReturnPathRoot_IfDirectoryPathIsPathRoot(string directoryPath, string expectedName) + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath); - // Act - var actualName = directoryInfo.Name; + // Act + var actualName = directoryInfo.Name; - // Assert - await That(actualName).IsEqualTo(expectedName); - } + // Assert + await That(actualName).IsEqualTo(expectedName); + } - [Test] - public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentDirectoryIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentDirectoryIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => new MockDirectoryInfo(fileSystem, null); + // Act + Action action = () => new MockDirectoryInfo(fileSystem, null); - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + } - [Test] - public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentFileSystemIsNull() - { - // Arrange - // nothing to do + [Test] + public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentNullException_IfArgumentFileSystemIsNull() + { + // Arrange + // nothing to do - // Act - Action action = () => new MockDirectoryInfo(null, XFS.Path(@"c:\foo\bar\folder")); + // Act + Action action = () => new MockDirectoryInfo(null, XFS.Path(@"c:\foo\bar\folder")); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentException_IfArgumentDirectoryIsEmpty() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockDirectoryInfo_Constructor_ShouldThrowArgumentException_IfArgumentDirectoryIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => new MockDirectoryInfo(fileSystem, string.Empty); + // Act + Action action = () => new MockDirectoryInfo(fileSystem, string.Empty); - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("The path is not of a legal form."); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("The path is not of a legal form."); + } - [TestCase(@"c:\temp\folder\folder")] - [TestCase(@"..\..\..\Desktop")] - public async Task MockDirectoryInfo_ToString_ShouldReturnDirectoryName(string directoryName) - { - // Arrange - var directoryPath = XFS.Path(directoryName); + [TestCase(@"c:\temp\folder\folder")] + [TestCase(@"..\..\..\Desktop")] + public async Task MockDirectoryInfo_ToString_ShouldReturnDirectoryName(string directoryName) + { + // Arrange + var directoryPath = XFS.Path(directoryName); - // Act - var mockDirectoryInfo = new MockDirectoryInfo(new MockFileSystem(), directoryPath); + // Act + var mockDirectoryInfo = new MockDirectoryInfo(new MockFileSystem(), directoryPath); - // Assert - await That(mockDirectoryInfo.ToString()).IsEqualTo(directoryPath); - } + // Assert + await That(mockDirectoryInfo.ToString()).IsEqualTo(directoryPath); + } - [Test] - public async Task MockDirectoryInfo_Exists_ShouldReturnCachedData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\abc"); - var directoryInfo = fileSystem.DirectoryInfo.New(path); + [Test] + public async Task MockDirectoryInfo_Exists_ShouldReturnCachedData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\abc"); + var directoryInfo = fileSystem.DirectoryInfo.New(path); - // Act - fileSystem.AddDirectory(path); + // Act + fileSystem.AddDirectory(path); - // Assert - await That(directoryInfo.Exists).IsFalse(); - } + // Assert + await That(directoryInfo.Exists).IsFalse(); + } - [Test] - public async Task MockDirectoryInfo_Exists_ShouldUpdateCachedDataOnRefresh() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\abc"); - var directoryInfo = fileSystem.DirectoryInfo.New(path); + [Test] + public async Task MockDirectoryInfo_Exists_ShouldUpdateCachedDataOnRefresh() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\abc"); + var directoryInfo = fileSystem.DirectoryInfo.New(path); - // Act - fileSystem.AddDirectory(path); - directoryInfo.Refresh(); + // Act + fileSystem.AddDirectory(path); + directoryInfo.Refresh(); - // Assert - await That(directoryInfo.Exists).IsTrue(); - } + // Assert + await That(directoryInfo.Exists).IsTrue(); + } - [Test] - public async Task Directory_exists_after_creation() - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\abc")); + [Test] + public async Task Directory_exists_after_creation() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\abc")); - // Act - directoryInfo.Create(); + // Act + directoryInfo.Create(); - // Assert - await That(directoryInfo.Exists).IsTrue(); - } + // Assert + await That(directoryInfo.Exists).IsTrue(); + } - [Test, WindowsOnly(WindowsSpecifics.AccessControlLists)] - public async Task Directory_exists_after_creation_with_security() - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\abc")); + [Test, WindowsOnly(WindowsSpecifics.AccessControlLists)] + public async Task Directory_exists_after_creation_with_security() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\abc")); - // Act + // Act #pragma warning disable CA1416 - directoryInfo.Create(new DirectorySecurity()); + directoryInfo.Create(new DirectorySecurity()); #pragma warning restore CA1416 - // Assert - await That(directoryInfo.Exists).IsTrue(); - } + // Assert + await That(directoryInfo.Exists).IsTrue(); + } - [Test] - public async Task Directory_does_not_exist_after_delete() - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); + [Test] + public async Task Directory_does_not_exist_after_delete() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); - // Act - directoryInfo.Delete(); + // Act + directoryInfo.Delete(); - // Assert - await That(directoryInfo.Exists).IsFalse(); - } + // Assert + await That(directoryInfo.Exists).IsFalse(); + } - [Test] - public async Task Directory_does_not_exist_after_recursive_delete() - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); + [Test] + public async Task Directory_does_not_exist_after_recursive_delete() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); - // Act - directoryInfo.Delete(true); + // Act + directoryInfo.Delete(true); - // Assert - await That(directoryInfo.Exists).IsFalse(); - } + // Assert + await That(directoryInfo.Exists).IsFalse(); + } - [Test] - public async Task Directory_still_exists_after_move() - { - // Arrange - var fileSystem = new MockFileSystem(); - var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); + [Test] + public async Task Directory_still_exists_after_move() + { + // Arrange + var fileSystem = new MockFileSystem(); + var directoryInfo = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\abc")); - // Act - directoryInfo.MoveTo(XFS.Path(@"c:\abc2")); + // Act + directoryInfo.MoveTo(XFS.Path(@"c:\abc2")); - // Assert - await That(directoryInfo.Exists).IsTrue(); - } + // Assert + await That(directoryInfo.Exists).IsTrue(); + } - [Test] - public async Task MockDirectoryInfo_LastAccessTime_ShouldReflectChangedValue() + [Test] + public async Task MockDirectoryInfo_LastAccessTime_ShouldReflectChangedValue() + { + // Arrange + var path = XFS.Path(@"c:\abc"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var path = XFS.Path(@"c:\abc"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockDirectoryData() } - }); - var directoryInfo = fileSystem.DirectoryInfo.New(path); - var lastAccessTime = new DateTime(2022, 1, 8); + { path, new MockDirectoryData() } + }); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + var lastAccessTime = new DateTime(2022, 1, 8); - // Act - directoryInfo.LastAccessTime = lastAccessTime; + // Act + directoryInfo.LastAccessTime = lastAccessTime; - // Assert - await That(directoryInfo.LastAccessTime).IsEqualTo(lastAccessTime); - } - - [Test] - public async Task MockDirectoryInfo_CreationTime_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + // Assert + await That(directoryInfo.LastAccessTime).IsEqualTo(lastAccessTime); + } - var result = directoryInfo.CreationTime; + [Test] + public async Task MockDirectoryInfo_CreationTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + var result = directoryInfo.CreationTime; - [Test] - public async Task MockDirectoryInfo_LastAccessTime_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } - var result = directoryInfo.LastAccessTime; + [Test] + public async Task MockDirectoryInfo_LastAccessTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + var result = directoryInfo.LastAccessTime; - [Test] - public async Task MockDirectoryInfo_LastWriteTime_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } - var result = directoryInfo.LastWriteTime; + [Test] + public async Task MockDirectoryInfo_LastWriteTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + var result = directoryInfo.LastWriteTime; - [Test] - public async Task MockDirectoryInfo_CreationTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } - var result = directoryInfo.CreationTimeUtc; + [Test] + public async Task MockDirectoryInfo_CreationTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + var result = directoryInfo.CreationTimeUtc; - [Test] - public async Task MockDirectoryInfo_LastAccessTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } - var result = directoryInfo.LastAccessTimeUtc; + [Test] + public async Task MockDirectoryInfo_LastAccessTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + var result = directoryInfo.LastAccessTimeUtc; - [Test] - public async Task MockDirectoryInfo_LastWriteTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } - var result = directoryInfo.LastWriteTimeUtc; + [Test] + public async Task MockDirectoryInfo_LastWriteTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + var result = directoryInfo.LastWriteTimeUtc; - [Test] - public async Task MockDirectoryInfo_Create_WithConflictingFile_ShouldThrowIOException() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); - var sut = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\foo\bar.txt")); + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } - // Act - Action action = () => sut.Create(); + [Test] + public async Task MockDirectoryInfo_Create_WithConflictingFile_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + var sut = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\foo\bar.txt")); - // Assert - await That(action).Throws(); - } + // Act + Action action = () => sut.Create(); - public async Task MockDirectoryInfo_CreationTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() - { - var newTime = new DateTime(2022, 04, 06); - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + // Assert + await That(action).Throws(); + } - await That(() => directoryInfo.CreationTime = newTime).Throws(); - } + public async Task MockDirectoryInfo_CreationTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - public async Task MockDirectoryInfo_LastAccessTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() - { - var newTime = new DateTime(2022, 04, 06); - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(() => directoryInfo.CreationTime = newTime).Throws(); + } - await That(() => directoryInfo.LastAccessTime = newTime).Throws(); - } + public async Task MockDirectoryInfo_LastAccessTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - public async Task MockDirectoryInfo_LastWriteTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() - { - var newTime = new DateTime(2022, 04, 06); - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(() => directoryInfo.LastAccessTime = newTime).Throws(); + } - await That(() => directoryInfo.LastWriteTime = newTime).Throws(); - } + public async Task MockDirectoryInfo_LastWriteTime_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - public async Task MockDirectoryInfo_CreationTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() - { - var newTime = new DateTime(2022, 04, 06); - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(() => directoryInfo.LastWriteTime = newTime).Throws(); + } - await That(() => directoryInfo.CreationTimeUtc = newTime).Throws(); - } + public async Task MockDirectoryInfo_CreationTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - public async Task MockDirectoryInfo_LastAccessTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() - { - var newTime = new DateTime(2022, 04, 06); - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(() => directoryInfo.CreationTimeUtc = newTime).Throws(); + } - await That(() => directoryInfo.LastAccessTimeUtc = newTime).Throws(); - } + public async Task MockDirectoryInfo_LastAccessTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); - public async Task MockDirectoryInfo_LastWriteTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() - { - var newTime = new DateTime(2022, 04, 06); - var fileSystem = new MockFileSystem(); - var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(() => directoryInfo.LastAccessTimeUtc = newTime).Throws(); + } - await That(() => directoryInfo.LastWriteTime = newTime).Throws(); - } + public async Task MockDirectoryInfo_LastWriteTimeUtc_SetterShouldThrowDirectoryNotFoundExceptionForNonExistingDirectory() + { + var newTime = new DateTime(2022, 04, 06); + var fileSystem = new MockFileSystem(); + var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\non\existing")); + await That(() => directoryInfo.LastWriteTime = newTime).Throws(); } -} + +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySetAccessControlTests.cs index 74245ae38..3d18ff9dc 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySetAccessControlTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySetAccessControlTests.cs @@ -1,68 +1,67 @@ using NUnit.Framework; using System.Collections.Generic; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using System.Runtime.Versioning; - using Security.AccessControl; - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using System.Runtime.Versioning; +using Security.AccessControl; +using XFS = MockUnixSupport; - [TestFixture] - [SupportedOSPlatform("windows")] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - public class MockDirectorySetAccessControlTests +[TestFixture] +[SupportedOSPlatform("windows")] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +public class MockDirectorySetAccessControlTests +{ + [TestCase(" ")] + [TestCase(" ")] + public async Task MockDirectory_SetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockDirectory_SetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - var directorySecurity = new DirectorySecurity(); + // Arrange + var fileSystem = new MockFileSystem(); + var directorySecurity = new DirectorySecurity(); - // Act - Action action = () => fileSystem.Directory.SetAccessControl(path, directorySecurity); + // Act + Action action = () => fileSystem.Directory.SetAccessControl(path, directorySecurity); - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockDirectory_SetAccessControl_ShouldThrowDirectoryNotFoundExceptionIfDirectoryDoesNotExistInMockData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var expectedFileName = XFS.Path(@"c:\a\"); - var directorySecurity = new DirectorySecurity(); + [Test] + public async Task MockDirectory_SetAccessControl_ShouldThrowDirectoryNotFoundExceptionIfDirectoryDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedFileName = XFS.Path(@"c:\a\"); + var directorySecurity = new DirectorySecurity(); - // Act - Action action = () => fileSystem.Directory.SetAccessControl(expectedFileName, directorySecurity); + // Act + Action action = () => fileSystem.Directory.SetAccessControl(expectedFileName, directorySecurity); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockDirectory_SetAccessControl_ShouldSetAccessControlOfDirectoryData() - { - // Arrange - var filePath = XFS.Path(@"c:\a\"); - var fileData = new MockDirectoryData(); + [Test] + public async Task MockDirectory_SetAccessControl_ShouldSetAccessControlOfDirectoryData() + { + // Arrange + var filePath = XFS.Path(@"c:\a\"); + var fileData = new MockDirectoryData(); - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); - // Act - var expectedAccessControl = new DirectorySecurity(); - expectedAccessControl.SetAccessRuleProtection(false, false); - fileSystem.Directory.SetAccessControl(filePath, expectedAccessControl); + // Act + var expectedAccessControl = new DirectorySecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + fileSystem.Directory.SetAccessControl(filePath, expectedAccessControl); - // Assert - var accessControl = fileSystem.Directory.GetAccessControl(filePath); - await That(accessControl).IsEqualTo(expectedAccessControl); - } + // Assert + var accessControl = fileSystem.Directory.GetAccessControl(filePath); + await That(accessControl).IsEqualTo(expectedAccessControl); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySymlinkTests.cs index 0b9ee0ed4..e0e617b7a 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySymlinkTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectorySymlinkTests.cs @@ -1,295 +1,294 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; - [TestFixture] - public class MockDirectorySymlinkTests - { +using XFS = MockUnixSupport; + +[TestFixture] +public class MockDirectorySymlinkTests +{ #if FEATURE_CREATE_SYMBOLIC_LINK - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldReturnFileSystemInfo() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo"); - var path = XFS.Path(@"C:\bar"); - fileSystem.AddDirectory(pathToTarget); - - // Act - IFileSystemInfo fileSystemInfo = fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); - - // Assert - await That(fileSystemInfo.FullName).IsEqualTo(path); - await That(fileSystemInfo.LinkTarget).IsEqualTo(pathToTarget); - } + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldReturnFileSystemInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + var path = XFS.Path(@"C:\bar"); + fileSystem.AddDirectory(pathToTarget); + + // Act + IFileSystemInfo fileSystemInfo = fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + + // Assert + await That(fileSystemInfo.FullName).IsEqualTo(path); + await That(fileSystemInfo.LinkTarget).IsEqualTo(pathToTarget); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldSucceedFromDirectoryInfo() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo"); - var path = XFS.Path(@"C:\bar"); - fileSystem.AddDirectory(pathToTarget); - - // Act - fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); - IDirectoryInfo directoryInfo = fileSystem.DirectoryInfo.New(path); - - // Assert - await That(directoryInfo.FullName).IsEqualTo(path); - await That(directoryInfo.LinkTarget).IsEqualTo(pathToTarget); - } + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldSucceedFromDirectoryInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + var path = XFS.Path(@"C:\bar"); + fileSystem.AddDirectory(pathToTarget); + + // Act + fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + IDirectoryInfo directoryInfo = fileSystem.DirectoryInfo.New(path); + + // Assert + await That(directoryInfo.FullName).IsEqualTo(path); + await That(directoryInfo.LinkTarget).IsEqualTo(pathToTarget); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithNullPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo"); - fileSystem.AddDirectory(pathToTarget); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithNullPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); - // Act - var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(null, pathToTarget)).Throws(); + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(null, pathToTarget)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("path"); - } + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithNullTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"C:\Folder\foo"); - fileSystem.AddDirectory(path); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithNullTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(path); - // Act - var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, null)).Throws(); + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, null)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("pathToTarget"); - } + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithEmptyPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo"); - fileSystem.AddDirectory(pathToTarget); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithEmptyPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); - // Act - var ex = await That(() => fileSystem.Directory.CreateSymbolicLink("", pathToTarget)).Throws(); + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink("", pathToTarget)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("path"); - } + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithEmptyTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\Folder\foo"); - fileSystem.AddDirectory(path); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithEmptyTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(path); - // Act - var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, "")).Throws(); + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, "")).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("pathToTarget"); - } + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - string pathToTarget = XFS.Path(@"C:\Folder\foo"); - fileSystem.AddDirectory(pathToTarget); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); - // Act - var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(" ", pathToTarget)).Throws(); + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(" ", pathToTarget)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("path"); - } + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\Folder\foo"); - fileSystem.AddDirectory(path); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(path); - // Act - var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, " ")).Throws(); + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, " ")).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("pathToTarget"); - } + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalCharactersInPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - string pathToTarget = XFS.Path(@"C:\Folder\foo"); - fileSystem.AddDirectory(pathToTarget); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalCharactersInPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo"); + fileSystem.AddDirectory(pathToTarget); - // Act - Action ex = () => fileSystem.Directory.CreateSymbolicLink(@"C:\bar_?_", pathToTarget); + // Act + Action ex = () => fileSystem.Directory.CreateSymbolicLink(@"C:\bar_?_", pathToTarget); - // Assert - await That(ex).Throws(); - } + // Assert + await That(ex).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalCharactersInTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\foo"); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailWithIllegalCharactersInTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\foo"); - // Act - Action ex = () => fileSystem.Directory.CreateSymbolicLink(path, @"C:\bar_?_"); + // Act + Action ex = () => fileSystem.Directory.CreateSymbolicLink(path, @"C:\bar_?_"); - // Assert - await That(ex).Throws(); - } + // Assert + await That(ex).Throws(); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldFailIfPathExists() - { - // Arrange - var fileSystem = new MockFileSystem(); - string pathToTarget = XFS.Path(@"C:\Folder\foo"); - string path = XFS.Path(@"C:\Folder\bar"); - fileSystem.AddDirectory(pathToTarget); - fileSystem.AddDirectory(path); - - // Act - var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, pathToTarget)).Throws(); - - // Assert - await That(ex.Message).Contains("path"); - } + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldFailIfPathExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo"); + string path = XFS.Path(@"C:\Folder\bar"); + fileSystem.AddDirectory(pathToTarget); + fileSystem.AddDirectory(path); + + // Act + var ex = await That(() => fileSystem.Directory.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains("path"); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldNotFailIfTargetDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\Folder\foo"); - string pathToTarget = XFS.Path(@"C:\Target"); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldNotFailIfTargetDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo"); + string pathToTarget = XFS.Path(@"C:\Target"); - // Act - var fileSystemInfo = fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + // Act + var fileSystemInfo = fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); - // Assert - await That(fileSystemInfo.Exists).IsTrue(); - } + // Assert + await That(fileSystemInfo.Exists).IsTrue(); + } - [Test] - public async Task MockDirectory_CreateSymbolicLink_ShouldSetReparsePointAttribute() - { - var path = "foo"; - var pathToTarget = "bar"; - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(pathToTarget); + [Test] + public async Task MockDirectory_CreateSymbolicLink_ShouldSetReparsePointAttribute() + { + var path = "foo"; + var pathToTarget = "bar"; + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(pathToTarget); - fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); + fileSystem.Directory.CreateSymbolicLink(path, pathToTarget); - var attributes = fileSystem.DirectoryInfo.New(path).Attributes; - await That(attributes.HasFlag(FileAttributes.ReparsePoint)).IsTrue(); - } + var attributes = fileSystem.DirectoryInfo.New(path).Attributes; + await That(attributes.HasFlag(FileAttributes.ReparsePoint)).IsTrue(); + } - [Test] - public async Task MockDirectory_ResolveLinkTarget_ShouldReturnPathOfTargetLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + [Test] + public async Task MockDirectory_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); - var result = fileSystem.Directory.ResolveLinkTarget("foo", false); + var result = fileSystem.Directory.ResolveLinkTarget("foo", false); - await That(result.Name).IsEqualTo("bar"); - } + await That(result.Name).IsEqualTo("bar"); + } - [Test] - public async Task MockDirectory_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) { - // The maximum number of symbolic links that are followed: - // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks - var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - var previousPath = "bar"; - for (int i = 0; i < maxResolveLinks; i++) - { - string newPath = $"foo-{i}"; - fileSystem.Directory.CreateSymbolicLink(newPath, previousPath); - previousPath = newPath; - } - - var result = fileSystem.Directory.ResolveLinkTarget(previousPath, true); - - await That(result.Name).IsEqualTo("bar"); + string newPath = $"foo-{i}"; + fileSystem.Directory.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; } - [Test] - public async Task MockDirectory_ResolveLinkTarget_WithFinalTargetWithTooManyLinks_ShouldThrowIOException() + var result = fileSystem.Directory.ResolveLinkTarget(previousPath, true); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithFinalTargetWithTooManyLinks_ShouldThrowIOException() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + maxResolveLinks++; + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) { - // The maximum number of symbolic links that are followed: - // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks - var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; - maxResolveLinks++; - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - var previousPath = "bar"; - for (int i = 0; i < maxResolveLinks; i++) - { - string newPath = $"foo-{i}"; - fileSystem.Directory.CreateSymbolicLink(newPath, previousPath); - previousPath = newPath; - } - - await That(() => fileSystem.Directory.ResolveLinkTarget(previousPath, true)).Throws(); + string newPath = $"foo-{i}"; + fileSystem.Directory.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; } - [Test] - public async Task MockDirectory_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - fileSystem.Directory.CreateSymbolicLink("foo", "bar"); - fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); + await That(() => fileSystem.Directory.ResolveLinkTarget(previousPath, true)).Throws(); + } - var result = fileSystem.Directory.ResolveLinkTarget("foo1", false); + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + fileSystem.Directory.CreateSymbolicLink("foo1", "foo"); - await That(result.Name).IsEqualTo("foo"); - } + var result = fileSystem.Directory.ResolveLinkTarget("foo1", false); - [Test] - public async Task MockDirectory_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + await That(result.Name).IsEqualTo("foo"); + } + + [Test] + public async Task MockDirectory_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("bar"); + fileSystem.Directory.CreateSymbolicLink("foo", "bar"); + + await That(() => { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("bar"); - fileSystem.Directory.CreateSymbolicLink("foo", "bar"); - - await That(() => - { - fileSystem.Directory.ResolveLinkTarget("bar", false); - }).Throws(); - } -#endif + fileSystem.Directory.ResolveLinkTarget("bar", false); + }).Throws(); } -} +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryTests.cs index 1254e3391..fcad7ebe5 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDirectoryTests.cs @@ -5,2192 +5,2191 @@ using aweXpect.Equivalency; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; - - [TestFixture] - public class MockDirectoryTests - { - [Test] - public async Task MockDirectory_GetFiles_ShouldReturnAllFilesBelowPathWhenPatternIsEmptyAndSearchOptionIsAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif"), - XFS.Path(@"c:\a\a\d") - }; +namespace System.IO.Abstractions.TestingHelpers.Tests; - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "", SearchOption.AllDirectories); +using XFS = MockUnixSupport; - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } +[TestFixture] +public class MockDirectoryTests +{ + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnAllFilesBelowPathWhenPatternIsEmptyAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsEmptyAndSearchOptionIsTopDirectoryOnly() + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsEmptyAndSearchOptionIsTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "", SearchOption.TopDirectoryOnly); + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d") + }; - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "", SearchOption.TopDirectoryOnly); - [Test] - public async Task MockDirectory_GetFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif"), - XFS.Path(@"c:\a\a\d") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } #if FEATURE_ENUMERATION_OPTIONS - [Test] - public async Task MockDirectory_GetFiles_ShouldReturnAllPatternMatchingFilesWhenEnumerationOptionHasRecurseSubdirectoriesSetToTrue() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\b.txt"), - XFS.Path(@"c:\c.txt"), - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.txt", new EnumerationOptions { RecurseSubdirectories = true }); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnAllPatternMatchingFilesWhenEnumerationOptionHasRecurseSubdirectoriesSetToTrue() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] + { + XFS.Path(@"c:\b.txt"), + XFS.Path(@"c:\c.txt"), + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.txt", new EnumerationOptions { RecurseSubdirectories = true }); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } #endif - private MockFileSystem SetupFileSystem() - { - return new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\d"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\d"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\d"), new MockFileData("Demo text content") } - }); - - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsWildcardAndSearchOptionIsTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.TopDirectoryOnly); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPattern() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RespectingAllDirectorySearchOption() - { - // Arrange - var additionalFilePath = XFS.Path(@"c:\a\a\c.gifx"); - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifz\xyz"), new MockFileData(string.Empty)); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif"), - additionalFilePath - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RespectingTopDirectorySearchOption() - { - // Arrange - var additionalFilePath = XFS.Path(@"c:\a\c.gifx"); - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); - var expected = new[] - { - XFS.Path(@"c:\a\b.gif"), - additionalFilePath - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gif", SearchOption.TopDirectoryOnly); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternOnlyIfTheFileExtensionIsThreeCharacterLong() - { - // Arrange - var additionalFilePath = XFS.Path(@"c:\a\c.gi"); - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gif"), new MockFileData(string.Empty)); - fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); - var expected = new[] - { - additionalFilePath - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gi", SearchOption.AllDirectories); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithDotsInFilenames() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - }); - var expected = new[] - { - XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_FilterShouldFindFilesWithSpecialChars() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.1#.pdf"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b\b #1.txt"), new MockFileData("Demo text content") } - }); - var expected = new[] - { - XFS.Path(@"c:\a.1#.pdf"), - XFS.Path(@"c:\b\b #1.txt") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.*", SearchOption.AllDirectories); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternAndSearchOptionTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] { XFS.Path(@"c:\a.gif") }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.TopDirectoryOnly); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterForAllFilesWithNoExtensionsAndSearchOptionTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); - - var expected = new[] - { - XFS.Path(@"c:\d"), - XFS.Path(@"C:\mytestfilename"), - XFS.Path(@"C:\mytestfilename."), - XFS.Path(@"C:\mytestfile.name."), - XFS.Path(@"C:\mytestfile.name.again.") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "*.", SearchOption.TopDirectoryOnly); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterForAllFilesWithNoExtensionsAndSearchOptionAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfilename"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfilename."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name.again"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name.again."), new MockFileData("some content")); - - var expected = new[] - { - XFS.Path(@"c:\d"), - XFS.Path(@"c:\a\d"), - XFS.Path(@"c:\a\a\d"), - XFS.Path(@"C:\specialNameFormats\mytestfilename"), - XFS.Path(@"C:\specialNameFormats\mytestfilename."), - XFS.Path(@"C:\specialNameFormats\mytestfile.name."), - XFS.Path(@"C:\specialNameFormats\mytestfile.name.again.") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.", SearchOption.AllDirectories); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndNonTrivialFilterAndSearchOptionTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); - - var expected = new[] - { - XFS.Path(@"C:\mytestfilename"), - XFS.Path(@"C:\mytestfilename."), - XFS.Path(@"C:\mytestfile.name."), - XFS.Path(@"C:\mytestfile.name.again.") - - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my??s*.", SearchOption.TopDirectoryOnly); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndNonTrivialFilter2AndSearchOptionTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); - - var expected = new[] - { - XFS.Path(@"C:\mytestfile.name"), - XFS.Path(@"C:\mytestfile.name."), - XFS.Path(@"C:\mytestfile.name.again.") - - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my*.n*.", SearchOption.TopDirectoryOnly); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - [Test] - public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndFilterThatIncludesDotAndSearchOptionTopDirectoryOnly() - { - // Arrange - var fileSystem = SetupFileSystem(); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); - fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); - - var expected = new[] - { - XFS.Path(@"C:\mytestfile.name"), - XFS.Path(@"C:\mytestfile.name."), - XFS.Path(@"C:\mytestfile.name.again.") - }; - - // Act - var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my*.n*.", SearchOption.TopDirectoryOnly); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } - - private async Task ExecuteTimeAttributeTest(DateTime time, Action setter, Func getter) - { - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - - // Act - setter(fileSystem, path, time); - var result = getter(fileSystem, path); - - // Assert - await That(result).IsEqualTo(time); - } - - [Test] - public async Task MockDirectory_GetCreationTime_ShouldReturnCreationTimeFromFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42), - (fs, p, d) => fs.File.SetCreationTime(p, d), - (fs, p) => fs.Directory.GetCreationTime(p)); - } - - [Test] - public async Task MockDirectory_GetCreationTimeUtc_ShouldReturnCreationTimeUtcFromFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), - (fs, p, d) => fs.File.SetCreationTimeUtc(p, d), - (fs, p) => fs.Directory.GetCreationTimeUtc(p)); - } - - [Test] - public async Task MockDirectory_GetLastAccessTime_ShouldReturnLastAccessTimeFromFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42), - (fs, p, d) => fs.File.SetLastAccessTime(p, d), - (fs, p) => fs.Directory.GetLastAccessTime(p)); - } - - [Test] - public async Task MockDirectory_GetLastAccessTimeUtc_ShouldReturnLastAccessTimeUtcFromFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), - (fs, p, d) => fs.File.SetLastAccessTimeUtc(p, d), - (fs, p) => fs.Directory.GetLastAccessTimeUtc(p)); - } - - [Test] - public async Task MockDirectory_GetLastWriteTime_ShouldReturnLastWriteTimeFromFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42), - (fs, p, d) => fs.File.SetLastWriteTime(p, d), - (fs, p) => fs.Directory.GetLastWriteTime(p)); - } - - [Test] - public async Task MockDirectory_GetLastWriteTimeUtc_ShouldReturnLastWriteTimeUtcFromFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), - (fs, p, d) => fs.File.SetLastWriteTimeUtc(p, d), - (fs, p) => fs.Directory.GetLastWriteTimeUtc(p)); - } - - [Test] - public async Task MockDirectory_SetCreationTime_ShouldSetCreationTimeOnFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42), - (fs, p, d) => fs.Directory.SetCreationTime(p, d), - (fs, p) => fs.File.GetCreationTime(p)); - } - - [Test] - public async Task MockDirectory_SetCreationTimeUtc_ShouldSetCreationTimeUtcOnFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), - (fs, p, d) => fs.Directory.SetCreationTimeUtc(p, d), - (fs, p) => fs.File.GetCreationTimeUtc(p)); - } - - [Test] - public async Task MockDirectory_SetLastAccessTime_ShouldSetLastAccessTimeOnFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42), - (fs, p, d) => fs.Directory.SetLastAccessTime(p, d), - (fs, p) => fs.File.GetLastAccessTime(p)); - } - - [Test] - public async Task MockDirectory_SetLastAccessTimeUtc_ShouldSetLastAccessTimeUtcOnFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), - (fs, p, d) => fs.Directory.SetLastAccessTimeUtc(p, d), - (fs, p) => fs.File.GetLastAccessTimeUtc(p)); - } - - [Test] - public async Task MockDirectory_SetLastWriteTime_ShouldSetLastWriteTimeOnFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42), - (fs, p, d) => fs.Directory.SetLastWriteTime(p, d), - (fs, p) => fs.File.GetLastWriteTime(p)); - } + private MockFileSystem SetupFileSystem() + { + return new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\d"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\d"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\d"), new MockFileData("Demo text content") } + }); - [Test] - public async Task MockDirectory_SetLastWriteTimeUtc_ShouldSetLastWriteTimeUtcOnFile() - { - await ExecuteTimeAttributeTest( - new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), - (fs, p, d) => fs.Directory.SetLastWriteTimeUtc(p, d), - (fs, p) => fs.File.GetLastWriteTimeUtc(p)); - } + } - [Test] - public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithoutTrailingSlash() + [Test] + public async Task MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsWildcardAndSearchOptionIsTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d") + }; - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo")); + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*", SearchOption.TopDirectoryOnly); - // Assert - await That(result).IsTrue(); - } + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithTrailingSlash() + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPattern() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); - - // Assert - await That(result).IsTrue(); - } - - [Test] - public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithoutTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsFalse(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RespectingAllDirectorySearchOption() + { + // Arrange + var additionalFilePath = XFS.Path(@"c:\a\a\c.gifx"); + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifz\xyz"), new MockFileData(string.Empty)); + var expected = new[] + { + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif"), + additionalFilePath + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithThreeCharacterLongFileExtension_RespectingTopDirectorySearchOption() + { + // Arrange + var additionalFilePath = XFS.Path(@"c:\a\c.gifx"); + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); + var expected = new[] + { + XFS.Path(@"c:\a\b.gif"), + additionalFilePath + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gif", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz\")); + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternOnlyIfTheFileExtensionIsThreeCharacterLong() + { + // Arrange + var additionalFilePath = XFS.Path(@"c:\a\c.gi"); + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(additionalFilePath, new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx.xyz"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gif"), new MockFileData(string.Empty)); + fileSystem.AddFile(XFS.Path(@"c:\a\a\c.gifx"), new MockFileData(string.Empty)); + var expected = new[] + { + additionalFilePath + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\a"), "*.gi", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsFalse(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternWithDotsInFilenames() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + }); + var expected = new[] + { + XFS.Path(@"c:\a.there.are.dots.in.this.filename.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithSimilarFileName() + [Test] + public async Task MockDirectory_GetFiles_FilterShouldFindFilesWithSpecialChars() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\baz.txt"), new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); - - // Assert - await That(result).IsFalse(); - } - - [Test] - public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryCreatedViaMocks() + { XFS.Path(@"c:\a.1#.pdf"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b\b #1.txt"), new MockFileData("Demo text content") } + }); + var expected = new[] { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } - }); - fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); - - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\bar")); + XFS.Path(@"c:\a.1#.pdf"), + XFS.Path(@"c:\b\b #1.txt") + }; - // Assert - await That(result).IsTrue(); - } - - [Test] - public async Task MockDirectory_Exists_ShouldReturnTrueForFolderContainingFileAddedToMockFileSystem() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.*", SearchOption.AllDirectories); - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsTrue(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] { XFS.Path(@"c:\a.gif") }; - [TestCase(@"\\s")] - [TestCase(@"<")] - [TestCase("\t")] - public async Task MockDirectory_Exists_ShouldReturnFalseForIllegalPath(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.TopDirectoryOnly); - // Act - var result = fileSystem.Directory.Exists(path); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsFalse(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForAllFilesWithNoExtensionsAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"c:\d"), + XFS.Path(@"C:\mytestfilename"), + XFS.Path(@"C:\mytestfilename."), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "*.", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_CreateDirectory_WithConflictingFile_ShouldThrowIOException() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); - - // Act - Action action = () => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\bar.txt")); + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForAllFilesWithNoExtensionsAndSearchOptionAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\specialNameFormats\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"c:\d"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\d"), + XFS.Path(@"C:\specialNameFormats\mytestfilename"), + XFS.Path(@"C:\specialNameFormats\mytestfilename."), + XFS.Path(@"C:\specialNameFormats\mytestfile.name."), + XFS.Path(@"C:\specialNameFormats\mytestfile.name.again.") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), "*.", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(action).Throws(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndNonTrivialFilterAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); - [Test] - public async Task MockDirectory_Exists_ShouldReturnFalseForFiles() + var expected = new[] { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + XFS.Path(@"C:\mytestfilename"), + XFS.Path(@"C:\mytestfilename."), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") - // Act - var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\bar.txt")); + }; - // Assert - await That(result).IsFalse(); - } - - [Test] - public async Task MockDirectory_CreateDirectory_ShouldCreateFolderInMemoryFileSystem() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } - }); + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my??s*.", SearchOption.TopDirectoryOnly); - // Act - fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(fileSystem.FileExists(XFS.Path(@"c:\bar\"))).IsTrue(); - await That(fileSystem.AllDirectories.Any(d => d == XFS.Path(@"c:\bar"))).IsTrue(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndNonTrivialFilter2AndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); - [Test] - public async Task MockDirectory_CreateDirectory_ShouldThrowIfIllegalCharacterInPath() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } - }); + var expected = new[] + { + XFS.Path(@"C:\mytestfile.name"), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") - // Act - Action createDelegate = () => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar_?_")); + }; - // Assert - await That(createDelegate).Throws(); - } + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my*.n*.", SearchOption.TopDirectoryOnly); - // Issue #210 - [Test] - public async Task MockDirectory_CreateDirectory_ShouldIgnoreExistingDirectoryRegardlessOfTrailingSlash() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\"), new MockDirectoryData() } - }); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Act/Assert - await That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo"))).DoesNotThrow(); - await That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\"))).DoesNotThrow(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldFilterForFilesWithNoExtensionsAndFilterThatIncludesDotAndSearchOptionTopDirectoryOnly() + { + // Arrange + var fileSystem = SetupFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfilename."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name."), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again"), new MockFileData("some content")); + fileSystem.AddFile(XFS.Path(@"C:\mytestfile.name.again."), new MockFileData("some content")); + + var expected = new[] + { + XFS.Path(@"C:\mytestfile.name"), + XFS.Path(@"C:\mytestfile.name."), + XFS.Path(@"C:\mytestfile.name.again.") + }; + + // Act + var result = fileSystem.Directory.GetFiles(XFS.Path(@"C:\"), "my*.n*.", SearchOption.TopDirectoryOnly); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBase() + private async Task ExecuteTimeAttributeTest(DateTime time, Action setter, Func getter) + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } - }); + { path, new MockFileData("Demo text content") } + }); - // Act - var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); + // Act + setter(fileSystem, path, time); + var result = getter(fileSystem, path); - // Assert - await That(result).IsNotNull(); - } + // Assert + await That(result).IsEqualTo(time); + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockDirectory_CreateDirectory_ShouldTrimTrailingSpaces() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockDirectory_GetCreationTime_ShouldReturnCreationTimeFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.File.SetCreationTime(p, d), + (fs, p) => fs.Directory.GetCreationTime(p)); + } - // Act - fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\temp\folder ")); + [Test] + public async Task MockDirectory_GetCreationTimeUtc_ShouldReturnCreationTimeUtcFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.File.SetCreationTimeUtc(p, d), + (fs, p) => fs.Directory.GetCreationTimeUtc(p)); + } - // Assert - await That(fileSystem.Directory.Exists(XFS.Path(@"c:\temp\folder"))).IsTrue(); - } + [Test] + public async Task MockDirectory_GetLastAccessTime_ShouldReturnLastAccessTimeFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.File.SetLastAccessTime(p, d), + (fs, p) => fs.Directory.GetLastAccessTime(p)); + } - [Test] - public async Task MockDirectory_CreMockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBaseWhenDirectoryExists() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo\"), new MockDirectoryData() } - }); + [Test] + public async Task MockDirectory_GetLastAccessTimeUtc_ShouldReturnLastAccessTimeUtcFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.File.SetLastAccessTimeUtc(p, d), + (fs, p) => fs.Directory.GetLastAccessTimeUtc(p)); + } - // Act - var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")); + [Test] + public async Task MockDirectory_GetLastWriteTime_ShouldReturnLastWriteTimeFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.File.SetLastWriteTime(p, d), + (fs, p) => fs.Directory.GetLastWriteTime(p)); + } - // Assert - await That(result).IsNotNull(); - } + [Test] + public async Task MockDirectory_GetLastWriteTimeUtc_ShouldReturnLastWriteTimeUtcFromFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.File.SetLastWriteTimeUtc(p, d), + (fs, p) => fs.Directory.GetLastWriteTimeUtc(p)); + } - [Test] - [WindowsOnly(WindowsSpecifics.UNCPaths)] - public async Task MockDirectory_CreateDirectory_ShouldWorkWithUNCPath() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockDirectory_SetCreationTime_ShouldSetCreationTimeOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.Directory.SetCreationTime(p, d), + (fs, p) => fs.File.GetCreationTime(p)); + } - // Act - fileSystem.Directory.CreateDirectory(@"\\server\share\path\to\create"); + [Test] + public async Task MockDirectory_SetCreationTimeUtc_ShouldSetCreationTimeUtcOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.Directory.SetCreationTimeUtc(p, d), + (fs, p) => fs.File.GetCreationTimeUtc(p)); + } - // Assert - await That(fileSystem.Directory.Exists(@"\\server\share\path\to\create\")).IsTrue(); - } + [Test] + public async Task MockDirectory_SetLastAccessTime_ShouldSetLastAccessTimeOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.Directory.SetLastAccessTime(p, d), + (fs, p) => fs.File.GetLastAccessTime(p)); + } - [Test] - [WindowsOnly(WindowsSpecifics.UNCPaths)] - public async Task MockDirectory_CreateDirectory_ShouldFailIfTryingToCreateUNCPathOnlyServer() + [Test] + public async Task MockDirectory_SetLastAccessTimeUtc_ShouldSetLastAccessTimeUtcOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.Directory.SetLastAccessTimeUtc(p, d), + (fs, p) => fs.File.GetLastAccessTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_SetLastWriteTime_ShouldSetLastWriteTimeOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42), + (fs, p, d) => fs.Directory.SetLastWriteTime(p, d), + (fs, p) => fs.File.GetLastWriteTime(p)); + } + + [Test] + public async Task MockDirectory_SetLastWriteTimeUtc_ShouldSetLastWriteTimeUtcOnFile() + { + await ExecuteTimeAttributeTest( + new DateTime(2010, 6, 4, 13, 26, 42, DateTimeKind.Utc), + (fs, p, d) => fs.Directory.SetLastWriteTimeUtc(p, d), + (fs, p) => fs.File.GetLastWriteTimeUtc(p)); + } + + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithoutTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); - // Act - var ex = await That(() => fileSystem.Directory.CreateDirectory(@"\\server")).Throws(); + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo")); - // Assert - await That(ex.Message).StartsWith("The UNC path should be of the form \\\\server\\share."); - await That(ex.ParamName).IsEqualTo("path"); - } + // Assert + await That(result).IsTrue(); + } - [Test] - [WindowsOnly(WindowsSpecifics.UNCPaths)] - public async Task MockDirectory_CreateDirectory_ShouldSucceedIfTryingToCreateUNCPathShare() + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryDefinedInMemoryFileSystemWithTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); - // Act - fileSystem.Directory.CreateDirectory(@"\\server\share"); + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); - // Assert - await That(fileSystem.Directory.Exists(@"\\server\share\")).IsTrue(); - } + // Assert + await That(result).IsTrue(); + } -#if FEATURE_CREATE_TEMP_SUBDIRECTORY - [Test] - public async Task MockDirectory_CreateTempSubdirectory_ShouldCreateSubdirectoryInTempDirectory() + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithoutTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); - // Act - var result = fileSystem.Directory.CreateTempSubdirectory(); + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); - // Assert - await That(fileSystem.Directory.Exists(result.FullName)).IsTrue(); - await That(result.FullName).StartsWith(fileSystem.Path.GetTempPath()); - } + // Assert + await That(result).IsFalse(); + } - [Test] - public async Task MockDirectory_CreateTempSubdirectoryWithPrefix_ShouldCreateDirectoryWithGivenPrefixInTempDirectory() + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); - // Act - var result = fileSystem.Directory.CreateTempSubdirectory("foo-"); + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz\")); - // Assert - await That(fileSystem.Directory.Exists(result.FullName)).IsTrue(); - await That(Path.GetFileName(result.FullName).StartsWith("foo-")).IsTrue(); - await That(result.FullName.Contains(fileSystem.Path.GetTempPath())).IsTrue(); - } -#endif + // Assert + await That(result).IsFalse(); + } - [Test] - public async Task MockDirectory_Delete_ShouldDeleteDirectory() + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForDirectoryNotDefinedInMemoryFileSystemWithSimilarFileName() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } - }); + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\baz.txt"), new MockFileData("Demo text content") } + }); - // Act - fileSystem.Directory.Delete(XFS.Path(@"c:\bar"), true); + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\baz")); - // Assert - await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); - } + // Assert + await That(result).IsFalse(); + } - [Test] - public async Task MockDirectory_Delete_ShouldNotDeleteAllDirectories() + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForDirectoryCreatedViaMocks() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var folder1Path = XFS.Path(@"D:\Test\Program"); - var folder1SubFolderPath = XFS.Path(@"D:\Test\Program\Subfolder"); - var folder2Path = XFS.Path(@"D:\Test\Program_bak"); + { XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content") } + }); + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); - var fileSystem = new MockFileSystem(); + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\bar")); - fileSystem.AddDirectory(folder1Path); - fileSystem.AddDirectory(folder2Path); - fileSystem.AddDirectory(folder1SubFolderPath); + // Assert + await That(result).IsTrue(); + } - // Act - fileSystem.Directory.Delete(folder1Path, recursive: true); + [Test] + public async Task MockDirectory_Exists_ShouldReturnTrueForFolderContainingFileAddedToMockFileSystem() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); - // Assert - await That(fileSystem.Directory.Exists(folder1Path)).IsFalse(); - await That(fileSystem.Directory.Exists(folder1SubFolderPath)).IsFalse(); - await That(fileSystem.Directory.Exists(folder2Path)).IsTrue(); - } + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\")); - [Test] - [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] - public async Task MockDirectory_Delete_ShouldDeleteDirectoryCaseInsensitively() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } - }); + // Assert + await That(result).IsTrue(); + } - // Act - fileSystem.Directory.Delete(XFS.Path(@"c:\BAR"), true); + [TestCase(@"\\s")] + [TestCase(@"<")] + [TestCase("\t")] + public async Task MockDirectory_Exists_ShouldReturnFalseForIllegalPath(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Assert - await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); - } + // Act + var result = fileSystem.Directory.Exists(path); - [Test] - [UnixOnly(UnixSpecifics.CaseSensitivity)] - public async Task MockDirectory_Delete_ShouldThrowDirectoryNotFoundException_WhenSpecifiedWithInDifferentCase() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { "/bar/foo.txt", new MockFileData("Demo text content") } - }); + // Assert + await That(result).IsFalse(); + } - // Act - Action action = () => fileSystem.Directory.Delete("/BAR", true); + [Test] + public async Task MockDirectory_CreateDirectory_WithConflictingFile_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); + + // Act + Action action = () => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\bar.txt")); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - [UnixOnly(UnixSpecifics.CaseSensitivity)] - public async Task MockDirectory_Delete_ShouldDeleteDirectoryCaseSensitively() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { "/bar/foo.txt", new MockFileData("Demo text content") } - }); + [Test] + public async Task MockDirectory_Exists_ShouldReturnFalseForFiles() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\foo\bar.txt"), new MockFileData("Demo text content")); - // Act - fileSystem.Directory.Delete("/bar", true); + // Act + var result = fileSystem.Directory.Exists(XFS.Path(@"c:\foo\bar.txt")); - // Assert - await That(fileSystem.Directory.Exists("/bar")).IsFalse(); - } + // Assert + await That(result).IsFalse(); + } - [Test] - public async Task MockDirectory_Delete_ShouldThrowDirectoryNotFoundException() + [Test] + public async Task MockDirectory_CreateDirectory_ShouldCreateFolderInMemoryFileSystem() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } - }); + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } + }); - var ex = await That(() => fileSystem.Directory.Delete(XFS.Path(@"c:\baz"))).Throws(); + // Act + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); - await That(ex.Message).IsEqualTo($"'{XFS.Path("c:\\baz")}' does not exist or could not be found."); - } + // Assert + await That(fileSystem.FileExists(XFS.Path(@"c:\bar\"))).IsTrue(); + await That(fileSystem.AllDirectories.Any(d => d == XFS.Path(@"c:\bar"))).IsTrue(); + } - [Test] - public async Task MockDirectory_Delete_ShouldThrowIOException() + [Test] + public async Task MockDirectory_CreateDirectory_ShouldThrowIfIllegalCharacterInPath() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\bar\baz.txt"), new MockFileData("Demo text content") } - }); + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } + }); - var ex = await That(() => fileSystem.Directory.Delete(XFS.Path(@"c:\bar"))).Throws(); + // Act + Action createDelegate = () => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar_?_")); - await That(ex.Message).IsEqualTo("The directory specified by " + XFS.Path("c:\\bar") + " is read-only, or recursive is false and " + XFS.Path("c:\\bar") + " is not an empty directory."); - } + // Assert + await That(createDelegate).Throws(); + } - [Test] - public async Task MockDirectory_Delete_ShouldDeleteDirectoryRecursively() + // Issue #210 + [Test] + public async Task MockDirectory_CreateDirectory_ShouldIgnoreExistingDirectoryRegardlessOfTrailingSlash() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\bar\bar2\foo.txt"), new MockFileData("Demo text content") } - }); - - // Act - fileSystem.DirectoryInfo.New(XFS.Path(@"c:\bar")).Delete(true); + { XFS.Path(@"c:\foo\"), new MockDirectoryData() } + }); - // Assert - await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); - await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar\bar2"))).IsFalse(); - } + // Act/Assert + await That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo"))).DoesNotThrow(); + await That(() => fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\"))).DoesNotThrow(); + } - [Test] - public async Task MockDirectory_Delete_ShouldThrowIOException_WhenPathIsAFile() + [Test] + public async Task MockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") }, - }); + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") } + }); - // Act - Action action = () => fileSystem.Directory.Delete(XFS.Path(@"c:\foo.txt")); + // Act + var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar")); - // Assert - await That(action).Throws(); - } + // Assert + await That(result).IsNotNull(); + } - [Test] - public async Task MockDirectory_GetFileSystemEntries_Returns_Files_And_Directories() - { - string testPath = XFS.Path(@"c:\foo\bar.txt"); - string testDir = XFS.Path(@"c:\foo\bar"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testPath, new MockFileData("Demo text content") }, - { testDir, new MockDirectoryData() } - }); - - var entries = fileSystem.Directory.GetFileSystemEntries(XFS.Path(@"c:\foo")).OrderBy(k => k); - await That(entries.Count()).IsEqualTo(2); - await That(entries.First()).IsEqualTo(testDir); - await That(entries.Last()).IsEqualTo(testPath); - } + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectory_CreateDirectory_ShouldTrimTrailingSpaces() + { + // Arrange + var fileSystem = new MockFileSystem(); - [Test] - public async Task MockDirectory_GetFileSystemEntries_ShouldNotReturnSubDirectory_WithSearchOption() - { - string testPath = XFS.Path(@"c:\foo\bar.txt"); - string testDir = XFS.Path(@"c:\foo\bar"); - string testSubDir = XFS.Path(@"c:\foo\bar\baz"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testPath, new MockFileData("Demo text content") }, - { testSubDir, new MockDirectoryData() }, - }); - - var entries = fileSystem.Directory.GetFileSystemEntries(XFS.Path(@"c:\foo"), "*", SearchOption.TopDirectoryOnly).OrderBy(k => k); - await That(entries.Count()).IsEqualTo(2); - await That(entries.First()).IsEqualTo(testDir); - await That(entries.Last()).IsEqualTo(testPath); - } + // Act + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\temp\folder ")); - [Test] - public async Task MockDirectory_GetFiles_ShouldThrowArgumentNullException_IfPathParamIsNull() + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\temp\folder"))).IsTrue(); + } + + [Test] + public async Task MockDirectory_CreMockDirectory_CreateDirectory_ShouldReturnDirectoryInfoBaseWhenDirectoryExists() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary()); + { XFS.Path(@"c:\foo\"), new MockDirectoryData() } + }); - Action action = () => fileSystem.Directory.GetFiles(null); - await That(action).Throws(); - } + // Act + var result = fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")); - [Test] - public async Task MockDirectory_GetFiles_ShouldThrowDirectoryNotFoundException_IfPathDoesNotExists() - { - // Arrange - var fileSystem = new MockFileSystem(); + // Assert + await That(result).IsNotNull(); + } - // Act - Action action = () => fileSystem.Directory.GetFiles(XFS.Path(@"c:\Foo"), "*a.txt"); + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectory_CreateDirectory_ShouldWorkWithUNCPath() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Assert - await That(action).Throws(); - } + // Act + fileSystem.Directory.CreateDirectory(@"\\server\share\path\to\create"); - [Test] - public async Task MockDirectory_GetFiles_Returns_Files() - { - string testPath = XFS.Path(@"c:\foo\bar.txt"); - string testDir = XFS.Path(@"c:\foo\bar\"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testPath, new MockFileData("Demo text content") }, - { testDir, new MockDirectoryData() } - }); + // Assert + await That(fileSystem.Directory.Exists(@"\\server\share\path\to\create\")).IsTrue(); + } - var entries = fileSystem.Directory.GetFiles(XFS.Path(@"c:\foo")).OrderBy(k => k); - await That(entries.Count()).IsEqualTo(1); - await That(entries.First()).IsEqualTo(testPath); - } + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectory_CreateDirectory_ShouldFailIfTryingToCreateUNCPathOnlyServer() + { + // Arrange + var fileSystem = new MockFileSystem(); - [Test] - public async Task MockDirectory_GetFiles_Returns_Files_WithRelativePath() - { - // arrange - var fileSystem = new MockFileSystem(new Dictionary()); + // Act + var ex = await That(() => fileSystem.Directory.CreateDirectory(@"\\server")).Throws(); - string directory = XFS.Path(@"C:\foo"); + // Assert + await That(ex.Message).StartsWith("The UNC path should be of the form \\\\server\\share."); + await That(ex.ParamName).IsEqualTo("path"); + } - fileSystem.Directory.SetCurrentDirectory(directory); - fileSystem.AddFile(XFS.Path(@"C:\test.txt"), new MockFileData("Some ASCII text.")); + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockDirectory_CreateDirectory_ShouldSucceedIfTryingToCreateUNCPathShare() + { + // Arrange + var fileSystem = new MockFileSystem(); - await That(fileSystem.Directory.GetFiles(XFS.Path(@"..\")).Length).IsEqualTo(1); // Assert with relative path - } + // Act + fileSystem.Directory.CreateDirectory(@"\\server\share"); + // Assert + await That(fileSystem.Directory.Exists(@"\\server\share\")).IsTrue(); + } + +#if FEATURE_CREATE_TEMP_SUBDIRECTORY [Test] - public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentNullException_IfSearchPatternIsNull() + public async Task MockDirectory_CreateTempSubdirectory_ShouldCreateSubdirectoryInTempDirectory() { // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); // Act - Action action = () => fileSystem.Directory.GetFiles(directoryPath, null); + var result = fileSystem.Directory.CreateTempSubdirectory(); // Assert - await That(action).Throws(); + await That(fileSystem.Directory.Exists(result.FullName)).IsTrue(); + await That(result.FullName).StartsWith(fileSystem.Path.GetTempPath()); } [Test] - public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternEndsWithTwoDots() + public async Task MockDirectory_CreateTempSubdirectoryWithPrefix_ShouldCreateDirectoryWithGivenPrefixInTempDirectory() { // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); // Act - Action action = () => fileSystem.Directory.GetFiles(directoryPath, "*a.."); + var result = fileSystem.Directory.CreateTempSubdirectory("foo-"); // Assert - await That(action).Throws(); + await That(fileSystem.Directory.Exists(result.FullName)).IsTrue(); + await That(Path.GetFileName(result.FullName).StartsWith("foo-")).IsTrue(); + await That(result.FullName.Contains(fileSystem.Path.GetTempPath())).IsTrue(); } +#endif - [TestCase(@"..\")] - [TestCase(@"aaa\vv..\")] - [TestCase(@"a..\b")] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternContainsTwoDotsFollowedByOneBackslash(string searchPattern) + [Test] + public async Task MockDirectory_Delete_ShouldDeleteDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } + }); - // Act - Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); + // Act + fileSystem.Directory.Delete(XFS.Path(@"c:\bar"), true); - // Assert - await That(action).Throws(); - } + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); + } - [TestCase(@"a../b")] - [TestCase(@"../")] - public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternContainsTwoDotsFollowedByOneSlash(string searchPattern) + [Test] + public async Task MockDirectory_Delete_ShouldNotDeleteAllDirectories() + { + // Arrange + var folder1Path = XFS.Path(@"D:\Test\Program"); + var folder1SubFolderPath = XFS.Path(@"D:\Test\Program\Subfolder"); + var folder2Path = XFS.Path(@"D:\Test\Program_bak"); + + var fileSystem = new MockFileSystem(); + + fileSystem.AddDirectory(folder1Path); + fileSystem.AddDirectory(folder2Path); + fileSystem.AddDirectory(folder1SubFolderPath); + + // Act + fileSystem.Directory.Delete(folder1Path, recursive: true); + + // Assert + await That(fileSystem.Directory.Exists(folder1Path)).IsFalse(); + await That(fileSystem.Directory.Exists(folder1SubFolderPath)).IsFalse(); + await That(fileSystem.Directory.Exists(folder2Path)).IsTrue(); + } + + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockDirectory_Delete_ShouldDeleteDirectoryCaseInsensitively() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } + }); - // Act - Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); + // Act + fileSystem.Directory.Delete(XFS.Path(@"c:\BAR"), true); - // Assert - await That(action).Throws(); - } + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); + } - [Test] - public async Task MockDirectory_GetFiles_ShouldFindFilesContainingTwoOrMoreDots() + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockDirectory_Delete_ShouldThrowDirectoryNotFoundException_WhenSpecifiedWithInDifferentCase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string testPath = XFS.Path(@"c:\foo..r\bar.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testPath, new MockFileData(string.Empty) } - }); + { "/bar/foo.txt", new MockFileData("Demo text content") } + }); - // Act - var actualResult = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), XFS.Path(@"foo..r\*")); + // Act + Action action = () => fileSystem.Directory.Delete("/BAR", true); - // Assert - await That(actualResult).IsEquivalentTo(new[] { testPath }); - } + // Assert + await That(action).Throws(); + } - [TestCase("aa\t")] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternHasIllegalCharacters(string searchPattern) + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockDirectory_Delete_ShouldDeleteDirectoryCaseSensitively() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var directoryPath = XFS.Path(@"c:\Foo"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(directoryPath); + { "/bar/foo.txt", new MockFileData("Demo text content") } + }); - // Act - Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); + // Act + fileSystem.Directory.Delete("/bar", true); - // Assert - await That(action).Throws(); - } + // Assert + await That(fileSystem.Directory.Exists("/bar")).IsFalse(); + } - [Test] - public async Task MockDirectory_GetRoot_Returns_Root() + [Test] + public async Task MockDirectory_Delete_ShouldThrowDirectoryNotFoundException() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - string testDir = XFS.Path(@"c:\foo\bar\"); - var fileSystem = new MockFileSystem(new Dictionary - { - { testDir, new MockDirectoryData() } - }); + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") } + }); - await That(fileSystem.Directory.GetDirectoryRoot(XFS.Path(@"C:\foo\bar"))).IsEqualTo(XFS.Path("C:\\")); - } + var ex = await That(() => fileSystem.Directory.Delete(XFS.Path(@"c:\baz"))).Throws(); - [Test] - public async Task MockDirectory_GetLogicalDrives_Returns_LogicalDrives() + await That(ex.Message).IsEqualTo($"'{XFS.Path("c:\\baz")}' does not exist or could not be found."); + } + + [Test] + public async Task MockDirectory_Delete_ShouldThrowIOException() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - {XFS.Path(@"c:\foo\bar\"), new MockDirectoryData()}, - {XFS.Path(@"c:\foo\baz\"), new MockDirectoryData()}, - {XFS.Path(@"d:\bash\"), new MockDirectoryData()}, - }); + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\bar\baz.txt"), new MockFileData("Demo text content") } + }); - var drives = fileSystem.Directory.GetLogicalDrives(); + var ex = await That(() => fileSystem.Directory.Delete(XFS.Path(@"c:\bar"))).Throws(); - if (XFS.IsUnixPlatform()) - { - await That(drives.Length).IsEqualTo(1); - await That(drives.Contains("/")).IsTrue(); - } - else - { - await That(drives.Length).IsEqualTo(2); - await That(drives.Contains(@"C:\")).IsTrue(); - await That(drives.Contains(@"D:\")).IsTrue(); - } - } + await That(ex.Message).IsEqualTo("The directory specified by " + XFS.Path("c:\\bar") + " is read-only, or recursive is false and " + XFS.Path("c:\\bar") + " is not an empty directory."); + } - [Test] - public async Task MockDirectory_GetDirectories_Returns_Child_Directories() + [Test] + public async Task MockDirectory_Delete_ShouldDeleteDirectoryRecursively() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, - }); - - var directories = fileSystem.Directory.GetDirectories(XFS.Path(@"A:\folder1")).ToArray(); + { XFS.Path(@"c:\bar\foo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\bar\bar2\foo.txt"), new MockFileData("Demo text content") } + }); - //Check that it does not returns itself - await That(directories.Contains(XFS.Path(@"A:\folder1"))).IsFalse(); + // Act + fileSystem.DirectoryInfo.New(XFS.Path(@"c:\bar")).Delete(true); - //Check that it correctly returns all child directories - await That(directories.Count()).IsEqualTo(2); - await That(directories.Contains(XFS.Path(@"A:\folder1\folder2"))).IsTrue(); - await That(directories.Contains(XFS.Path(@"A:\folder1\folder4"))).IsTrue(); - } + // Assert + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar"))).IsFalse(); + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\bar\bar2"))).IsFalse(); + } - [Test] - public async Task MockDirectory_GetDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() + [Test] + public async Task MockDirectory_Delete_ShouldThrowIOException_WhenPathIsAFile() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") }, + }); - // Act - var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"C:\Folder\"), "*.foo"); + // Act + Action action = () => fileSystem.Directory.Delete(XFS.Path(@"c:\foo.txt")); - // Assert - await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockDirectory_GetDirectories_RelativeWithNoSubDirectories_ShouldReturnDirectories() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("Folder"); + [Test] + public async Task MockDirectory_GetFileSystemEntries_Returns_Files_And_Directories() + { + string testPath = XFS.Path(@"c:\foo\bar.txt"); + string testDir = XFS.Path(@"c:\foo\bar"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testPath, new MockFileData("Demo text content") }, + { testDir, new MockDirectoryData() } + }); + + var entries = fileSystem.Directory.GetFileSystemEntries(XFS.Path(@"c:\foo")).OrderBy(k => k); + await That(entries.Count()).IsEqualTo(2); + await That(entries.First()).IsEqualTo(testDir); + await That(entries.Last()).IsEqualTo(testPath); + } - // Act - var actualResult = fileSystem.Directory.GetDirectories("Folder"); + [Test] + public async Task MockDirectory_GetFileSystemEntries_ShouldNotReturnSubDirectory_WithSearchOption() + { + string testPath = XFS.Path(@"c:\foo\bar.txt"); + string testDir = XFS.Path(@"c:\foo\bar"); + string testSubDir = XFS.Path(@"c:\foo\bar\baz"); + var fileSystem = new MockFileSystem(new Dictionary + { + { testPath, new MockFileData("Demo text content") }, + { testSubDir, new MockDirectoryData() }, + }); + + var entries = fileSystem.Directory.GetFileSystemEntries(XFS.Path(@"c:\foo"), "*", SearchOption.TopDirectoryOnly).OrderBy(k => k); + await That(entries.Count()).IsEqualTo(2); + await That(entries.First()).IsEqualTo(testDir); + await That(entries.Last()).IsEqualTo(testPath); + } - // Assert - await That(actualResult).IsEmpty(); - } + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowArgumentNullException_IfPathParamIsNull() + { + var fileSystem = new MockFileSystem(new Dictionary()); - [TestCase(@"Folder\SubFolder")] - [TestCase(@"Folder")] - public async Task MockDirectory_GetDirectories_RelativeDirectory_WithoutChildren_ShouldReturnNoChildDirectories(string relativeDirPath) - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(relativeDirPath); + Action action = () => fileSystem.Directory.GetFiles(null); + await That(action).Throws(); + } - // Act - var actualResult = fileSystem.Directory.GetDirectories(relativeDirPath); + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowDirectoryNotFoundException_IfPathDoesNotExists() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Assert - await That(actualResult).IsEmpty(); - } + // Act + Action action = () => fileSystem.Directory.GetFiles(XFS.Path(@"c:\Foo"), "*a.txt"); + + // Assert + await That(action).Throws(); + } - [TestCase(@"Folder\SubFolder")] - [TestCase(@"Folder")] - public async Task MockDirectory_GetDirectories_RelativeDirectory_WithChildren_ShouldReturnChildDirectories(string relativeDirPath) + [Test] + public async Task MockDirectory_GetFiles_Returns_Files() + { + string testPath = XFS.Path(@"c:\foo\bar.txt"); + string testDir = XFS.Path(@"c:\foo\bar\"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var currentDirectory = XFS.Path(@"T:\foo"); - var fileSystem = new MockFileSystem(null, currentDirectory: currentDirectory); - fileSystem.Directory.CreateDirectory(XFS.Path(relativeDirPath)); - fileSystem.Directory.CreateDirectory(XFS.Path(relativeDirPath + @"\child")); + { testPath, new MockFileData("Demo text content") }, + { testDir, new MockDirectoryData() } + }); - // Act - var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(relativeDirPath)); + var entries = fileSystem.Directory.GetFiles(XFS.Path(@"c:\foo")).OrderBy(k => k); + await That(entries.Count()).IsEqualTo(1); + await That(entries.First()).IsEqualTo(testPath); + } - // Assert - await That(actualResult).IsEqualTo(new[] { XFS.Path(relativeDirPath + @"\child") }); - } + [Test] + public async Task MockDirectory_GetFiles_Returns_Files_WithRelativePath() + { + // arrange + var fileSystem = new MockFileSystem(new Dictionary()); - [Test] - public async Task MockDirectory_GetDirectories_AbsoluteWithNoSubDirectories_ShouldReturnDirectories() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("Folder"); + string directory = XFS.Path(@"C:\foo"); - // Act - var fullPath = fileSystem.Path.GetFullPath("Folder"); - var actualResult = fileSystem.Directory.GetDirectories(fullPath); + fileSystem.Directory.SetCurrentDirectory(directory); + fileSystem.AddFile(XFS.Path(@"C:\test.txt"), new MockFileData("Some ASCII text.")); - // Assert - await That(actualResult).IsEmpty(); - } + await That(fileSystem.Directory.GetFiles(XFS.Path(@"..\")).Length).IsEqualTo(1); // Assert with relative path + } - [Test] - public async Task MockDirectory_GetDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentNullException_IfSearchPatternIsNull() + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); - // Act - var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"C:\Folder\"), "*.foo", SearchOption.AllDirectories); + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, null); - // Assert - await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo"), XFS.Path(@"C:\Folder\.foo\.foo") }); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockDirectory_GetDirectories_ShouldThrowWhenPathIsNotMocked() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - }); + [Test] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternEndsWithTwoDots() + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); - // Act - Action action = () => fileSystem.Directory.GetDirectories(XFS.Path(@"c:\d")); + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, "*a.."); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockDirectory_EnumerateDirectories_Returns_Child_Directories() - { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, - }); + [TestCase(@"..\")] + [TestCase(@"aaa\vv..\")] + [TestCase(@"a..\b")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternContainsTwoDotsFollowedByOneBackslash(string searchPattern) + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); - var directories = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"A:\folder1")).ToArray(); + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); - //Check that it does not returns itself - await That(directories.Contains(XFS.Path(@"A:\folder1"))).IsFalse(); + // Assert + await That(action).Throws(); + } - //Check that it correctly returns all child directories - await That(directories.Count()).IsEqualTo(2); - await That(directories.Contains(XFS.Path(@"A:\folder1\folder2"))).IsTrue(); - await That(directories.Contains(XFS.Path(@"A:\folder1\folder4"))).IsTrue(); - } + [TestCase(@"a../b")] + [TestCase(@"../")] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternContainsTwoDotsFollowedByOneSlash(string searchPattern) + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); - [Test] - public async Task MockDirectory_EnumerateDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_GetFiles_ShouldFindFilesContainingTwoOrMoreDots() + { + // Arrange + string testPath = XFS.Path(@"c:\foo..r\bar.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + { testPath, new MockFileData(string.Empty) } + }); - // Act - var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo"); + // Act + var actualResult = fileSystem.Directory.GetFiles(XFS.Path(@"c:\"), XFS.Path(@"foo..r\*")); - // Assert - await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); - } + // Assert + await That(actualResult).IsEquivalentTo(new[] { testPath }); + } -#if FEATURE_ENUMERATION_OPTIONS - [Test] - public async Task MockDirectory_EnumerateDirectories_WithEnumerationOptionsTopDirectories_ShouldOnlyReturnTopDirectories() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + [TestCase("aa\t")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternHasIllegalCharacters(string searchPattern) + { + // Arrange + var directoryPath = XFS.Path(@"c:\Foo"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(directoryPath); - var enumerationOptions = new EnumerationOptions - { - RecurseSubdirectories = false - }; + // Act + Action action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern); - // Act - var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo", enumerationOptions); + // Assert + await That(action).Throws(); + } - // Assert - await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); - } -#endif - [Test] - public async Task MockDirectory_EnumerateDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() + [Test] + public async Task MockDirectory_GetRoot_Returns_Root() + { + string testDir = XFS.Path(@"c:\foo\bar\"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); - fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); - fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + { testDir, new MockDirectoryData() } + }); - // Act - var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo", SearchOption.AllDirectories); - - // Assert - await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo"), XFS.Path(@"C:\Folder\.foo\.foo") }); - } + await That(fileSystem.Directory.GetDirectoryRoot(XFS.Path(@"C:\foo\bar"))).IsEqualTo(XFS.Path("C:\\")); + } - [Test] - public async Task MockDirectory_EnumerateDirectories_ShouldThrowWhenPathIsNotMocked() + [Test] + public async Task MockDirectory_GetLogicalDrives_Returns_LogicalDrives() + { + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, - }); + {XFS.Path(@"c:\foo\bar\"), new MockDirectoryData()}, + {XFS.Path(@"c:\foo\baz\"), new MockDirectoryData()}, + {XFS.Path(@"d:\bash\"), new MockDirectoryData()}, + }); - // Act - Action action = () => fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\d")); + var drives = fileSystem.Directory.GetLogicalDrives(); - // Assert - await That(action).Throws(); - } - - [TestCaseSource(nameof(GetPrefixTestPaths))] - public async Task MockDirectory_EnumerateDirectories_ShouldReturnPathsPrefixedWithQueryPath( - string queryPath, string expectedPath) + if (XFS.IsUnixPlatform()) { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory("Folder/SubFolder"); - - var actualResult = fileSystem.Directory.EnumerateDirectories(queryPath); - - await That(actualResult).IsEqualTo(new[] { expectedPath }); + await That(drives.Length).IsEqualTo(1); + await That(drives.Contains("/")).IsTrue(); } - - private static IEnumerable GetPrefixTestPaths() + else { - var sep = Path.DirectorySeparatorChar; - yield return new object[] { "Folder", $"Folder{sep}SubFolder" }; - yield return new object[] { $"Folder{sep}", $"Folder{sep}SubFolder" }; - yield return new object[] { $"Folder{sep}..{sep}.{sep}Folder", $"Folder{sep}..{sep}.{sep}Folder{sep}SubFolder" }; + await That(drives.Length).IsEqualTo(2); + await That(drives.Contains(@"C:\")).IsTrue(); + await That(drives.Contains(@"D:\")).IsTrue(); } + } - public static IEnumerable GetPathsForMoving() + [Test] + public async Task MockDirectory_GetDirectories_Returns_Child_Directories() + { + var fileSystem = new MockFileSystem(new Dictionary { - yield return new object[] { XFS.Path(@"a:\folder1\"), XFS.Path(@"A:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; - yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"A:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; - yield return new object[] { XFS.Path(@"a:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; - yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; - yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"Folder2\file2.txt") }; - yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"Folder2\fiLe2.txt") }; - yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("folder444\\file.txt"), XFS.Path(@"Folder2\fiLe2.txt") }; - } + { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, + }); - [Test] - public async Task Move_DirectoryExistsWithDifferentCase_DirectorySuccessfullyMoved() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\OLD_LOCATION\Data")); - fileSystem.AddFile(XFS.Path(@"C:\old_location\Data\someFile.txt"), new MockFileData("abc")); + var directories = fileSystem.Directory.GetDirectories(XFS.Path(@"A:\folder1")).ToArray(); - // Act - fileSystem.Directory.Move(XFS.Path(@"C:\old_location"), XFS.Path(@"C:\NewLocation\")); + //Check that it does not returns itself + await That(directories.Contains(XFS.Path(@"A:\folder1"))).IsFalse(); - // Assert - await That(fileSystem.File.Exists(XFS.Path(@"C:\NewLocation\Data\someFile.txt"))).IsTrue(); - } + //Check that it correctly returns all child directories + await That(directories.Count()).IsEqualTo(2); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder2"))).IsTrue(); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder4"))).IsTrue(); + } - [TestCaseSource(nameof(GetPathsForMoving))] - public async Task MockDirectory_Move_ShouldMoveDirectories(string sourceDirName, string destDirName, string filePathOne, string filePathTwo) - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, - { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, - }); + [Test] + public async Task MockDirectory_GetDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"C:\Folder\"), "*.foo"); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); + } - // Act - fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + [Test] + public async Task MockDirectory_GetDirectories_RelativeWithNoSubDirectories_ShouldReturnDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("Folder"); - // Assert - await That(fileSystem.Directory.Exists(sourceDirName)).IsFalse(); - await That(fileSystem.File.Exists(XFS.Path(destDirName + filePathOne))).IsTrue(); - await That(fileSystem.File.Exists(XFS.Path(destDirName + filePathTwo))).IsTrue(); - } + // Act + var actualResult = fileSystem.Directory.GetDirectories("Folder"); - [Test] - public async Task MockDirectory_Move_ShouldMoveFiles() - { - string sourceFilePath = XFS.Path(@"c:\demo.txt"); - string sourceFileContent = "this is some content"; + // Assert + await That(actualResult).IsEmpty(); + } - var fileSystem = new MockFileSystem(new Dictionary - { - { sourceFilePath, new MockFileData(sourceFileContent) } - }); + [TestCase(@"Folder\SubFolder")] + [TestCase(@"Folder")] + public async Task MockDirectory_GetDirectories_RelativeDirectory_WithoutChildren_ShouldReturnNoChildDirectories(string relativeDirPath) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(relativeDirPath); - string destFilePath = XFS.Path(@"c:\demo1.txt"); + // Act + var actualResult = fileSystem.Directory.GetDirectories(relativeDirPath); - fileSystem.Directory.Move(sourceFilePath, destFilePath); + // Assert + await That(actualResult).IsEmpty(); + } - await That(fileSystem.FileExists(destFilePath)).IsTrue(); - await That(fileSystem.FileExists(sourceFilePath)).IsFalse(); - await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); - } + [TestCase(@"Folder\SubFolder")] + [TestCase(@"Folder")] + public async Task MockDirectory_GetDirectories_RelativeDirectory_WithChildren_ShouldReturnChildDirectories(string relativeDirPath) + { + // Arrange + var currentDirectory = XFS.Path(@"T:\foo"); + var fileSystem = new MockFileSystem(null, currentDirectory: currentDirectory); + fileSystem.Directory.CreateDirectory(XFS.Path(relativeDirPath)); + fileSystem.Directory.CreateDirectory(XFS.Path(relativeDirPath + @"\child")); - [Test] - public async Task MockDirectory_Move_ShouldMoveDirectoryAttributes() + // Act + var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(relativeDirPath)); + + // Assert + await That(actualResult).IsEqualTo(new[] { XFS.Path(relativeDirPath + @"\child") }); + } + + [Test] + public async Task MockDirectory_GetDirectories_AbsoluteWithNoSubDirectories_ShouldReturnDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("Folder"); + + // Act + var fullPath = fileSystem.Path.GetFullPath("Folder"); + var actualResult = fileSystem.Directory.GetDirectories(fullPath); + + // Assert + await That(actualResult).IsEmpty(); + } + + [Test] + public async Task MockDirectory_GetDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"C:\Folder\"), "*.foo", SearchOption.AllDirectories); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo"), XFS.Path(@"C:\Folder\.foo\.foo") }); + } + + [Test] + public async Task MockDirectory_GetDirectories_ShouldThrowWhenPathIsNotMocked() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + }); + + // Act + Action action = () => fileSystem.Directory.GetDirectories(XFS.Path(@"c:\d")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDirectory_EnumerateDirectories_Returns_Child_Directories() + { + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var sourceDirName = XFS.Path(@"a:\folder1\"); - var destDirName = XFS.Path(@"a:\folder2\"); - const string filePathOne = "file1.txt"; - const string filePathTwo = "file2.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, - { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, - }); + { XFS.Path(@"A:\folder1\folder2\folder3\file.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"A:\folder1\folder4\file2.txt"), new MockFileData("Demo text content 2") }, + }); - var sourceDirectoryInfo = fileSystem.DirectoryInfo.New(sourceDirName); - sourceDirectoryInfo.Attributes |= FileAttributes.System; + var directories = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"A:\folder1")).ToArray(); - // Act - fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + //Check that it does not returns itself + await That(directories.Contains(XFS.Path(@"A:\folder1"))).IsFalse(); - // Assert - var destDirectoryInfo = fileSystem.DirectoryInfo.New(destDirName); - await That(destDirectoryInfo.Attributes.HasFlag(FileAttributes.System)).IsTrue(); - } + //Check that it correctly returns all child directories + await That(directories.Count()).IsEqualTo(2); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder2"))).IsTrue(); + await That(directories.Contains(XFS.Path(@"A:\folder1\folder4"))).IsTrue(); + } - [Test] - public async Task MockDirectory_Move_ShouldMoveDirectoryWithReadOnlySubDirectory() + [Test] + public async Task MockDirectory_EnumerateDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo"); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); + } + +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectory_EnumerateDirectories_WithEnumerationOptionsTopDirectories_ShouldOnlyReturnTopDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + var enumerationOptions = new EnumerationOptions { - // Arrange - var sourceDirName = XFS.Path(@"a:\folder1\"); - var sourceSubDirName = XFS.Path(@"a:\folder1\sub\"); + RecurseSubdirectories = false + }; - var destDirName = XFS.Path(@"a:\folder2\"); - var destSubDirName = XFS.Path(@"a:\folder2\sub\"); + // Act + var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo", enumerationOptions); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(sourceSubDirName); + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo") }); + } +#endif + [Test] + public async Task MockDirectory_EnumerateDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\foo.foo")); + fileSystem.AddDirectory(XFS.Path(@"C:\Folder\.foo\.foo")); + fileSystem.AddFile(XFS.Path(@"C:\Folder\.foo\bar"), new MockFileData(string.Empty)); + + // Act + var actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"C:\Folder\"), "*.foo", SearchOption.AllDirectories); + + // Assert + await That(actualResult).IsEquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo"), XFS.Path(@"C:\Folder\foo.foo"), XFS.Path(@"C:\Folder\.foo\.foo") }); + } - var subDirectoryInfo = fileSystem.DirectoryInfo.New(sourceSubDirName); - subDirectoryInfo.Attributes |= FileAttributes.ReadOnly; + [Test] + public async Task MockDirectory_EnumerateDirectories_ShouldThrowWhenPathIsNotMocked() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(@"c:\a.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b.gif"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\c.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\b.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\a\c.gif"), new MockFileData("Demo text content") }, + }); + + // Act + Action action = () => fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\d")); + + // Assert + await That(action).Throws(); + } + + [TestCaseSource(nameof(GetPrefixTestPaths))] + public async Task MockDirectory_EnumerateDirectories_ShouldReturnPathsPrefixedWithQueryPath( + string queryPath, string expectedPath) + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory("Folder/SubFolder"); + + var actualResult = fileSystem.Directory.EnumerateDirectories(queryPath); + + await That(actualResult).IsEqualTo(new[] { expectedPath }); + } + + private static IEnumerable GetPrefixTestPaths() + { + var sep = Path.DirectorySeparatorChar; + yield return new object[] { "Folder", $"Folder{sep}SubFolder" }; + yield return new object[] { $"Folder{sep}", $"Folder{sep}SubFolder" }; + yield return new object[] { $"Folder{sep}..{sep}.{sep}Folder", $"Folder{sep}..{sep}.{sep}Folder{sep}SubFolder" }; + } - var sourceDirectoryInfo = fileSystem.DirectoryInfo.New(sourceDirName); + public static IEnumerable GetPathsForMoving() + { + yield return new object[] { XFS.Path(@"a:\folder1\"), XFS.Path(@"A:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"A:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"a:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"Folder2\file2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("file.txt"), XFS.Path(@"Folder2\fiLe2.txt") }; + yield return new object[] { XFS.Path(@"A:\folder1\"), XFS.Path(@"a:\folder3\"), XFS.Path("folder444\\file.txt"), XFS.Path(@"Folder2\fiLe2.txt") }; + } - // Act - fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + [Test] + public async Task Move_DirectoryExistsWithDifferentCase_DirectorySuccessfullyMoved() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\OLD_LOCATION\Data")); + fileSystem.AddFile(XFS.Path(@"C:\old_location\Data\someFile.txt"), new MockFileData("abc")); - // Assert - await That(fileSystem.Directory.Exists(sourceSubDirName)).IsFalse(); - await That(fileSystem.FileExists(destSubDirName)).IsTrue(); - } + // Act + fileSystem.Directory.Move(XFS.Path(@"C:\old_location"), XFS.Path(@"C:\NewLocation\")); - [Test] - public async Task MockDirectory_Move_ShouldOnlyMoveDirAndFilesWithinDir() + // Assert + await That(fileSystem.File.Exists(XFS.Path(@"C:\NewLocation\Data\someFile.txt"))).IsTrue(); + } + + [TestCaseSource(nameof(GetPathsForMoving))] + public async Task MockDirectory_Move_ShouldMoveDirectories(string sourceDirName, string destDirName, string filePathOne, string filePathTwo) + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - {XFS.Path(@"c:\source\dummy"), new MockDirectoryData()}, - {XFS.Path(@"c:\source\dummy\content.txt"), new MockFileData(new byte[] {0})}, - {XFS.Path(@"c:\source\dummy.txt"), new MockFileData(new byte[] {0})}, - {XFS.Path(@"c:\source\dummy2"), new MockDirectoryData()}, - {XFS.Path(@"c:\destination"), new MockDirectoryData()}, - }); + { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, + { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, + }); - // Act - fileSystem.Directory.Move(XFS.Path(@"c:\source\dummy"), XFS.Path(@"c:\destination\dummy")); + // Act + fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); - // Assert - await That(fileSystem.FileExists(XFS.Path(@"c:\source\dummy.txt"))).IsTrue(); - await That(fileSystem.Directory.Exists(XFS.Path(@"c:\source\dummy2"))).IsTrue(); - } + // Assert + await That(fileSystem.Directory.Exists(sourceDirName)).IsFalse(); + await That(fileSystem.File.Exists(XFS.Path(destDirName + filePathOne))).IsTrue(); + await That(fileSystem.File.Exists(XFS.Path(destDirName + filePathTwo))).IsTrue(); + } - [Test] - public async Task MockDirectory_GetCurrentDirectory_ShouldReturnValueFromFileSystemConstructor() + [Test] + public async Task MockDirectory_Move_ShouldMoveFiles() + { + string sourceFilePath = XFS.Path(@"c:\demo.txt"); + string sourceFileContent = "this is some content"; + + var fileSystem = new MockFileSystem(new Dictionary { - string directory = XFS.Path(@"D:\folder1\folder2"); - var fileSystem = new MockFileSystem(new Dictionary(), directory); + { sourceFilePath, new MockFileData(sourceFileContent) } + }); - var actual = fileSystem.Directory.GetCurrentDirectory(); + string destFilePath = XFS.Path(@"c:\demo1.txt"); - await That(actual).IsEqualTo(directory); - } + fileSystem.Directory.Move(sourceFilePath, destFilePath); - [Test] - public async Task MockDirectory_GetCurrentDirectory_ShouldReturnDefaultPathWhenNotSet() - { - string directory = XFS.Path(@"C:\"); + await That(fileSystem.FileExists(destFilePath)).IsTrue(); + await That(fileSystem.FileExists(sourceFilePath)).IsFalse(); + await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); + } - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockDirectory_Move_ShouldMoveDirectoryAttributes() + { + // Arrange + var sourceDirName = XFS.Path(@"a:\folder1\"); + var destDirName = XFS.Path(@"a:\folder2\"); + const string filePathOne = "file1.txt"; + const string filePathTwo = "file2.txt"; + var fileSystem = new MockFileSystem(new Dictionary + { + { XFS.Path(sourceDirName + filePathOne) , new MockFileData("aaa") }, + { XFS.Path(sourceDirName + filePathTwo) , new MockFileData("bbb") }, + }); + + var sourceDirectoryInfo = fileSystem.DirectoryInfo.New(sourceDirName); + sourceDirectoryInfo.Attributes |= FileAttributes.System; + + // Act + fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + + // Assert + var destDirectoryInfo = fileSystem.DirectoryInfo.New(destDirName); + await That(destDirectoryInfo.Attributes.HasFlag(FileAttributes.System)).IsTrue(); + } - var actual = fileSystem.Directory.GetCurrentDirectory(); + [Test] + public async Task MockDirectory_Move_ShouldMoveDirectoryWithReadOnlySubDirectory() + { + // Arrange + var sourceDirName = XFS.Path(@"a:\folder1\"); + var sourceSubDirName = XFS.Path(@"a:\folder1\sub\"); - await That(actual).IsEqualTo(directory); - } + var destDirName = XFS.Path(@"a:\folder2\"); + var destSubDirName = XFS.Path(@"a:\folder2\sub\"); - [Test] - public async Task MockDirectory_SetCurrentDirectory_ShouldChangeCurrentDirectory() - { - string directory = XFS.Path(@"D:\folder1\folder2"); - var fileSystem = new MockFileSystem(); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(sourceSubDirName); + + var subDirectoryInfo = fileSystem.DirectoryInfo.New(sourceSubDirName); + subDirectoryInfo.Attributes |= FileAttributes.ReadOnly; + + var sourceDirectoryInfo = fileSystem.DirectoryInfo.New(sourceDirName); + + // Act + fileSystem.DirectoryInfo.New(sourceDirName).MoveTo(destDirName); + + // Assert + await That(fileSystem.Directory.Exists(sourceSubDirName)).IsFalse(); + await That(fileSystem.FileExists(destSubDirName)).IsTrue(); + } + + [Test] + public async Task MockDirectory_Move_ShouldOnlyMoveDirAndFilesWithinDir() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary + { + {XFS.Path(@"c:\source\dummy"), new MockDirectoryData()}, + {XFS.Path(@"c:\source\dummy\content.txt"), new MockFileData(new byte[] {0})}, + {XFS.Path(@"c:\source\dummy.txt"), new MockFileData(new byte[] {0})}, + {XFS.Path(@"c:\source\dummy2"), new MockDirectoryData()}, + {XFS.Path(@"c:\destination"), new MockDirectoryData()}, + }); + + // Act + fileSystem.Directory.Move(XFS.Path(@"c:\source\dummy"), XFS.Path(@"c:\destination\dummy")); + + // Assert + await That(fileSystem.FileExists(XFS.Path(@"c:\source\dummy.txt"))).IsTrue(); + await That(fileSystem.Directory.Exists(XFS.Path(@"c:\source\dummy2"))).IsTrue(); + } - // Precondition - await That(fileSystem.Directory.GetCurrentDirectory()).IsNotEqualTo(directory); + [Test] + public async Task MockDirectory_GetCurrentDirectory_ShouldReturnValueFromFileSystemConstructor() + { + string directory = XFS.Path(@"D:\folder1\folder2"); + var fileSystem = new MockFileSystem(new Dictionary(), directory); - fileSystem.Directory.SetCurrentDirectory(directory); + var actual = fileSystem.Directory.GetCurrentDirectory(); - await That(fileSystem.Directory.GetCurrentDirectory()).IsEqualTo(directory); - } + await That(actual).IsEqualTo(directory); + } - [Test] - public async Task MockDirectory_SetCurrentDirectory_WithRelativePath_ShouldUseFullPath() - { - var fileSystem = new MockFileSystem(); - fileSystem.Directory.SetCurrentDirectory("."); + [Test] + public async Task MockDirectory_GetCurrentDirectory_ShouldReturnDefaultPathWhenNotSet() + { + string directory = XFS.Path(@"C:\"); - var result = fileSystem.Directory.GetCurrentDirectory(); + var fileSystem = new MockFileSystem(); - await That(fileSystem.Path.IsPathRooted(result)).IsTrue(); - } + var actual = fileSystem.Directory.GetCurrentDirectory(); - [Test] - public async Task MockDirectory_GetParent_ShouldThrowArgumentNullExceptionIfPathIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); + await That(actual).IsEqualTo(directory); + } - // Act - Action act = () => fileSystem.Directory.GetParent(null); + [Test] + public async Task MockDirectory_SetCurrentDirectory_ShouldChangeCurrentDirectory() + { + string directory = XFS.Path(@"D:\folder1\folder2"); + var fileSystem = new MockFileSystem(); - // Assert - await That(act).Throws(); - } + // Precondition + await That(fileSystem.Directory.GetCurrentDirectory()).IsNotEqualTo(directory); - [Test] - public async Task MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathIsEmpty() - { - // Arrange - var fileSystem = new MockFileSystem(); + fileSystem.Directory.SetCurrentDirectory(directory); - // Act - Action act = () => fileSystem.Directory.GetParent(string.Empty); + await That(fileSystem.Directory.GetCurrentDirectory()).IsEqualTo(directory); + } - // Assert - await That(act).Throws(); - } + [Test] + public async Task MockDirectory_SetCurrentDirectory_WithRelativePath_ShouldUseFullPath() + { + var fileSystem = new MockFileSystem(); + fileSystem.Directory.SetCurrentDirectory("."); - [Test] - public async Task MockDirectory_GetParent_ShouldReturnADirectoryInfoIfPathDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); + var result = fileSystem.Directory.GetCurrentDirectory(); - // Act - var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\directory\does\not\exist")); + await That(fileSystem.Path.IsPathRooted(result)).IsTrue(); + } - // Assert - await That(actualResult).IsNotNull(); - } + [Test] + public async Task MockDirectory_GetParent_ShouldThrowArgumentNullExceptionIfPathIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathHasIllegalCharacters() - { - // Arrange - var fileSystem = new MockFileSystem(); + // Act + Action act = () => fileSystem.Directory.GetParent(null); - // Act - Action act = () => fileSystem.Directory.GetParent(XFS.Path("c:\\director\ty\\has\\illegal\\character")); + // Assert + await That(act).Throws(); + } - // Assert - await That(act).Throws(); - } + [Test] + public async Task MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); - [Test] - public async Task MockDirectory_GetParent_ShouldReturnNullIfPathIsRoot() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\")); + // Act + Action act = () => fileSystem.Directory.GetParent(string.Empty); - // Act - var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\")); + // Assert + await That(act).Throws(); + } - // Assert - await That(actualResult).IsNull(); - } + [Test] + public async Task MockDirectory_GetParent_ShouldReturnADirectoryInfoIfPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); - [Test] - [UnixOnly(UnixSpecifics.SlashRoot)] - public async Task MockDirectory_GetParent_ShouldReturnRootIfDirectoryIsInRoot() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory("/bar"); + // Act + var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\directory\does\not\exist")); - // Act - var parent = fileSystem.Directory.GetParent("/bar"); + // Assert + await That(actualResult).IsNotNull(); + } - // Assert - await That(parent.FullName).IsEqualTo("/"); - } + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathHasIllegalCharacters() + { + // Arrange + var fileSystem = new MockFileSystem(); - public static IEnumerable MockDirectory_GetParent_Cases - { - get - { - yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"c:\") }; - yield return new[] { XFS.Path(@"c:\a\b\c\d"), XFS.Path(@"c:\a\b\c") }; - yield return new[] { XFS.Path(@"c:\a\b\c\d\"), XFS.Path(@"c:\a\b\c") }; - } - } + // Act + Action act = () => fileSystem.Directory.GetParent(XFS.Path("c:\\director\ty\\has\\illegal\\character")); - public async Task MockDirectory_GetParent_ShouldReturnTheParentWithoutTrailingDirectorySeparatorChar(string path, string expectedResult) - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(path); + // Assert + await That(act).Throws(); + } - // Act - var actualResult = fileSystem.Directory.GetParent(path); + [Test] + public async Task MockDirectory_GetParent_ShouldReturnNullIfPathIsRoot() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\")); - // Assert - await That(actualResult.FullName).IsEqualTo(expectedResult); - } + // Act + var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\")); - [Test] - public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfBothPathAreIdentical() - { - // Arrange - string path = XFS.Path(@"c:\a"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(path); + // Assert + await That(actualResult).IsNull(); + } - // Act - Action action = () => fileSystem.Directory.Move(path, path); + [Test] + [UnixOnly(UnixSpecifics.SlashRoot)] + public async Task MockDirectory_GetParent_ShouldReturnRootIfDirectoryIsInRoot() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory("/bar"); - // Assert - await That(action, "Source and destination path must be different.").Throws(); - } + // Act + var parent = fileSystem.Directory.GetParent("/bar"); - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfDirectoriesAreOnDifferentVolumes() + // Assert + await That(parent.FullName).IsEqualTo("/"); + } + + public static IEnumerable MockDirectory_GetParent_Cases + { + get { - // Arrange - string sourcePath = XFS.Path(@"c:\a"); - string destPath = XFS.Path(@"d:\v"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(sourcePath); + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"c:\") }; + yield return new[] { XFS.Path(@"c:\a\b\c\d"), XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\b\c\d\"), XFS.Path(@"c:\a\b\c") }; + } + } - // Act - Action action = () => fileSystem.Directory.Move(sourcePath, destPath); + public async Task MockDirectory_GetParent_ShouldReturnTheParentWithoutTrailingDirectorySeparatorChar(string path, string expectedResult) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(path); - // Assert - await That(action, "Source and destination path must have identical roots. Move will not work across volumes.").Throws(); - } + // Act + var actualResult = fileSystem.Directory.GetParent(path); - [Test] - public async Task MockDirectory_Move_ShouldThrowADirectoryNotFoundExceptionIfDestinationDirectoryDoesNotExist() - { - // Arrange - string sourcePath = XFS.Path(@"c:\a"); - string destPath = XFS.Path(@"c:\b"); - var fileSystem = new MockFileSystem(); + // Assert + await That(actualResult.FullName).IsEqualTo(expectedResult); + } - // Act - Action action = () => fileSystem.Directory.Move(sourcePath, destPath); + [Test] + public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfBothPathAreIdentical() + { + // Arrange + string path = XFS.Path(@"c:\a"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(path); - // Assert - await That(action, "Could not find a part of the path 'c:\a'.").Throws(); - } + // Act + Action action = () => fileSystem.Directory.Move(path, path); - [Test] - public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfDestinationDirectoryExists() - { - // Arrange - string sourcePath = XFS.Path(@"c:\a"); - string destPath = XFS.Path(@"c:\b"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(sourcePath); - fileSystem.AddDirectory(destPath); + // Assert + await That(action, "Source and destination path must be different.").Throws(); + } - // Act - Action action = () => fileSystem.Directory.Move(sourcePath, destPath); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfDirectoriesAreOnDifferentVolumes() + { + // Arrange + string sourcePath = XFS.Path(@"c:\a"); + string destPath = XFS.Path(@"d:\v"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(sourcePath); - // Assert - await That(action, "Cannot create 'c:\b\' because a file or directory with the same name already exists.'").Throws(); - } + // Act + Action action = () => fileSystem.Directory.Move(sourcePath, destPath); - [Test] - public async Task MockDirectory_EnumerateFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - IEnumerable expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif"), - XFS.Path(@"c:\a\a\d") - }; + // Assert + await That(action, "Source and destination path must have identical roots. Move will not work across volumes.").Throws(); + } - // Act - var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + [Test] + public async Task MockDirectory_Move_ShouldThrowADirectoryNotFoundExceptionIfDestinationDirectoryDoesNotExist() + { + // Arrange + string sourcePath = XFS.Path(@"c:\a"); + string destPath = XFS.Path(@"c:\b"); + var fileSystem = new MockFileSystem(); - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + // Act + Action action = () => fileSystem.Directory.Move(sourcePath, destPath); -#if FEATURE_ENUMERATION_OPTIONS - [Test] - public async Task MockDirectory_EnumerateFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndEnumerationOptionsIsAllDirectories() - { - // Arrange - var fileSystem = SetupFileSystem(); - IEnumerable expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif"), - XFS.Path(@"c:\a\a\d") - }; + // Assert + await That(action, "Could not find a part of the path 'c:\a'.").Throws(); + } - var enumerationOptions = new EnumerationOptions - { - RecurseSubdirectories = true - }; + [Test] + public async Task MockDirectory_Move_ShouldThrowAnIOExceptionIfDestinationDirectoryExists() + { + // Arrange + string sourcePath = XFS.Path(@"c:\a"); + string destPath = XFS.Path(@"c:\b"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(sourcePath); + fileSystem.AddDirectory(destPath); + + // Act + Action action = () => fileSystem.Directory.Move(sourcePath, destPath); + + // Assert + await That(action, "Cannot create 'c:\b\' because a file or directory with the same name already exists.'").Throws(); + } - // Act - var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\a"), "*", enumerationOptions); + [Test] + public async Task MockDirectory_EnumerateFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectory_EnumerateFiles_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndEnumerationOptionsIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d") + }; + + var enumerationOptions = new EnumerationOptions + { + RecurseSubdirectories = true + }; + + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\a"), "*", enumerationOptions); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } #endif - [Test] - public async Task MockDirectory_EnumerateFiles_ShouldFilterByExtensionBasedSearchPattern() + [Test] + public async Task MockDirectory_EnumerateFiles_ShouldFilterByExtensionBasedSearchPattern() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; - // Act - var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_EnumerateFiles_WhenFilterIsUnRooted_ShouldFindFilesInCurrentDirectory() + [Test] + public async Task MockDirectory_EnumerateFiles_WhenFilterIsUnRooted_ShouldFindFilesInCurrentDirectory() + { + // Arrange + var someContent = new MockFileData(String.Empty); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var someContent = new MockFileData(String.Empty); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), someContent }, - { XFS.Path(@"c:\a\a.txt"), someContent }, - { XFS.Path(@"c:\a\b\b.txt"), someContent }, - { XFS.Path(@"c:\a\c\c.txt"), someContent }, - }); - - var expected = new[] - { - XFS.Path(@"c:\a\b\b.txt"), - }; - - fileSystem.Directory.SetCurrentDirectory(XFS.Path(@"c:\a")); - - // Act - var result = fileSystem.Directory.EnumerateFiles(XFS.Path("b")); - - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + { XFS.Path(@"c:\a.txt"), someContent }, + { XFS.Path(@"c:\a\a.txt"), someContent }, + { XFS.Path(@"c:\a\b\b.txt"), someContent }, + { XFS.Path(@"c:\a\c\c.txt"), someContent }, + }); - [Test] - public async Task MockDirectory_EnumerateFiles_WhenFilterIsUnRooted_ShouldNotFindFilesInPathOutsideCurrentDirectory() + var expected = new[] { - // Arrange - var someContent = new MockFileData(String.Empty); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), someContent }, - { XFS.Path(@"c:\a\b\b.txt"), someContent }, - { XFS.Path(@"c:\c\b\b.txt"), someContent }, - }); - - var expected = new[] - { - XFS.Path(@"c:\a\b\b.txt"), - }; + XFS.Path(@"c:\a\b\b.txt"), + }; - fileSystem.Directory.SetCurrentDirectory(XFS.Path(@"c:\a")); + fileSystem.Directory.SetCurrentDirectory(XFS.Path(@"c:\a")); - // Act - var result = fileSystem.Directory.EnumerateFiles(XFS.Path("b")); + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path("b")); - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - [Test] - public async Task MockDirectory_EnumerateFileSystemEntries_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() + [Test] + public async Task MockDirectory_EnumerateFiles_WhenFilterIsUnRooted_ShouldNotFindFilesInPathOutsideCurrentDirectory() + { + // Arrange + var someContent = new MockFileData(String.Empty); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = SetupFileSystem(); - IEnumerable expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif"), - XFS.Path(@"c:\a\a\d"), - XFS.Path(@"c:\a\a") - }; + { XFS.Path(@"c:\a.txt"), someContent }, + { XFS.Path(@"c:\a\b\b.txt"), someContent }, + { XFS.Path(@"c:\c\b\b.txt"), someContent }, + }); - // Act - var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + var expected = new[] + { + XFS.Path(@"c:\a\b\b.txt"), + }; - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + fileSystem.Directory.SetCurrentDirectory(XFS.Path(@"c:\a")); - [Test] - public async Task MockDirectory_EnumerateFileSystemEntries_ShouldFilterByExtensionBasedSearchPattern() - { - // Arrange - var fileSystem = SetupFileSystem(); - var expected = new[] - { - XFS.Path(@"c:\a.gif"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\a\c.gif") - }; + // Act + var result = fileSystem.Directory.EnumerateFiles(XFS.Path("b")); - // Act - var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } + [Test] + public async Task MockDirectory_EnumerateFileSystemEntries_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndSearchOptionIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d"), + XFS.Path(@"c:\a\a") + }; + + // Act + var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\a"), "*", SearchOption.AllDirectories); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } -#if FEATURE_ENUMERATION_OPTIONS - [Test] - public async Task MockDirectory_EnumerateFileSystemEntries_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndEnumerationOptionsIsAllDirectories() + [Test] + public async Task MockDirectory_EnumerateFileSystemEntries_ShouldFilterByExtensionBasedSearchPattern() + { + // Arrange + var fileSystem = SetupFileSystem(); + var expected = new[] { - // Arrange - var fileSystem = SetupFileSystem(); - IEnumerable expected = new[] - { - XFS.Path(@"c:\a\a.txt"), - XFS.Path(@"c:\a\b.gif"), - XFS.Path(@"c:\a\c.txt"), - XFS.Path(@"c:\a\d"), - XFS.Path(@"c:\a\a\a.txt"), - XFS.Path(@"c:\a\a\b.txt"), - XFS.Path(@"c:\a\a\c.gif"), - XFS.Path(@"c:\a\a\d"), - XFS.Path(@"c:\a\a") - }; + XFS.Path(@"c:\a.gif"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\a\c.gif") + }; - var enumerationOptions = new EnumerationOptions - { - RecurseSubdirectories = true - }; + // Act + var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\"), "*.gif", SearchOption.AllDirectories); - // Act - var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\a"), "*", enumerationOptions); + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } - // Assert - await That(result).IsEqualTo(expected).InAnyOrder(); - } +#if FEATURE_ENUMERATION_OPTIONS + [Test] + public async Task MockDirectory_EnumerateFileSystemEntries_ShouldReturnAllFilesBelowPathWhenPatternIsWildcardAndEnumerationOptionsIsAllDirectories() + { + // Arrange + var fileSystem = SetupFileSystem(); + IEnumerable expected = new[] + { + XFS.Path(@"c:\a\a.txt"), + XFS.Path(@"c:\a\b.gif"), + XFS.Path(@"c:\a\c.txt"), + XFS.Path(@"c:\a\d"), + XFS.Path(@"c:\a\a\a.txt"), + XFS.Path(@"c:\a\a\b.txt"), + XFS.Path(@"c:\a\a\c.gif"), + XFS.Path(@"c:\a\a\d"), + XFS.Path(@"c:\a\a") + }; + + var enumerationOptions = new EnumerationOptions + { + RecurseSubdirectories = true + }; + + // Act + var result = fileSystem.Directory.EnumerateFileSystemEntries(XFS.Path(@"c:\a"), "*", enumerationOptions); + + // Assert + await That(result).IsEqualTo(expected).InAnyOrder(); + } #endif - [Test] - public async Task MockDirectory_GetAccessControl_ShouldThrowExceptionOnDirectoryNotFound() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockDirectory_GetAccessControl_ShouldThrowExceptionOnDirectoryNotFound() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act + // Act #pragma warning disable CA1416 - await That(() => fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo"))).Throws(); + await That(() => fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo"))).Throws(); #pragma warning restore CA1416 - } + } - [Test] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - [SupportedOSPlatform("windows")] - public async Task MockDirectory_GetAccessControl_ShouldReturnNewDirectorySecurity() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")); + [Test] + [WindowsOnly(WindowsSpecifics.AccessControlLists)] + [SupportedOSPlatform("windows")] + public async Task MockDirectory_GetAccessControl_ShouldReturnNewDirectorySecurity() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\foo\")); - // Act - DirectorySecurity result = fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo\")); + // Act + DirectorySecurity result = fileSystem.Directory.GetAccessControl(XFS.Path(@"c:\foo\")); - // Assert - await That(result).IsNotNull(); - } + // Assert + await That(result).IsNotNull(); + } - [Test] - public async Task MockDirectory_SetCreationTime_ShouldNotThrowWithoutTrailingBackslash() - { - var path = XFS.Path(@"C:\NoTrailingBackslash"); - var fs = new MockFileSystem(); - fs.Directory.CreateDirectory(path); - await That(()=> fs.Directory.SetCreationTime(path, DateTime.Now)).DoesNotThrow(); - fs.Directory.Delete(path); - } + [Test] + public async Task MockDirectory_SetCreationTime_ShouldNotThrowWithoutTrailingBackslash() + { + var path = XFS.Path(@"C:\NoTrailingBackslash"); + var fs = new MockFileSystem(); + fs.Directory.CreateDirectory(path); + await That(()=> fs.Directory.SetCreationTime(path, DateTime.Now)).DoesNotThrow(); + fs.Directory.Delete(path); + } - private static IEnumerable Failing_DirectoryMoveFromToPaths + private static IEnumerable Failing_DirectoryMoveFromToPaths + { + get { - get + var testTargetDirs = new[] { - var testTargetDirs = new[] - { - @"c:\temp2\fd\df", @"c:\temp2\fd\", @"c:\temp2\fd\..\fd", @"c:\temp2\fd", @".\..\temp2\fd\df", - @".\..\temp2\fd\df\..", @".\..\temp2\fd\df\..\", @"..\temp2\fd\", @".\temp2\fd", @"temp2\fd", - @"c:\temp3\exists2\d3", @"c:\temp4\exists" - }; - - var testSourceDirs = new[] { @"c:\temp\exists\foldertomove", @"c:\temp3\exists", @"c:\temp3" }; - - return - from s in testSourceDirs - from t in testTargetDirs - select new TestCaseData(XFS.Path(s), XFS.Path(t)); - } + @"c:\temp2\fd\df", @"c:\temp2\fd\", @"c:\temp2\fd\..\fd", @"c:\temp2\fd", @".\..\temp2\fd\df", + @".\..\temp2\fd\df\..", @".\..\temp2\fd\df\..\", @"..\temp2\fd\", @".\temp2\fd", @"temp2\fd", + @"c:\temp3\exists2\d3", @"c:\temp4\exists" + }; + + var testSourceDirs = new[] { @"c:\temp\exists\foldertomove", @"c:\temp3\exists", @"c:\temp3" }; + + return + from s in testSourceDirs + from t in testTargetDirs + select new TestCaseData(XFS.Path(s), XFS.Path(t)); } + } - [Test] - [TestCaseSource(nameof(Failing_DirectoryMoveFromToPaths))] - public async Task Move_Directory_Throws_When_Target_Directory_Parent_Does_Not_Exist( - string sourceDirName, - string targetDirName) - { - // Arange - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(sourceDirName); + [Test] + [TestCaseSource(nameof(Failing_DirectoryMoveFromToPaths))] + public async Task Move_Directory_Throws_When_Target_Directory_Parent_Does_Not_Exist( + string sourceDirName, + string targetDirName) + { + // Arange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(sourceDirName); - // Act - await That(() => fileSystem.Directory.Move(sourceDirName, targetDirName)) - .Throws(); + // Act + await That(() => fileSystem.Directory.Move(sourceDirName, targetDirName)) + .Throws(); - // Assert - await That(fileSystem.Directory.Exists(targetDirName)).IsFalse(); - await That(fileSystem.Directory.Exists(sourceDirName)).IsTrue(); - } + // Assert + await That(fileSystem.Directory.Exists(targetDirName)).IsFalse(); + await That(fileSystem.Directory.Exists(sourceDirName)).IsTrue(); + } - private static IEnumerable Success_DirectoryMoveFromToPaths + private static IEnumerable Success_DirectoryMoveFromToPaths + { + get { - get + var testTargetDirs = new[] { - var testTargetDirs = new[] - { - @"c:\temp2\", @"c:\temp2", @"c:\temp2\..\temp2", @".\..\temp2", @".\..\temp2\..\temp2", - @".\..\temp2\fd\df\..\..", @".\..\temp2\fd\df\..\..\", @"..\temp2", @".\temp2", @"\temp2", @"temp2", - }; - - var testSourceDirs = new[] { @"c:\temp3\exists\foldertomove", @"c:\temp3\exists", @"c:\temp4" }; - - return - from s in testSourceDirs - from t in testTargetDirs - select new TestCaseData(XFS.Path(s), XFS.Path(t)); - } + @"c:\temp2\", @"c:\temp2", @"c:\temp2\..\temp2", @".\..\temp2", @".\..\temp2\..\temp2", + @".\..\temp2\fd\df\..\..", @".\..\temp2\fd\df\..\..\", @"..\temp2", @".\temp2", @"\temp2", @"temp2", + }; + + var testSourceDirs = new[] { @"c:\temp3\exists\foldertomove", @"c:\temp3\exists", @"c:\temp4" }; + + return + from s in testSourceDirs + from t in testTargetDirs + select new TestCaseData(XFS.Path(s), XFS.Path(t)); } + } - [Test] - [TestCaseSource(nameof(Success_DirectoryMoveFromToPaths))] - public async Task Move_Directory_DoesNotThrow_When_Target_Directory_Parent_Exists( - string sourceDirName, - string targetDirName) - { - // Arange - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(sourceDirName); + [Test] + [TestCaseSource(nameof(Success_DirectoryMoveFromToPaths))] + public async Task Move_Directory_DoesNotThrow_When_Target_Directory_Parent_Exists( + string sourceDirName, + string targetDirName) + { + // Arange + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(sourceDirName); - // Act - await That(() => fileSystem.Directory.Move(sourceDirName, targetDirName)).DoesNotThrow(); + // Act + await That(() => fileSystem.Directory.Move(sourceDirName, targetDirName)).DoesNotThrow(); - // Assert - await That(fileSystem.Directory.Exists(targetDirName)).IsTrue(); - await That(fileSystem.Directory.Exists(sourceDirName)).IsFalse(); - } + // Assert + await That(fileSystem.Directory.Exists(targetDirName)).IsTrue(); + await That(fileSystem.Directory.Exists(sourceDirName)).IsFalse(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoFactoryTests.cs index 71d20902b..cf36bb17b 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoFactoryTests.cs @@ -2,110 +2,109 @@ using System.Linq; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.Drives)] +public class MockDriveInfoFactoryTests { - using XFS = MockUnixSupport; + [Test] + public async Task MockDriveInfoFactory_GetDrives_ShouldReturnDrives() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test")); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResults = factory.GetDrives(); + + var actualNames = actualResults.Select(d => d.Name); + + // Assert + await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); + } + + [Test] + public async Task MockDriveInfoFactory_GetDrives_ShouldReturnDrivesWithNoDuplicates() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + fileSystem.AddDirectory(XFS.Path(@"c:\Test2")); + fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test2")); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResults = factory.GetDrives(); + + var actualNames = actualResults.Select(d => d.Name); + + // Assert + await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); + } + + [Test] + public async Task MockDriveInfoFactory_GetDrives_ShouldReturnOnlyLocalDrives() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); + fileSystem.AddDirectory(XFS.Path(@"d:\Test")); + fileSystem.AddDirectory(XFS.Path(@"\\anunc\share\Zzz")); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResults = factory.GetDrives(); + + var actualNames = actualResults.Select(d => d.Name); - [TestFixture] - [WindowsOnly(WindowsSpecifics.Drives)] - public class MockDriveInfoFactoryTests + // Assert + await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); + } + + [Test] + public async Task MockDriveInfoFactory_New_WithDriveShouldReturnDrive() + { + // Arrange + var fileSystem = new MockFileSystem(); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResult = factory.New(@"Z:\"); + + // Assert + await That(actualResult.Name).IsEquivalentTo(@"Z:\"); + } + + [Test] + public async Task MockDriveInfoFactory_New_WithPathShouldReturnDrive() { - [Test] - public async Task MockDriveInfoFactory_GetDrives_ShouldReturnDrives() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test")); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResults = factory.GetDrives(); - - var actualNames = actualResults.Select(d => d.Name); - - // Assert - await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); - } - - [Test] - public async Task MockDriveInfoFactory_GetDrives_ShouldReturnDrivesWithNoDuplicates() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - fileSystem.AddDirectory(XFS.Path(@"c:\Test2")); - fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test2")); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResults = factory.GetDrives(); - - var actualNames = actualResults.Select(d => d.Name); - - // Assert - await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); - } - - [Test] - public async Task MockDriveInfoFactory_GetDrives_ShouldReturnOnlyLocalDrives() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - fileSystem.AddDirectory(XFS.Path(@"Z:\Test")); - fileSystem.AddDirectory(XFS.Path(@"d:\Test")); - fileSystem.AddDirectory(XFS.Path(@"\\anunc\share\Zzz")); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResults = factory.GetDrives(); - - var actualNames = actualResults.Select(d => d.Name); - - // Assert - await That(actualNames).IsEquivalentTo(new[] { @"C:\", @"Z:\", @"d:\" }); - } - - [Test] - public async Task MockDriveInfoFactory_New_WithDriveShouldReturnDrive() - { - // Arrange - var fileSystem = new MockFileSystem(); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResult = factory.New(@"Z:\"); - - // Assert - await That(actualResult.Name).IsEquivalentTo(@"Z:\"); - } - - [Test] - public async Task MockDriveInfoFactory_New_WithPathShouldReturnDrive() - { - // Arrange - var fileSystem = new MockFileSystem(); - var factory = new MockDriveInfoFactory(fileSystem); - - // Act - var actualResult = factory.New(@"Z:\foo\bar\"); - - // Assert - await That(actualResult.Name).IsEquivalentTo(@"Z:\"); - } - - [Test] - public async Task MockDriveInfoFactory_Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new MockFileSystem(); - - var result = fileSystem.DriveInfo.Wrap(null); - - await That(result).IsNull(); - } + // Arrange + var fileSystem = new MockFileSystem(); + var factory = new MockDriveInfoFactory(fileSystem); + + // Act + var actualResult = factory.New(@"Z:\foo\bar\"); + + // Assert + await That(actualResult.Name).IsEquivalentTo(@"Z:\"); + } + + [Test] + public async Task MockDriveInfoFactory_Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new MockFileSystem(); + + var result = fileSystem.DriveInfo.Wrap(null); + + await That(result).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoTests.cs index fdb2aea75..4946b34bb 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockDriveInfoTests.cs @@ -1,222 +1,221 @@ using NUnit.Framework; using System.Linq; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.Drives)] +public class MockDriveInfoTests { - using XFS = MockUnixSupport; + [TestCase(@"c:")] + [TestCase(@"c:\")] + public async Task MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives(string driveName) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\Test")); + var path = XFS.Path(driveName); + + // Act + var driveInfo = new MockDriveInfo(fileSystem, path); + + // Assert + await That(driveInfo.Name).IsEqualTo(@"c:\"); + } + + [Test] + public async Task MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives_SpecialForWindows() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\Test")); + + // Act + var driveInfo = new MockDriveInfo(fileSystem, "c"); + + // Assert + await That(driveInfo.Name).IsEqualTo(@"c:\"); + } + + [TestCase(@"\\unc\share")] + [TestCase(@"\\unctoo")] + public async Task MockDriveInfo_Constructor_ShouldThrowExceptionIfUncPath(string driveName) + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => new MockDriveInfo(fileSystem, XFS.Path(driveName)); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockDriveInfo_RootDirectory_ShouldReturnTheDirectoryBase() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\Test")); + var driveInfo = new MockDriveInfo(fileSystem, "c:"); + var expectedDirectory = XFS.Path(@"c:\"); + + // Act + var actualDirectory = driveInfo.RootDirectory; + + // Assert + await That(actualDirectory.FullName).IsEqualTo(expectedDirectory); + } + + [TestCase("c:", "c:\\")] + [TestCase("C:", "C:\\")] + [TestCase("d:", "d:\\")] + [TestCase("e:", "e:\\")] + [TestCase("f:", "f:\\")] + public async Task MockDriveInfo_ToString_ShouldReturnTheDrivePath(string path, string expectedPath) + { + // Arrange + var directoryPath = XFS.Path(path); + + // Act + var mockDriveInfo = new MockDriveInfo(new MockFileSystem(), directoryPath); + + // Assert + await That(mockDriveInfo.ToString()).IsEqualTo(expectedPath); + } + + [Test] + public async Task MockDriveInfo_AvailableFreeSpace_ShouldReturnAvailableFreeSpaceOfDriveInMemoryFileSystem() + { + // Arrange + var availableFreeSpace = 1024L; + var driveData = new MockDriveData { AvailableFreeSpace = availableFreeSpace }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.AvailableFreeSpace; + + // Assert + await That(result).IsEqualTo(availableFreeSpace); + } + + [Test] + public async Task MockDriveInfo_DriveFormat_ShouldReturnDriveFormatOfDriveInMemoryFileSystem() + { + // Arrange + var driveFormat = "NTFS"; + var driveData = new MockDriveData { DriveFormat = driveFormat }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.DriveFormat; + + // Assert + await That(result).IsEqualTo(driveFormat); + } + + [Test] + public async Task MockDriveInfo_DriveType_ShouldReturnDriveTypeOfDriveInMemoryFileSystem() + { + // Arrange + var driveType = DriveType.Fixed; + var driveData = new MockDriveData { DriveType = driveType }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.DriveType; + + // Assert + await That(result).IsEqualTo(driveType); + } + + [TestCase(true)] + [TestCase(false)] + public async Task MockDriveInfo_IsReady_ShouldReturnIsReadyOfDriveInMemoryFileSystem(bool isReady) + { + // Arrange + var driveData = new MockDriveData { IsReady = isReady }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.IsReady; + + // Assert + await That(result).IsEqualTo(isReady); + } + + [Test] + public async Task MockDriveInfo_TotalFreeSpace_ShouldReturnTotalFreeSpaceOfDriveInMemoryFileSystem() + { + // Arrange + var totalFreeSpace = 4096L; + var driveData = new MockDriveData { TotalFreeSpace = totalFreeSpace }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.TotalFreeSpace; + + // Assert + await That(result).IsEqualTo(totalFreeSpace); + } + + [Test] + public async Task MockDriveInfo_TotalSize_ShouldReturnTotalSizeOfDriveInMemoryFileSystem() + { + // Arrange + var totalSize = 8192L; + var driveData = new MockDriveData { TotalSize = totalSize }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.TotalSize; + + // Assert + await That(result).IsEqualTo(totalSize); + } - [TestFixture] - [WindowsOnly(WindowsSpecifics.Drives)] - public class MockDriveInfoTests + [Test] + public async Task MockDriveInfo_VolumeLabel_ShouldReturnVolumeLabelOfDriveInMemoryFileSystem() { - [TestCase(@"c:")] - [TestCase(@"c:\")] - public async Task MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives(string driveName) - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\Test")); - var path = XFS.Path(driveName); - - // Act - var driveInfo = new MockDriveInfo(fileSystem, path); - - // Assert - await That(driveInfo.Name).IsEqualTo(@"c:\"); - } - - [Test] - public async Task MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives_SpecialForWindows() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\Test")); - - // Act - var driveInfo = new MockDriveInfo(fileSystem, "c"); - - // Assert - await That(driveInfo.Name).IsEqualTo(@"c:\"); - } - - [TestCase(@"\\unc\share")] - [TestCase(@"\\unctoo")] - public async Task MockDriveInfo_Constructor_ShouldThrowExceptionIfUncPath(string driveName) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Action action = () => new MockDriveInfo(fileSystem, XFS.Path(driveName)); - - // Assert - await That(action).Throws(); - } - - [Test] - public async Task MockDriveInfo_RootDirectory_ShouldReturnTheDirectoryBase() - { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\Test")); - var driveInfo = new MockDriveInfo(fileSystem, "c:"); - var expectedDirectory = XFS.Path(@"c:\"); - - // Act - var actualDirectory = driveInfo.RootDirectory; - - // Assert - await That(actualDirectory.FullName).IsEqualTo(expectedDirectory); - } - - [TestCase("c:", "c:\\")] - [TestCase("C:", "C:\\")] - [TestCase("d:", "d:\\")] - [TestCase("e:", "e:\\")] - [TestCase("f:", "f:\\")] - public async Task MockDriveInfo_ToString_ShouldReturnTheDrivePath(string path, string expectedPath) - { - // Arrange - var directoryPath = XFS.Path(path); - - // Act - var mockDriveInfo = new MockDriveInfo(new MockFileSystem(), directoryPath); - - // Assert - await That(mockDriveInfo.ToString()).IsEqualTo(expectedPath); - } - - [Test] - public async Task MockDriveInfo_AvailableFreeSpace_ShouldReturnAvailableFreeSpaceOfDriveInMemoryFileSystem() - { - // Arrange - var availableFreeSpace = 1024L; - var driveData = new MockDriveData { AvailableFreeSpace = availableFreeSpace }; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive("C:", driveData); - var driveInfo = fileSystem.DriveInfo - .GetDrives() - .Single(x => x.Name == @"C:\"); - - // Act - var result = driveInfo.AvailableFreeSpace; - - // Assert - await That(result).IsEqualTo(availableFreeSpace); - } - - [Test] - public async Task MockDriveInfo_DriveFormat_ShouldReturnDriveFormatOfDriveInMemoryFileSystem() - { - // Arrange - var driveFormat = "NTFS"; - var driveData = new MockDriveData { DriveFormat = driveFormat }; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive("C:", driveData); - var driveInfo = fileSystem.DriveInfo - .GetDrives() - .Single(x => x.Name == @"C:\"); - - // Act - var result = driveInfo.DriveFormat; - - // Assert - await That(result).IsEqualTo(driveFormat); - } - - [Test] - public async Task MockDriveInfo_DriveType_ShouldReturnDriveTypeOfDriveInMemoryFileSystem() - { - // Arrange - var driveType = DriveType.Fixed; - var driveData = new MockDriveData { DriveType = driveType }; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive("C:", driveData); - var driveInfo = fileSystem.DriveInfo - .GetDrives() - .Single(x => x.Name == @"C:\"); - - // Act - var result = driveInfo.DriveType; - - // Assert - await That(result).IsEqualTo(driveType); - } - - [TestCase(true)] - [TestCase(false)] - public async Task MockDriveInfo_IsReady_ShouldReturnIsReadyOfDriveInMemoryFileSystem(bool isReady) - { - // Arrange - var driveData = new MockDriveData { IsReady = isReady }; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive("C:", driveData); - var driveInfo = fileSystem.DriveInfo - .GetDrives() - .Single(x => x.Name == @"C:\"); - - // Act - var result = driveInfo.IsReady; - - // Assert - await That(result).IsEqualTo(isReady); - } - - [Test] - public async Task MockDriveInfo_TotalFreeSpace_ShouldReturnTotalFreeSpaceOfDriveInMemoryFileSystem() - { - // Arrange - var totalFreeSpace = 4096L; - var driveData = new MockDriveData { TotalFreeSpace = totalFreeSpace }; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive("C:", driveData); - var driveInfo = fileSystem.DriveInfo - .GetDrives() - .Single(x => x.Name == @"C:\"); - - // Act - var result = driveInfo.TotalFreeSpace; - - // Assert - await That(result).IsEqualTo(totalFreeSpace); - } - - [Test] - public async Task MockDriveInfo_TotalSize_ShouldReturnTotalSizeOfDriveInMemoryFileSystem() - { - // Arrange - var totalSize = 8192L; - var driveData = new MockDriveData { TotalSize = totalSize }; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive("C:", driveData); - var driveInfo = fileSystem.DriveInfo - .GetDrives() - .Single(x => x.Name == @"C:\"); - - // Act - var result = driveInfo.TotalSize; - - // Assert - await That(result).IsEqualTo(totalSize); - } - - [Test] - public async Task MockDriveInfo_VolumeLabel_ShouldReturnVolumeLabelOfDriveInMemoryFileSystem() - { - // Arrange - var volumeLabel = "Windows"; - var driveData = new MockDriveData { VolumeLabel = volumeLabel }; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive("C:", driveData); - var driveInfo = fileSystem.DriveInfo - .GetDrives() - .Single(x => x.Name == @"C:\"); - - // Act - var result = driveInfo.VolumeLabel; - - // Assert - await That(result).IsEqualTo(volumeLabel); - } + // Arrange + var volumeLabel = "Windows"; + var driveData = new MockDriveData { VolumeLabel = volumeLabel }; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive("C:", driveData); + var driveInfo = fileSystem.DriveInfo + .GetDrives() + .Single(x => x.Name == @"C:\"); + + // Act + var result = driveInfo.VolumeLabel; + + // Assert + await That(result).IsEqualTo(volumeLabel); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAdjustTimesTest.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAdjustTimesTest.cs index 17fa1cb9c..89d270c1a 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAdjustTimesTest.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAdjustTimesTest.cs @@ -3,300 +3,299 @@ using System.Text; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileAdjustTimesTest { - [TestFixture] - public class MockFileAdjustTimesTest + [Test] + public async Task MockFile_AfterAppendAllText_ShouldUpdateLastAccessAndLastWriteTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.AppendAllText("foo.txt", "xyz"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [Test] + public async Task MockFile_AfterCopy_ShouldUpdateCreationAndLastAccessTimeOfDestination() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Copy("foo.txt", "bar.txt"); + + var actualSourceCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualDestinationCreationTime = fileSystem.File.GetCreationTimeUtc("bar.txt"); + var actualSourceLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualDestinationLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("bar.txt"); + var actualSourceLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + var actualDestinationLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("bar.txt"); + + await That(actualSourceCreationTime).IsEqualTo(creationTime); + await That(actualDestinationCreationTime).IsEqualTo(updateTime); + await That(actualSourceLastAccessTime).IsEqualTo(creationTime); + await That(actualDestinationLastAccessTime).IsEqualTo(updateTime); + await That(actualSourceLastWriteTime).IsEqualTo(creationTime); + await That(actualDestinationLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterMove_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Move("foo.txt", "bar.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("bar.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("bar.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("bar.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [TestCase(FileMode.Open, FileAccess.ReadWrite)] + [TestCase(FileMode.OpenOrCreate, FileAccess.Write)] + [TestCase(FileMode.Append, FileAccess.Write)] + public async Task MockFile_AfterOpen_WithWriteAccess_ShouldUpdateLastAccessAndLastWriteTime(FileMode fileMode, FileAccess fileAccess) + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Open("foo.txt", fileMode, fileAccess); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [TestCase(FileMode.Open, FileAccess.Read)] + [TestCase(FileMode.OpenOrCreate, FileAccess.Read)] + public async Task MockFile_AfterOpen_WithReadOnlyAccess_ShouldUpdateLastAccessTime(FileMode fileMode, FileAccess fileAccess) + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.Open("foo.txt", fileMode, fileAccess); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterReadAllBytes_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.ReadAllBytes("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterReadAllLines_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.ReadAllLines("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterReadAllText_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.ReadAllText("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterSetAttributes_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.SetAttributes("foo.txt", FileAttributes.Hidden); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + [SupportedOSPlatform("windows")] + [WindowsOnly(WindowsSpecifics.AccessControlLists)] + public async Task MockFile_AfterSetAccessControl_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.SetAccessControl("foo.txt", new FileSecurity()); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(creationTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFile_AfterWriteAllBytes_ShouldUpdateLastAccessAndLastWriteTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.WriteAllBytes("foo.txt", Encoding.UTF8.GetBytes("xyz")); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [Test] + public async Task MockFile_AfterWriteAllText_ShouldUpdateLastAccessAndLastWriteTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); + } + + [Test] + public async Task MockFileStream_OpenRead_ShouldUpdateLastAccessTime() + { + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + _ = fileSystem.File.OpenRead("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(creationTime); + } + + [Test] + public async Task MockFileStream_OpenWrite_ShouldUpdateLastAccessAndLastWriteTime() { - [Test] - public async Task MockFile_AfterAppendAllText_ShouldUpdateLastAccessAndLastWriteTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.AppendAllText("foo.txt", "xyz"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(updateTime); - } - - [Test] - public async Task MockFile_AfterCopy_ShouldUpdateCreationAndLastAccessTimeOfDestination() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.Copy("foo.txt", "bar.txt"); - - var actualSourceCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualDestinationCreationTime = fileSystem.File.GetCreationTimeUtc("bar.txt"); - var actualSourceLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualDestinationLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("bar.txt"); - var actualSourceLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - var actualDestinationLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("bar.txt"); - - await That(actualSourceCreationTime).IsEqualTo(creationTime); - await That(actualDestinationCreationTime).IsEqualTo(updateTime); - await That(actualSourceLastAccessTime).IsEqualTo(creationTime); - await That(actualDestinationLastAccessTime).IsEqualTo(updateTime); - await That(actualSourceLastWriteTime).IsEqualTo(creationTime); - await That(actualDestinationLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_AfterMove_ShouldUpdateLastAccessTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.Move("foo.txt", "bar.txt"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("bar.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("bar.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("bar.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [TestCase(FileMode.Open, FileAccess.ReadWrite)] - [TestCase(FileMode.OpenOrCreate, FileAccess.Write)] - [TestCase(FileMode.Append, FileAccess.Write)] - public async Task MockFile_AfterOpen_WithWriteAccess_ShouldUpdateLastAccessAndLastWriteTime(FileMode fileMode, FileAccess fileAccess) - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.Open("foo.txt", fileMode, fileAccess); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(updateTime); - } - - [TestCase(FileMode.Open, FileAccess.Read)] - [TestCase(FileMode.OpenOrCreate, FileAccess.Read)] - public async Task MockFile_AfterOpen_WithReadOnlyAccess_ShouldUpdateLastAccessTime(FileMode fileMode, FileAccess fileAccess) - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.Open("foo.txt", fileMode, fileAccess); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_AfterReadAllBytes_ShouldUpdateLastAccessTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.ReadAllBytes("foo.txt"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_AfterReadAllLines_ShouldUpdateLastAccessTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.ReadAllLines("foo.txt"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_AfterReadAllText_ShouldUpdateLastAccessTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.ReadAllText("foo.txt"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_AfterSetAttributes_ShouldUpdateLastAccessTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.SetAttributes("foo.txt", FileAttributes.Hidden); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - [SupportedOSPlatform("windows")] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - public async Task MockFile_AfterSetAccessControl_ShouldUpdateLastAccessTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.SetAccessControl("foo.txt", new FileSecurity()); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(creationTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_AfterWriteAllBytes_ShouldUpdateLastAccessAndLastWriteTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.WriteAllBytes("foo.txt", Encoding.UTF8.GetBytes("xyz")); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(updateTime); - } - - [Test] - public async Task MockFile_AfterWriteAllText_ShouldUpdateLastAccessAndLastWriteTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - fileSystem.File.WriteAllText("foo.txt", "xyz"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(updateTime); - } - - [Test] - public async Task MockFileStream_OpenRead_ShouldUpdateLastAccessTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - _ = fileSystem.File.OpenRead("foo.txt"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFileStream_OpenWrite_ShouldUpdateLastAccessAndLastWriteTime() - { - var creationTime = DateTime.UtcNow.AddDays(10); - var updateTime = creationTime.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => creationTime); - fileSystem.File.WriteAllText("foo.txt", "abc"); - fileSystem.MockTime(() => updateTime); - _ = fileSystem.File.OpenWrite("foo.txt"); - - var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(actualCreationTime).IsEqualTo(creationTime); - await That(actualLastAccessTime).IsEqualTo(updateTime); - await That(actualLastWriteTime).IsEqualTo(updateTime); - } + var creationTime = DateTime.UtcNow.AddDays(10); + var updateTime = creationTime.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => creationTime); + fileSystem.File.WriteAllText("foo.txt", "abc"); + fileSystem.MockTime(() => updateTime); + _ = fileSystem.File.OpenWrite("foo.txt"); + + var actualCreationTime = fileSystem.File.GetCreationTimeUtc("foo.txt"); + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(actualCreationTime).IsEqualTo(creationTime); + await That(actualLastAccessTime).IsEqualTo(updateTime); + await That(actualLastWriteTime).IsEqualTo(updateTime); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllLinesTests.cs index fed728208..f67ed4c76 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllLinesTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllLinesTests.cs @@ -4,120 +4,120 @@ using System.Threading.Tasks; using System.Threading; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileAppendAllLinesTests { - public class MockFileAppendAllLinesTests + [Test] + public async Task MockFile_AppendAllLines_ShouldPersistNewLinesToExistingFile() { - [Test] - public async Task MockFile_AppendAllLines_ShouldPersistNewLinesToExistingFile() + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); + { path, new MockFileData("Demo text content") } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); + // Act + file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); - // Assert - await That(file.ReadAllText(path)) - .IsEqualTo("Demo text contentline 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); - } + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("Demo text contentline 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); + } - [Test] - public async Task MockFile_AppendAllLines_ShouldPersistNewLinesToNewFile() + [Test] + public async Task MockFile_AppendAllLines_ShouldPersistNewLinesToNewFile() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\"), new MockDirectoryData() } - }); - var file = new MockFile(fileSystem); + { XFS.Path(@"c:\something\"), new MockDirectoryData() } + }); + var file = new MockFile(fileSystem); - // Act - file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); + // Act + file.AppendAllLines(path, new[] { "line 1", "line 2", "line 3" }); - // Assert - await That(file.ReadAllText(path)) - .IsEqualTo("line 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); - } + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("line 1" + Environment.NewLine + "line 2" + Environment.NewLine + "line 3" + Environment.NewLine); + } - [Test] - public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathIsZeroLength() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathIsZeroLength() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.AppendAllLines(string.Empty, new[] { "does not matter" }); + // Act + Action action = () => fileSystem.File.AppendAllLines(string.Empty, new[] { "does not matter" }); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); + // Act + Action action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [TestCase("\"")] - [TestCase("<")] - [TestCase(">")] - [TestCase("|")] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsInvalidChar(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + [TestCase("\"")] + [TestCase("<")] + [TestCase(">")] + [TestCase("|")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsInvalidChar(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); + // Act + Action action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" }); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfContentIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfContentIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.AppendAllLines("foo", null); + // Act + Action action = () => fileSystem.File.AppendAllLines("foo", null); - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("contents"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("contents"); + } - [Test] - public async Task MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfEncodingIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_AppendAllLines_ShouldThrowArgumentNullExceptionIfEncodingIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.AppendAllLines("foo.txt", new[] { "bar" }, null); + // Act + Action action = () => fileSystem.File.AppendAllLines("foo.txt", new[] { "bar" }, null); - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("encoding"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("encoding"); + } #if FEATURE_ASYNC_FILE [Test] @@ -253,5 +253,4 @@ public async Task MockFile_AppendAllLinesAsync_ShouldThrowArgumentNullExceptionI await That(exception.ParamName).IsEqualTo("encoding"); } #endif - } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllTextTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllTextTests.cs index 2da36ec0b..8a8f280e8 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllTextTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileAppendAllTextTests.cs @@ -1,315 +1,314 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; - using Globalization; +using Globalization; - using NUnit.Framework; - using Text; +using NUnit.Framework; +using Text; - using XFS = MockUnixSupport; +using XFS = MockUnixSupport; - using System.Threading.Tasks; - using System.Threading; +using System.Threading.Tasks; +using System.Threading; - public class MockFileAppendAllTextTests +public class MockFileAppendAllTextTests +{ + [Test] + public async Task MockFile_AppendAllText_ShouldPersistNewText() { - [Test] - public async Task MockFile_AppendAllText_ShouldPersistNewText() + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); + {path, new MockFileData("Demo text content")} + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - file.AppendAllText(path, "+ some text"); + // Act + file.AppendAllText(path, "+ some text"); - // Assert - await That(file.ReadAllText(path)) - .IsEqualTo("Demo text content+ some text"); - } + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("Demo text content+ some text"); + } - [Test] - public async Task MockFile_AppendAllText_ShouldPersistNewTextWithDifferentEncoding() + [Test] + public async Task MockFile_AppendAllText_ShouldPersistNewTextWithDifferentEncoding() + { + // Arrange + const string Path = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - const string Path = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - {Path, new MockFileData("AA", Encoding.UTF32)} - }); + {Path, new MockFileData("AA", Encoding.UTF32)} + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - file.AppendAllText(Path, "BB", Encoding.UTF8); + // Act + file.AppendAllText(Path, "BB", Encoding.UTF8); - // Assert - await That(fileSystem.GetFile(Path).Contents) - .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 66, 66 }); - } + // Assert + await That(fileSystem.GetFile(Path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 66, 66 }); + } - [Test] - public async Task MockFile_AppendAllText_ShouldCreateIfNotExist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - // Act - fileSystem.File.AppendAllText(path, " some text"); - - // Assert - await That(fileSystem.File.ReadAllText(path)) - .IsEqualTo("Demo text content some text"); - } - - [Test] - public async Task MockFile_AppendAllText_ShouldCreateIfNotExistWithBom() + [Test] + public async Task MockFile_AppendAllText_ShouldCreateIfNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary()); - var path = XFS.Path(@"c:\something\demo3.txt"); - fileSystem.AddDirectory(XFS.Path(@"c:\something\")); + {path, new MockFileData("Demo text content")} + }); + + // Act + fileSystem.File.AppendAllText(path, " some text"); - // Act - fileSystem.File.AppendAllText(path, "AA", Encoding.UTF32); + // Assert + await That(fileSystem.File.ReadAllText(path)) + .IsEqualTo("Demo text content some text"); + } - // Assert - await That(fileSystem.GetFile(path).Contents) - .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0 }); - } + [Test] + public async Task MockFile_AppendAllText_ShouldCreateIfNotExistWithBom() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary()); + var path = XFS.Path(@"c:\something\demo3.txt"); + fileSystem.AddDirectory(XFS.Path(@"c:\something\")); + + // Act + fileSystem.File.AppendAllText(path, "AA", Encoding.UTF32); + + // Assert + await That(fileSystem.GetFile(path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0 }); + } - [Test] - public async Task MockFile_AppendAllText_ShouldFailIfNotExistButDirectoryAlsoNotExist() + [Test] + public async Task MockFile_AppendAllText_ShouldFailIfNotExistButDirectoryAlsoNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - // Act - path = XFS.Path(@"c:\something2\demo.txt"); - - // Assert - Exception ex; - ex = await That(() => fileSystem.File.AppendAllText(path, "some text")).Throws(); - await That(ex.Message) - .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); - - ex = - await That( - () => fileSystem.File.AppendAllText(path, "some text", Encoding.Unicode)).Throws(); - await That(ex.Message) - .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); - } - - [Test] - public async Task MockFile_AppendAllText_ShouldPersistNewTextWithCustomEncoding() + {path, new MockFileData("Demo text content")} + }); + + // Act + path = XFS.Path(@"c:\something2\demo.txt"); + + // Assert + Exception ex; + ex = await That(() => fileSystem.File.AppendAllText(path, "some text")).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + + ex = + await That( + () => fileSystem.File.AppendAllText(path, "some text", Encoding.Unicode)).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldPersistNewTextWithCustomEncoding() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - var file = new MockFile(fileSystem); - - // Act - file.AppendAllText(path, "+ some text", Encoding.BigEndianUnicode); - - // Assert - var expected = new byte[] - { - 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, - 101, 110, 116, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, - 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 - }; - - await That(file.ReadAllBytes(path)).IsEqualTo(expected); - } - - [Test] - public async Task MockFile_AppendAllText_ShouldWorkWithRelativePath() + {path, new MockFileData("Demo text content")} + }); + + var file = new MockFile(fileSystem); + + // Act + file.AppendAllText(path, "+ some text", Encoding.BigEndianUnicode); + + // Assert + var expected = new byte[] { - var file = "file.txt"; - var fileSystem = new MockFileSystem(); + 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, + 101, 110, 116, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, + 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 + }; - fileSystem.File.AppendAllText(file, "Foo"); + await That(file.ReadAllBytes(path)).IsEqualTo(expected); + } + + [Test] + public async Task MockFile_AppendAllText_ShouldWorkWithRelativePath() + { + var file = "file.txt"; + var fileSystem = new MockFileSystem(); - await That(fileSystem.File.Exists(file)).IsTrue(); - } + fileSystem.File.AppendAllText(file, "Foo"); + + await That(fileSystem.File.Exists(file)).IsTrue(); + } #if FEATURE_ASYNC_FILE - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldPersistNewText() + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldPersistNewText() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); + {path, new MockFileData("Demo text content")} + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - await file.AppendAllTextAsync(path, "+ some text"); + // Act + await file.AppendAllTextAsync(path, "+ some text"); - // Assert - await That(file.ReadAllText(path)) - .IsEqualTo("Demo text content+ some text"); - } + // Assert + await That(file.ReadAllText(path)) + .IsEqualTo("Demo text content+ some text"); + } - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + { + // Arrange + const string path = "test.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - const string path = "test.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("line 1") } - }); - - // Act - async Task Act() => - await fileSystem.File.AppendAllTextAsync( - path, - "line 2", - new CancellationToken(canceled: true)); - await That(Act).Throws(); - - // Assert - await That(fileSystem.File.ReadAllText(path)).IsEqualTo("line 1"); - } - - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldPersistNewTextWithDifferentEncoding() + { path, new MockFileData("line 1") } + }); + + // Act + async Task Act() => + await fileSystem.File.AppendAllTextAsync( + path, + "line 2", + new CancellationToken(canceled: true)); + await That(Act).Throws(); + + // Assert + await That(fileSystem.File.ReadAllText(path)).IsEqualTo("line 1"); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldPersistNewTextWithDifferentEncoding() + { + // Arrange + const string Path = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - const string Path = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - {Path, new MockFileData("AA", Encoding.UTF32)} - }); + {Path, new MockFileData("AA", Encoding.UTF32)} + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - await file.AppendAllTextAsync(Path, "BB", Encoding.UTF8); + // Act + await file.AppendAllTextAsync(Path, "BB", Encoding.UTF8); - // Assert - await That(fileSystem.GetFile(Path).Contents) - .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 66, 66 }); - } + // Assert + await That(fileSystem.GetFile(Path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 66, 66 }); + } - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldCreateIfNotExist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - // Act - await fileSystem.File.AppendAllTextAsync(path, " some text"); - - // Assert - await That(fileSystem.File.ReadAllText(path)) - .IsEqualTo("Demo text content some text"); - } - - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldCreateIfNotExistWithBom() + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldCreateIfNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary()); - var path = XFS.Path(@"c:\something\demo3.txt"); - fileSystem.AddDirectory(XFS.Path(@"c:\something\")); + {path, new MockFileData("Demo text content")} + }); + + // Act + await fileSystem.File.AppendAllTextAsync(path, " some text"); - // Act - await fileSystem.File.AppendAllTextAsync(path, "AA", Encoding.UTF32); + // Assert + await That(fileSystem.File.ReadAllText(path)) + .IsEqualTo("Demo text content some text"); + } - // Assert - await That(fileSystem.GetFile(path).Contents) - .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0 }); - } + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldCreateIfNotExistWithBom() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary()); + var path = XFS.Path(@"c:\something\demo3.txt"); + fileSystem.AddDirectory(XFS.Path(@"c:\something\")); + + // Act + await fileSystem.File.AppendAllTextAsync(path, "AA", Encoding.UTF32); + + // Assert + await That(fileSystem.GetFile(path).Contents) + .IsEqualTo(new byte[] { 255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0 }); + } - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldFailIfNotExistButDirectoryAlsoNotExist() + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldFailIfNotExistButDirectoryAlsoNotExist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - // Act - path = XFS.Path(@"c:\something2\demo.txt"); - - // Assert - Exception ex; - Func action = async () => await fileSystem.File.AppendAllTextAsync(path, "some text"); - ex = await That(action).Throws(); - await That(ex.Message) - .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); - - async Task Act() => await fileSystem.File.AppendAllTextAsync(path, "some text", Encoding.Unicode); - ex = await That(Act).Throws(); - await That(ex.Message) - .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); - } - - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldPersistNewTextWithCustomEncoding() + {path, new MockFileData("Demo text content")} + }); + + // Act + path = XFS.Path(@"c:\something2\demo.txt"); + + // Assert + Exception ex; + Func action = async () => await fileSystem.File.AppendAllTextAsync(path, "some text"); + ex = await That(action).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + + async Task Act() => await fileSystem.File.AppendAllTextAsync(path, "some text", Encoding.Unicode); + ex = await That(Act).Throws(); + await That(ex.Message) + .IsEqualTo(String.Format(CultureInfo.InvariantCulture, "Could not find a part of the path '{0}'.", path)); + } + + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldPersistNewTextWithCustomEncoding() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, new MockFileData("Demo text content")} - }); - - var file = new MockFile(fileSystem); - - // Act - await file.AppendAllTextAsync(path, "+ some text", Encoding.BigEndianUnicode); - - // Assert - var expected = new byte[] - { - 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, - 101, 110, 116, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, - 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 - }; - - await That(file.ReadAllBytes(path)).IsEqualTo(expected); - } - - [Test] - public async Task MockFile_AppendAllTextAsync_ShouldWorkWithRelativePath() + {path, new MockFileData("Demo text content")} + }); + + var file = new MockFile(fileSystem); + + // Act + await file.AppendAllTextAsync(path, "+ some text", Encoding.BigEndianUnicode); + + // Assert + var expected = new byte[] { - var file = "file.txt"; - var fileSystem = new MockFileSystem(); + 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, + 101, 110, 116, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, + 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 + }; - await fileSystem.File.AppendAllTextAsync(file, "Foo"); + await That(file.ReadAllBytes(path)).IsEqualTo(expected); + } - await That(fileSystem.File.Exists(file)).IsTrue(); - } -#endif + [Test] + public async Task MockFile_AppendAllTextAsync_ShouldWorkWithRelativePath() + { + var file = "file.txt"; + var fileSystem = new MockFileSystem(); + + await fileSystem.File.AppendAllTextAsync(file, "Foo"); + + await That(fileSystem.File.Exists(file)).IsTrue(); } +#endif } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileArgumentPathTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileArgumentPathTests.cs index 8739f955b..5015a6d30 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileArgumentPathTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileArgumentPathTests.cs @@ -4,71 +4,70 @@ using Microsoft.Win32.SafeHandles; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileArgumentPathTests { - public class MockFileArgumentPathTests + private static IEnumerable> GetFileSystemActionsForArgumentNullException() { - private static IEnumerable> GetFileSystemActionsForArgumentNullException() - { - yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }); - yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }, Encoding.ASCII); - yield return fs => fs.AppendAllText(null, "does not matter"); - yield return fs => fs.AppendAllText(null, "does not matter", Encoding.ASCII); - yield return fs => fs.AppendText(null); - yield return fs => fs.WriteAllBytes(null, new byte[] { 0 }); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }, Encoding.ASCII); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray()); - yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray(), Encoding.ASCII); - yield return fs => fs.Create(null); - yield return fs => fs.Delete(null); - yield return fs => fs.GetCreationTime((string)null); - yield return fs => fs.GetCreationTimeUtc((string)null); - yield return fs => fs.GetLastAccessTime((string)null); - yield return fs => fs.GetLastAccessTimeUtc((string)null); - yield return fs => fs.GetLastWriteTime((string)null); - yield return fs => fs.GetLastWriteTimeUtc((string)null); - yield return fs => fs.WriteAllText(null, "does not matter"); - yield return fs => fs.WriteAllText(null, "does not matter", Encoding.ASCII); - yield return fs => fs.Open(null, FileMode.OpenOrCreate); - yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read); - yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Inheritable); - yield return fs => fs.OpenRead(null); - yield return fs => fs.OpenText(null); - yield return fs => fs.OpenWrite(null); - yield return fs => fs.ReadAllBytes(null); - yield return fs => fs.ReadAllLines(null); - yield return fs => fs.ReadAllLines(null, Encoding.ASCII); - yield return fs => fs.ReadAllText(null); - yield return fs => fs.ReadAllText(null, Encoding.ASCII); - yield return fs => fs.ReadLines(null); - yield return fs => fs.ReadLines(null, Encoding.ASCII); - yield return fs => fs.SetAttributes((string)null, FileAttributes.Archive); - yield return fs => fs.GetAttributes((string)null); - yield return fs => fs.SetCreationTime((string)null, DateTime.Now); - yield return fs => fs.SetCreationTimeUtc((string)null, DateTime.Now); - yield return fs => fs.SetLastAccessTime((string)null, DateTime.Now); - yield return fs => fs.SetLastAccessTimeUtc((string)null, DateTime.Now); - yield return fs => fs.SetLastWriteTime((string)null, DateTime.Now); - yield return fs => fs.SetLastWriteTimeUtc((string)null, DateTime.Now); + yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }); + yield return fs => fs.AppendAllLines(null, new[] { "does not matter" }, Encoding.ASCII); + yield return fs => fs.AppendAllText(null, "does not matter"); + yield return fs => fs.AppendAllText(null, "does not matter", Encoding.ASCII); + yield return fs => fs.AppendText(null); + yield return fs => fs.WriteAllBytes(null, new byte[] { 0 }); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }, Encoding.ASCII); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray()); + yield return fs => fs.WriteAllLines(null, new[] { "does not matter" }.ToArray(), Encoding.ASCII); + yield return fs => fs.Create(null); + yield return fs => fs.Delete(null); + yield return fs => fs.GetCreationTime((string)null); + yield return fs => fs.GetCreationTimeUtc((string)null); + yield return fs => fs.GetLastAccessTime((string)null); + yield return fs => fs.GetLastAccessTimeUtc((string)null); + yield return fs => fs.GetLastWriteTime((string)null); + yield return fs => fs.GetLastWriteTimeUtc((string)null); + yield return fs => fs.WriteAllText(null, "does not matter"); + yield return fs => fs.WriteAllText(null, "does not matter", Encoding.ASCII); + yield return fs => fs.Open(null, FileMode.OpenOrCreate); + yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read); + yield return fs => fs.Open(null, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Inheritable); + yield return fs => fs.OpenRead(null); + yield return fs => fs.OpenText(null); + yield return fs => fs.OpenWrite(null); + yield return fs => fs.ReadAllBytes(null); + yield return fs => fs.ReadAllLines(null); + yield return fs => fs.ReadAllLines(null, Encoding.ASCII); + yield return fs => fs.ReadAllText(null); + yield return fs => fs.ReadAllText(null, Encoding.ASCII); + yield return fs => fs.ReadLines(null); + yield return fs => fs.ReadLines(null, Encoding.ASCII); + yield return fs => fs.SetAttributes((string)null, FileAttributes.Archive); + yield return fs => fs.GetAttributes((string)null); + yield return fs => fs.SetCreationTime((string)null, DateTime.Now); + yield return fs => fs.SetCreationTimeUtc((string)null, DateTime.Now); + yield return fs => fs.SetLastAccessTime((string)null, DateTime.Now); + yield return fs => fs.SetLastAccessTimeUtc((string)null, DateTime.Now); + yield return fs => fs.SetLastWriteTime((string)null, DateTime.Now); + yield return fs => fs.SetLastWriteTimeUtc((string)null, DateTime.Now); #pragma warning disable CA1416 - yield return fs => fs.Decrypt(null); - yield return fs => fs.Encrypt(null); + yield return fs => fs.Decrypt(null); + yield return fs => fs.Encrypt(null); #pragma warning restore CA1416 - } + } - [TestCaseSource(nameof(GetFileSystemActionsForArgumentNullException))] - public async Task Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) - { - // Arrange - var fileSystem = new MockFileSystem(); + [TestCaseSource(nameof(GetFileSystemActionsForArgumentNullException))] + public async Task Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action action) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action wrapped = () => action(fileSystem.File); + // Act + Action wrapped = () => action(fileSystem.File); - // Assert - var exception = await That(wrapped).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } + // Assert + var exception = await That(wrapped).Throws(); + await That(exception.ParamName).IsEqualTo("path"); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCopyTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCopyTests.cs index 29ed98598..ddfb7992f 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCopyTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCopyTests.cs @@ -1,421 +1,420 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - using Globalization; - using Linq; - using NUnit.Framework; - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; - public class MockFileCopyTests - { +using Collections.Generic; +using Globalization; +using Linq; +using NUnit.Framework; +using XFS = MockUnixSupport; - [Test] - public async Task MockFile_Copy_ShouldOverwriteFileWhenOverwriteFlagIsTrue() - { - string sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var sourceContents = new MockFileData("Source content"); - string destFileName = XFS.Path(@"c:\destination\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, sourceContents}, - {destFileName, new MockFileData("Destination content")} - }); - - fileSystem.File.Copy(sourceFileName, destFileName, true); - - var copyResult = fileSystem.GetFile(destFileName); - await That(sourceContents.Contents).IsEqualTo(copyResult.Contents); - } +public class MockFileCopyTests +{ - [Test] - public async Task MockFile_Copy_ShouldAdjustTimestampsOnDestination() + [Test] + public async Task MockFile_Copy_ShouldOverwriteFileWhenOverwriteFlagIsTrue() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content"); + string destFileName = XFS.Path(@"c:\destination\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - var sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var destFileName = XFS.Path(@"c:\source\demo_copy.txt"); - - var mockFileSystem = new MockFileSystem(); - mockFileSystem.AddFile(sourceFileName, "Original"); - mockFileSystem.File.Copy(sourceFileName, destFileName); - - var sourceFileInfo = mockFileSystem.FileInfo.New(sourceFileName); - var destFileInfo = mockFileSystem.FileInfo.New(destFileName); - await That(destFileInfo.LastWriteTime).IsEqualTo(sourceFileInfo.LastWriteTime); - await That(DateTime.Now - destFileInfo.CreationTime).IsLessThanOrEqualTo( TimeSpan.FromSeconds(1)); - await That(destFileInfo.LastAccessTime).IsEqualTo(destFileInfo.CreationTime); - } + {sourceFileName, sourceContents}, + {destFileName, new MockFileData("Destination content")} + }); - [Test] - public async Task MockFile_Copy_ShouldCloneContents() - { - var sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var destFileName = XFS.Path(@"c:\source\demo_copy.txt"); + fileSystem.File.Copy(sourceFileName, destFileName, true); - var mockFileSystem = new MockFileSystem(); - mockFileSystem.AddFile(sourceFileName, "Original"); - mockFileSystem.File.Copy(sourceFileName, destFileName); + var copyResult = fileSystem.GetFile(destFileName); + await That(sourceContents.Contents).IsEqualTo(copyResult.Contents); + } - using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) - { - var binaryWriter = new System.IO.BinaryWriter(stream); + [Test] + public async Task MockFile_Copy_ShouldAdjustTimestampsOnDestination() + { + var sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var destFileName = XFS.Path(@"c:\source\demo_copy.txt"); + + var mockFileSystem = new MockFileSystem(); + mockFileSystem.AddFile(sourceFileName, "Original"); + mockFileSystem.File.Copy(sourceFileName, destFileName); + + var sourceFileInfo = mockFileSystem.FileInfo.New(sourceFileName); + var destFileInfo = mockFileSystem.FileInfo.New(destFileName); + await That(destFileInfo.LastWriteTime).IsEqualTo(sourceFileInfo.LastWriteTime); + await That(DateTime.Now - destFileInfo.CreationTime).IsLessThanOrEqualTo( TimeSpan.FromSeconds(1)); + await That(destFileInfo.LastAccessTime).IsEqualTo(destFileInfo.CreationTime); + } - binaryWriter.Seek(0, SeekOrigin.Begin); - binaryWriter.Write("Modified"); - } + [Test] + public async Task MockFile_Copy_ShouldCloneContents() + { + var sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var destFileName = XFS.Path(@"c:\source\demo_copy.txt"); - await That(mockFileSystem.File.ReadAllText(destFileName)).IsEqualTo("Original"); - } + var mockFileSystem = new MockFileSystem(); + mockFileSystem.AddFile(sourceFileName, "Original"); + mockFileSystem.File.Copy(sourceFileName, destFileName); - [Test] - public async Task MockFile_Copy_ShouldCloneBinaryContents() + using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) { - var sourceFileName = XFS.Path(@"c:\source\demo.bin"); - var destFileName = XFS.Path(@"c:\source\demo_copy.bin"); + var binaryWriter = new System.IO.BinaryWriter(stream); - byte[] original = new byte[] { 0xC0 }; - var mockFileSystem = new MockFileSystem(); - mockFileSystem.AddFile(sourceFileName, new MockFileData(original)); - mockFileSystem.File.Copy(sourceFileName, destFileName); + binaryWriter.Seek(0, SeekOrigin.Begin); + binaryWriter.Write("Modified"); + } - using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) - { - var binaryWriter = new System.IO.BinaryWriter(stream); + await That(mockFileSystem.File.ReadAllText(destFileName)).IsEqualTo("Original"); + } - binaryWriter.Seek(0, SeekOrigin.Begin); - binaryWriter.Write("Modified"); - } + [Test] + public async Task MockFile_Copy_ShouldCloneBinaryContents() + { + var sourceFileName = XFS.Path(@"c:\source\demo.bin"); + var destFileName = XFS.Path(@"c:\source\demo_copy.bin"); - await That(mockFileSystem.File.ReadAllBytes(destFileName)).IsEqualTo(original); - } + byte[] original = new byte[] { 0xC0 }; + var mockFileSystem = new MockFileSystem(); + mockFileSystem.AddFile(sourceFileName, new MockFileData(original)); + mockFileSystem.File.Copy(sourceFileName, destFileName); - [Test] - public async Task MockFile_Copy_ShouldCreateFileAtNewDestination() + using (var stream = mockFileSystem.File.Open(sourceFileName, FileMode.Open, FileAccess.ReadWrite)) { - string sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var sourceContents = new MockFileData("Source content"); - string destFileName = XFS.Path(@"c:\source\demo_copy.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, sourceContents} - }); - - fileSystem.File.Copy(sourceFileName, destFileName, false); - - var copyResult = fileSystem.GetFile(destFileName); - await That(sourceContents.Contents).IsEqualTo(copyResult.Contents); - } + var binaryWriter = new System.IO.BinaryWriter(stream); - [Test] - public async Task MockFile_Copy_ShouldThrowExceptionWhenFileExistsAtDestination() - { - string sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var sourceContents = new MockFileData("Source content"); - string destFileName = XFS.Path(@"c:\destination\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, sourceContents}, - {destFileName, new MockFileData("Destination content")} - }); - - await That(() => fileSystem.File.Copy(sourceFileName, destFileName), XFS.Path(@"The file c:\destination\demo.txt already exists.")).Throws(); + binaryWriter.Seek(0, SeekOrigin.Begin); + binaryWriter.Write("Modified"); } - [TestCase(@"c:\source\demo.txt", @"c:\source\doesnotexist\demo.txt")] - [TestCase(@"c:\source\demo.txt", @"c:\doesnotexist\demo.txt")] - public async Task MockFile_Copy_ShouldThrowExceptionWhenFolderInDestinationDoesNotExist(string sourceFilePath, string destFilePath) - { - string sourceFileName = XFS.Path(sourceFilePath); - string destFileName = XFS.Path(destFilePath); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, string.Empty} - }); - - await That(() => fileSystem.File.Copy(sourceFileName, destFileName), string.Format(CultureInfo.InvariantCulture, @"Could not find a part of the path '{0}'.", destFilePath)).Throws(); - } + await That(mockFileSystem.File.ReadAllBytes(destFileName)).IsEqualTo(original); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() + [Test] + public async Task MockFile_Copy_ShouldCreateFileAtNewDestination() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content"); + string destFileName = XFS.Path(@"c:\source\demo_copy.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + {sourceFileName, sourceContents} + }); - var exception = await That(() => fileSystem.File.Copy(null, destFilePath)).Throws(); + fileSystem.File.Copy(sourceFileName, destFileName, false); - await That(exception.Message).StartsWith("File name cannot be null."); - } + var copyResult = fileSystem.GetFile(destFileName); + await That(sourceContents.Contents).IsEqualTo(copyResult.Contents); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() + [Test] + public async Task MockFile_Copy_ShouldThrowExceptionWhenFileExistsAtDestination() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content"); + string destFileName = XFS.Path(@"c:\destination\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + {sourceFileName, sourceContents}, + {destFileName, new MockFileData("Destination content")} + }); - var exception = await That(() => fileSystem.File.Copy(null, destFilePath)).Throws(); - - await That(exception.ParamName).IsEqualTo("sourceFileName"); - } + await That(() => fileSystem.File.Copy(sourceFileName, destFileName), XFS.Path(@"The file c:\destination\demo.txt already exists.")).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceFileNameContainsInvalidChars_Message() + [TestCase(@"c:\source\demo.txt", @"c:\source\doesnotexist\demo.txt")] + [TestCase(@"c:\source\demo.txt", @"c:\doesnotexist\demo.txt")] + public async Task MockFile_Copy_ShouldThrowExceptionWhenFolderInDestinationDoesNotExist(string sourceFilePath, string destFilePath) + { + string sourceFileName = XFS.Path(sourceFilePath); + string destFileName = XFS.Path(destFilePath); + var fileSystem = new MockFileSystem(new Dictionary { - var destFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); - var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + {sourceFileName, string.Empty} + }); - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) - { - var sourceFilePath = @"c:\something\demo.txt" + invalidChar; + await That(() => fileSystem.File.Copy(sourceFileName, destFileName), string.Format(CultureInfo.InvariantCulture, @"Could not find a part of the path '{0}'.", destFilePath)).Throws(); + } - var exception = - await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } + var exception = await That(() => fileSystem.File.Copy(null, destFilePath)).Throws(); - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourcePathContainsInvalidChars_Message() - { - var destFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); + await That(exception.Message).StartsWith("File name cannot be null."); + } - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var sourceFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = - await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Copy(null, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } - } + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetPathContainsInvalidChars_Message() - { - var sourceFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceFileNameContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var destFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) + { + var sourceFilePath = @"c:\something\demo.txt" + invalidChar; - var exception = - await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetFileNameContainsInvalidChars_Message() - { - var sourceFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); - var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourcePathContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) - { - var destFilePath = @"c:\something\demo.txt" + invalidChar; + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) + { + var sourceFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; - var exception = - await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetPathContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidUseOfDriveSeparator() + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) { - var badSourcePath = @"C::\something\demo.txt"; - var destinationPath = @"C:\elsewhere\demo.txt"; - var fileSystem = new MockFileSystem(); + var destFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; - Action action = () => fileSystem.File.Copy(badSourcePath, destinationPath); + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); - await That(action).Throws(); + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } + + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetFileNameContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidDriveLetter() + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) { - var badSourcePath = @"0:\something\demo.txt"; - var destinationPath = @"C:\elsewhere\demo.txt"; - var fileSystem = new MockFileSystem(); + var destFilePath = @"c:\something\demo.txt" + invalidChar; - Action action = () => fileSystem.File.Copy(badSourcePath, destinationPath); + var exception = + await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); - await That(action).Throws(); + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidUseOfDriveSeparator() - { - var sourcePath = @"C:\something\demo.txt"; - var badDestinationPath = @"C:\elsewhere:\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidUseOfDriveSeparator() + { + var badSourcePath = @"C::\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Copy(sourcePath, badDestinationPath); + Action action = () => fileSystem.File.Copy(badSourcePath, destinationPath); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidDriveLetter() - { - var sourcePath = @"C:\something\demo.txt"; - var badDestinationPath = @"^:\elsewhere\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidDriveLetter() + { + var badSourcePath = @"0:\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Copy(sourcePath, badDestinationPath); + Action action = () => fileSystem.File.Copy(badSourcePath, destinationPath); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidUseOfDriveSeparator() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"C:\elsewhere:\demo.txt"; + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Copy(string.Empty, destFilePath)).Throws(); + Action action = () => fileSystem.File.Copy(sourcePath, badDestinationPath); - await That(exception.Message).StartsWith("Empty file name is not legal."); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Copy_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidDriveLetter() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"^:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Copy(string.Empty, destFilePath)).Throws(); + Action action = () => fileSystem.File.Copy(sourcePath, badDestinationPath); - await That(exception.ParamName).IsEqualTo("sourceFileName"); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() - { - string sourceFilePath = " "; - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Copy(string.Empty, destFilePath)).Throws(); - await That(exception.Message).StartsWith("The path is not of a legal form."); - } + await That(exception.Message).StartsWith("Empty file name is not legal."); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Copy(sourceFilePath, null)).Throws(); + var exception = await That(() => fileSystem.File.Copy(string.Empty, destFilePath)).Throws(); - await That(exception.Message).StartsWith("File name cannot be null."); - } + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() + { + string sourceFilePath = " "; + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Copy(sourceFilePath, null)).Throws(); + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); - await That(exception.ParamName).IsEqualTo("destFileName"); - } + await That(exception.Message).StartsWith("The path is not of a legal form."); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = " "; - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, null)).Throws(); - await That(exception.Message).StartsWith("The path is not of a legal form."); - } + await That(exception.Message).StartsWith("File name cannot be null."); + } - [Test] - public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Copy(sourceFilePath, string.Empty)).Throws(); + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, null)).Throws(); - await That(exception.Message).StartsWith("Empty file name is not legal."); - } + await That(exception.ParamName).IsEqualTo("destFileName"); + } - [Test] - public async Task MockFile_Copy_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = " "; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Copy(sourceFilePath, XFS.Path(@"c:\something\demo2.txt")); + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, destFilePath)).Throws(); - await That(action).Throws(); - } + await That(exception.Message).StartsWith("The path is not of a legal form."); + } - [Test] - public async Task MockFile_Copy_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_EvenWhenCopyingToItself() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Copy(sourceFilePath, XFS.Path(@"c:\something\demo.txt")); + var exception = await That(() => fileSystem.File.Copy(sourceFilePath, string.Empty)).Throws(); - await That(action).Throws(); - } + await That(exception.Message).StartsWith("Empty file name is not legal."); + } - [Test] - public async Task MockFile_Copy_ShouldWorkWithRelativePaths() - { - var sourceFile = "source_file.txt"; - var destinationFile = "destination_file.txt"; - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Copy_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - fileSystem.File.Create(sourceFile).Close(); - fileSystem.File.Copy(sourceFile, destinationFile); + Action action = () => fileSystem.File.Copy(sourceFilePath, XFS.Path(@"c:\something\demo2.txt")); - await That(fileSystem.File.Exists(destinationFile)).IsTrue(); - } + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_EvenWhenCopyingToItself() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + + Action action = () => fileSystem.File.Copy(sourceFilePath, XFS.Path(@"c:\something\demo.txt")); + + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Copy_ShouldWorkWithRelativePaths() + { + var sourceFile = "source_file.txt"; + var destinationFile = "destination_file.txt"; + var fileSystem = new MockFileSystem(); + + fileSystem.File.Create(sourceFile).Close(); + fileSystem.File.Copy(sourceFile, destinationFile); - [Test] - public async Task MockFile_Copy_ShouldThrowIOExceptionForInvalidFileShare() + await That(fileSystem.File.Exists(destinationFile)).IsTrue(); + } + + [Test] + public async Task MockFile_Copy_ShouldThrowIOExceptionForInvalidFileShare() + { + string sourceFileName = XFS.Path(@"c:\source\demo.txt"); + var sourceContents = new MockFileData("Source content") { - string sourceFileName = XFS.Path(@"c:\source\demo.txt"); - var sourceContents = new MockFileData("Source content") - { - AllowedFileShare = FileShare.None - }; - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFileName, sourceContents} - }); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - - Action action = () => fileSystem.File.Copy(sourceFileName, XFS.Path(@"c:\something\demo.txt")); - - await That(action).Throws(); - } + AllowedFileShare = FileShare.None + }; + var fileSystem = new MockFileSystem(new Dictionary + { + {sourceFileName, sourceContents} + }); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + Action action = () => fileSystem.File.Copy(sourceFileName, XFS.Path(@"c:\something\demo.txt")); + + await That(action).Throws(); } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCreateTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCreateTests.cs index 0563180b9..e63005dde 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCreateTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileCreateTests.cs @@ -1,305 +1,304 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; +namespace System.IO.Abstractions.TestingHelpers.Tests; - using Globalization; +using Collections.Generic; - using NUnit.Framework; +using Globalization; - using Text; +using NUnit.Framework; - using XFS = MockUnixSupport; +using Text; - public class MockFileCreateTests - { - [Test] - public async Task Mockfile_Create_ShouldCreateNewStream() - { - string fullPath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); +using XFS = MockUnixSupport; - var sut = new MockFile(fileSystem); +public class MockFileCreateTests +{ + [Test] + public async Task Mockfile_Create_ShouldCreateNewStream() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - await That(fileSystem.FileExists(fullPath)).IsFalse(); + var sut = new MockFile(fileSystem); - sut.Create(fullPath).Dispose(); + await That(fileSystem.FileExists(fullPath)).IsFalse(); - await That(fileSystem.FileExists(fullPath)).IsTrue(); - } + sut.Create(fullPath).Dispose(); - [Test] - public async Task Mockfile_Create_CanWriteToNewStream() - { - string fullPath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - var data = new UTF8Encoding(false).GetBytes("Test string"); - - var sut = new MockFile(fileSystem); - using (var stream = sut.Create(fullPath)) - { - stream.Write(data, 0, data.Length); - } - - var mockFileData = fileSystem.GetFile(fullPath); - var fileData = mockFileData.Contents; + await That(fileSystem.FileExists(fullPath)).IsTrue(); + } - await That(fileData).IsEqualTo(data); - } + [Test] + public async Task Mockfile_Create_CanWriteToNewStream() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var data = new UTF8Encoding(false).GetBytes("Test string"); - [Test] - public async Task Mockfile_Create_OverwritesExistingFile() + var sut = new MockFile(fileSystem); + using (var stream = sut.Create(fullPath)) { - string path = XFS.Path(@"c:\some\file.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\some")); + stream.Write(data, 0, data.Length); + } - var mockFile = new MockFile(fileSystem); + var mockFileData = fileSystem.GetFile(fullPath); + var fileData = mockFileData.Contents; - // Create a file - using (var stream = mockFile.Create(path)) - { - var contents = new UTF8Encoding(false).GetBytes("Test 1"); - stream.Write(contents, 0, contents.Length); - } + await That(fileData).IsEqualTo(data); + } - // Create new file that should overwrite existing file - var expectedContents = new UTF8Encoding(false).GetBytes("Test 2"); - using (var stream = mockFile.Create(path)) - { - stream.Write(expectedContents, 0, expectedContents.Length); - } + [Test] + public async Task Mockfile_Create_OverwritesExistingFile() + { + string path = XFS.Path(@"c:\some\file.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\some")); - var actualContents = fileSystem.GetFile(path).Contents; + var mockFile = new MockFile(fileSystem); - await That(actualContents).IsEqualTo(expectedContents); + // Create a file + using (var stream = mockFile.Create(path)) + { + var contents = new UTF8Encoding(false).GetBytes("Test 1"); + stream.Write(contents, 0, contents.Length); } - [Test] - public async Task Mockfile_Create_ShouldThrowUnauthorizedAccessExceptionIfPathIsReadOnly() + // Create new file that should overwrite existing file + var expectedContents = new UTF8Encoding(false).GetBytes("Test 2"); + using (var stream = mockFile.Create(path)) { - // Arrange - string path = XFS.Path(@"c:\something\read-only.txt"); - var fileSystem = new MockFileSystem(new Dictionary { { path, new MockFileData("Content") } }); - var mockFile = new MockFile(fileSystem); + stream.Write(expectedContents, 0, expectedContents.Length); + } - // Act - mockFile.SetAttributes(path, FileAttributes.ReadOnly); + var actualContents = fileSystem.GetFile(path).Contents; - // Assert - var exception = await That(() => mockFile.Create(path).Dispose()).Throws(); - await That(exception.Message).IsEqualTo(string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path)); - } + await That(actualContents).IsEqualTo(expectedContents); + } - [Test] - public async Task Mockfile_Create_ShouldThrowArgumentExceptionIfPathIsZeroLength() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task Mockfile_Create_ShouldThrowUnauthorizedAccessExceptionIfPathIsReadOnly() + { + // Arrange + string path = XFS.Path(@"c:\something\read-only.txt"); + var fileSystem = new MockFileSystem(new Dictionary { { path, new MockFileData("Content") } }); + var mockFile = new MockFile(fileSystem); - // Act - Action action = () => fileSystem.File.Create(""); + // Act + mockFile.SetAttributes(path, FileAttributes.ReadOnly); - // Assert - await That(action).Throws(); - } + // Assert + var exception = await That(() => mockFile.Create(path).Dispose()).Throws(); + await That(exception.Message).IsEqualTo(string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path)); + } - [TestCase("\"")] - [TestCase("<")] - [TestCase(">")] - [TestCase("|")] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull1(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task Mockfile_Create_ShouldThrowArgumentExceptionIfPathIsZeroLength() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.Create(path); + // Act + Action action = () => fileSystem.File.Create(""); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_Create_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + [TestCase("\"")] + [TestCase("<")] + [TestCase(">")] + [TestCase("|")] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull1(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.Create(path); + // Act + Action action = () => fileSystem.File.Create(path); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_Create_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.Create(null); + // Act + Action action = () => fileSystem.File.Create(path); - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Path cannot be null."); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_Create_ShouldThrowDirectoryNotFoundExceptionIfCreatingAndParentPathDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - var file = XFS.Path("C:\\path\\NotFound.ext"); + [Test] + public async Task MockFile_Create_ShouldThrowArgumentNullExceptionIfPathIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.Create(file); + // Act + Action action = () => fileSystem.File.Create(null); - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Could not find a part of the path"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Path cannot be null."); + } - [Test] - public async Task MockFile_Create_TruncateShouldWriteNewContents() - { - // Arrange - string testFileName = XFS.Path(@"c:\someFile.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Create_ShouldThrowDirectoryNotFoundExceptionIfCreatingAndParentPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var file = XFS.Path("C:\\path\\NotFound.ext"); - using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Create, FileAccess.Write)) - { - using (var writer = new StreamWriter(stream)) - { - writer.Write("original_text"); - } - } + // Act + Action action = () => fileSystem.File.Create(file); - // Act - using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Truncate, FileAccess.Write)) - { - using (var writer = new StreamWriter(stream)) - { - writer.Write("new_text"); - } - } + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Could not find a part of the path"); + } - // Assert - await That(fileSystem.File.ReadAllText(testFileName)).IsEqualTo("new_text"); - } + [Test] + public async Task MockFile_Create_TruncateShouldWriteNewContents() + { + // Arrange + string testFileName = XFS.Path(@"c:\someFile.txt"); + var fileSystem = new MockFileSystem(); - [Test] - public async Task MockFile_Create_TruncateShouldClearFileContentsOnOpen() + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Create, FileAccess.Write)) { - // Arrange - string testFileName = XFS.Path(@"c:\someFile.txt"); - var fileSystem = new MockFileSystem(); - - using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Create, FileAccess.Write)) + using (var writer = new StreamWriter(stream)) { - using (var writer = new StreamWriter(stream)) - { - writer.Write("original_text"); - } + writer.Write("original_text"); } + } - // Act - using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Truncate, FileAccess.Write)) + // Act + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Truncate, FileAccess.Write)) + { + using (var writer = new StreamWriter(stream)) { - // Opening the stream is enough to reset the contents + writer.Write("new_text"); } - - // Assert - await That(fileSystem.File.ReadAllText(testFileName)).IsEqualTo(string.Empty); } - [Test] - public async Task MockFile_Create_DeleteOnCloseOption_FileExistsWhileStreamIsOpen() - { - var root = XFS.Path(@"C:\"); - var filePath = XFS.Path(@"C:\test.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(root); + // Assert + await That(fileSystem.File.ReadAllText(testFileName)).IsEqualTo("new_text"); + } + + [Test] + public async Task MockFile_Create_TruncateShouldClearFileContentsOnOpen() + { + // Arrange + string testFileName = XFS.Path(@"c:\someFile.txt"); + var fileSystem = new MockFileSystem(); - using (fileSystem.File.Create(filePath, 4096, FileOptions.DeleteOnClose)) + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Create, FileAccess.Write)) + { + using (var writer = new StreamWriter(stream)) { - await That(fileSystem.File.Exists(filePath)).IsTrue(); + writer.Write("original_text"); } } - [Test] - public async Task MockFile_Create_DeleteOnCloseOption_FileDeletedWhenStreamIsClosed() + // Act + using (var stream = fileSystem.FileStream.New(testFileName, FileMode.Truncate, FileAccess.Write)) { - var root = XFS.Path(@"C:\"); - var filePath = XFS.Path(@"C:\test.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(root); + // Opening the stream is enough to reset the contents + } - using (fileSystem.File.Create(filePath, 4096, FileOptions.DeleteOnClose)) - { - } + // Assert + await That(fileSystem.File.ReadAllText(testFileName)).IsEqualTo(string.Empty); + } - await That(fileSystem.File.Exists(filePath)).IsFalse(); - } + [Test] + public async Task MockFile_Create_DeleteOnCloseOption_FileExistsWhileStreamIsOpen() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); - [Test] - public async Task MockFile_Create_EncryptedOption_FileNotYetEncryptedWhenStreamIsOpen() + using (fileSystem.File.Create(filePath, 4096, FileOptions.DeleteOnClose)) { - var root = XFS.Path(@"C:\"); - var filePath = XFS.Path(@"C:\test.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(root); - - using (var stream = fileSystem.File.Create(filePath, 4096, FileOptions.Encrypted)) - { - var fileInfo = fileSystem.FileInfo.New(filePath); - await That(fileInfo.Attributes.HasFlag(FileAttributes.Encrypted)).IsFalse(); - } + await That(fileSystem.File.Exists(filePath)).IsTrue(); } + } - [Test] - public async Task MockFile_Create_EncryptedOption_EncryptsFileWhenStreamIsClose() + [Test] + public async Task MockFile_Create_DeleteOnCloseOption_FileDeletedWhenStreamIsClosed() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); + + using (fileSystem.File.Create(filePath, 4096, FileOptions.DeleteOnClose)) { - var root = XFS.Path(@"C:\"); - var filePath = XFS.Path(@"C:\test.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(root); + } - using (var stream = fileSystem.File.Create(filePath, 4096, FileOptions.Encrypted)) - { - } + await That(fileSystem.File.Exists(filePath)).IsFalse(); + } + [Test] + public async Task MockFile_Create_EncryptedOption_FileNotYetEncryptedWhenStreamIsOpen() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); + + using (var stream = fileSystem.File.Create(filePath, 4096, FileOptions.Encrypted)) + { var fileInfo = fileSystem.FileInfo.New(filePath); - await That(fileInfo.Attributes.HasFlag(FileAttributes.Encrypted)).IsTrue(); + await That(fileInfo.Attributes.HasFlag(FileAttributes.Encrypted)).IsFalse(); } + } + + [Test] + public async Task MockFile_Create_EncryptedOption_EncryptsFileWhenStreamIsClose() + { + var root = XFS.Path(@"C:\"); + var filePath = XFS.Path(@"C:\test.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(root); - [Test] - public async Task MockFile_Create_ShouldWorkWithRelativePath() + using (var stream = fileSystem.File.Create(filePath, 4096, FileOptions.Encrypted)) { - var relativeFile = "file.txt"; - var fileSystem = new MockFileSystem(); + } - fileSystem.File.Create(relativeFile).Close(); + var fileInfo = fileSystem.FileInfo.New(filePath); + await That(fileInfo.Attributes.HasFlag(FileAttributes.Encrypted)).IsTrue(); + } - await That(fileSystem.File.Exists(relativeFile)).IsTrue(); - } + [Test] + public async Task MockFile_Create_ShouldWorkWithRelativePath() + { + var relativeFile = "file.txt"; + var fileSystem = new MockFileSystem(); - [Test] - public async Task MockFile_Create_CanReadFromNewStream() - { - string fullPath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + fileSystem.File.Create(relativeFile).Close(); - using (var stream = fileSystem.File.Create(fullPath)) - { - await That(stream.CanRead).IsTrue(); - } + await That(fileSystem.File.Exists(relativeFile)).IsTrue(); + } + + [Test] + public async Task MockFile_Create_CanReadFromNewStream() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + using (var stream = fileSystem.File.Create(fullPath)) + { + await That(stream.CanRead).IsTrue(); } } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs index 8b21b776f..9012b04e3 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileDeleteTests.cs @@ -1,63 +1,62 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using System.Collections.Generic; +using NUnit.Framework; + +using XFS = MockUnixSupport; + +public class MockFileDeleteTests { - using System.Collections.Generic; - using NUnit.Framework; + [Test] + public async Task MockFile_Delete_ShouldDeleteFile() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\some_folder\\test"); + var directory = fileSystem.Path.GetDirectoryName(path); + fileSystem.AddFile(path, new MockFileData("Bla")); - using XFS = MockUnixSupport; + var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; + fileSystem.File.Delete(path); + var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; - public class MockFileDeleteTests + await That(fileCount1).IsEqualTo(1).Because("File should have existed"); + await That(fileCount2).IsEqualTo(0).Because("File should have been deleted"); + } + + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_Delete_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [Test] - public async Task MockFile_Delete_ShouldDeleteFile() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\some_folder\\test"); - var directory = fileSystem.Path.GetDirectoryName(path); - fileSystem.AddFile(path, new MockFileData("Bla")); - - var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; - fileSystem.File.Delete(path); - var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; - - await That(fileCount1).IsEqualTo(1).Because("File should have existed"); - await That(fileCount2).IsEqualTo(0).Because("File should have been deleted"); - } - - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_Delete_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.Delete(path); + // Act + Action action = () => fileSystem.File.Delete(path); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_Delete_ShouldThrowDirectoryNotFoundExceptionIfParentFolderAbsent() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test\\somefile.txt"); + [Test] + public async Task MockFile_Delete_ShouldThrowDirectoryNotFoundExceptionIfParentFolderAbsent() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test\\somefile.txt"); - await That(() => fileSystem.File.Delete(path)).Throws(); - } + await That(() => fileSystem.File.Delete(path)).Throws(); + } - [Test] - public async Task MockFile_Delete_ShouldSilentlyReturnIfNonExistingFileInExistingFolder() + [Test] + public async Task MockFile_Delete_ShouldSilentlyReturnIfNonExistingFileInExistingFolder() + { + var fileSystem = new MockFileSystem(new Dictionary() { - var fileSystem = new MockFileSystem(new Dictionary() - { - { XFS.Path("C:\\temp\\exist.txt"), new MockFileData("foobar") }, - }); + { XFS.Path("C:\\temp\\exist.txt"), new MockFileData("foobar") }, + }); - string filePath = XFS.Path("C:\\temp\\somefile.txt"); + string filePath = XFS.Path("C:\\temp\\somefile.txt"); - // Delete() returns void, so there is nothing to check here beside absense of an exception - await That(() => fileSystem.File.Delete(filePath)).DoesNotThrow(); - } + // Delete() returns void, so there is nothing to check here beside absense of an exception + await That(() => fileSystem.File.Delete(filePath)).DoesNotThrow(); } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileExistsTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileExistsTests.cs index 2bfa329ee..bc064c8d9 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileExistsTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileExistsTests.cs @@ -1,134 +1,133 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; - using NUnit.Framework; +using NUnit.Framework; - using XFS = MockUnixSupport; +using XFS = MockUnixSupport; - public class MockFileExistsTests +public class MockFileExistsTests +{ + [Test] + public async Task MockFile_Exists_ShouldReturnTrueForSamePath() { - [Test] - public async Task MockFile_Exists_ShouldReturnTrueForSamePath() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } - }); - - // Act - var result = fileSystem.File.Exists(XFS.Path(@"C:\something\other.gif")); - - // Assert - await That(result).IsTrue(); - } - - [Test] - [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] - public async Task MockFile_Exists_ShouldReturnTrueForPathVaryingByCase() + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"C:\something\demo.txt", new MockFileData("Demo text content") } - }); - - // Act - var result = fileSystem.File.Exists(@"C:\SomeThing\DEMO.txt"); - - // Assert - await That(result).IsTrue(); - } - - [Test] - [UnixOnly(UnixSpecifics.CaseSensitivity)] - public async Task MockFile_Exists_ShouldReturnFalseForPathVaryingByCase() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { "/something/demo.txt", new MockFileData("Demo text content") } - }); + { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } + }); - // Act - var result = fileSystem.File.Exists("/SomeThing/DEMO.txt"); + // Act + var result = fileSystem.File.Exists(XFS.Path(@"C:\something\other.gif")); - // Assert - await That(result).IsFalse(); - } + // Assert + await That(result).IsTrue(); + } - [Test] - public async Task MockFile_Exists_ShouldReturnFalseForEntirelyDifferentPath() - { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"C:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } - }); - - // Act - var result = fileSystem.File.Exists(XFS.Path(@"C:\SomeThing\DoesNotExist.gif")); - - // Assert - await That(result).IsFalse(); - } - - [Test] - public async Task MockFile_Exists_ShouldReturnFalseForNullPath() + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFile_Exists_ShouldReturnTrueForPathVaryingByCase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { @"C:\something\demo.txt", new MockFileData("Demo text content") } + }); - // Act - var result = fileSystem.File.Exists(null); + // Act + var result = fileSystem.File.Exists(@"C:\SomeThing\DEMO.txt"); - // Assert - await That(result).IsFalse(); - } + // Assert + await That(result).IsTrue(); + } - [Test] - public async Task MockFile_Exists_ShouldReturnFalseForEmptyStringPath() + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockFile_Exists_ShouldReturnFalseForPathVaryingByCase() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { "/something/demo.txt", new MockFileData("Demo text content") } + }); - // Act - var result = fileSystem.File.Exists(string.Empty); + // Act + var result = fileSystem.File.Exists("/SomeThing/DEMO.txt"); - // Assert - await That(result).IsFalse(); - } + // Assert + await That(result).IsFalse(); + } - [Test] - public async Task MockFile_Exists_ShouldReturnFalseForInvalidCharactersInPath() + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForEntirelyDifferentPath() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { XFS.Path(@"C:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } + }); - // Act - var result = fileSystem.File.Exists(@"C:""*/:<>?|abc"); + // Act + var result = fileSystem.File.Exists(XFS.Path(@"C:\SomeThing\DoesNotExist.gif")); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForNullPath() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Assert - await That(result).IsFalse(); - } + // Act + var result = fileSystem.File.Exists(null); - [Test] - public async Task MockFile_Exists_ShouldReturnFalseForDirectories() + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForEmptyStringPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.File.Exists(string.Empty); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForInvalidCharactersInPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var result = fileSystem.File.Exists(@"C:""*/:<>?|abc"); + + // Assert + await That(result).IsFalse(); + } + + [Test] + public async Task MockFile_Exists_ShouldReturnFalseForDirectories() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"C:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } - }); - - // Act - var result = fileSystem.File.Exists(XFS.Path(@"C:\something\")); - - // Assert - await That(result).IsFalse(); - } + { XFS.Path(@"C:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"C:\something\other.gif"), new MockFileData("gif content") } + }); + + // Act + var result = fileSystem.File.Exists(XFS.Path(@"C:\something\")); + + // Assert + await That(result).IsFalse(); } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetAccessControlTests.cs index 5f56f42d4..4550a81c5 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetAccessControlTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetAccessControlTests.cs @@ -3,66 +3,65 @@ using System.Security.AccessControl; using System.Runtime.Versioning; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockFileGetAccessControlTests { - using XFS = MockUnixSupport; - [TestFixture] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - [SupportedOSPlatform("windows")] - public class MockFileGetAccessControlTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_GetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.GetAccessControl(path); + // Act + Action action = () => fileSystem.File.GetAccessControl(path); - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockFile_GetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var expectedFileName = XFS.Path(@"c:\a.txt"); + [Test] + public async Task MockFile_GetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedFileName = XFS.Path(@"c:\a.txt"); - // Act - Action action = () => fileSystem.File.GetAccessControl(expectedFileName); + // Act + Action action = () => fileSystem.File.GetAccessControl(expectedFileName); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_GetAccessControl_ShouldReturnAccessControlOfFileData() - { - // Arrange - var expectedFileSecurity = new FileSecurity(); - expectedFileSecurity.SetAccessRuleProtection(false, false); + [Test] + public async Task MockFile_GetAccessControl_ShouldReturnAccessControlOfFileData() + { + // Arrange + var expectedFileSecurity = new FileSecurity(); + expectedFileSecurity.SetAccessRuleProtection(false, false); - var filePath = XFS.Path(@"c:\a.txt"); - var fileData = new MockFileData("Test content") - { - AccessControl = expectedFileSecurity, - }; + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content") + { + AccessControl = expectedFileSecurity, + }; - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); - // Act - var fileSecurity = fileSystem.File.GetAccessControl(filePath); + // Act + var fileSecurity = fileSystem.File.GetAccessControl(filePath); - // Assert - await That(fileSecurity).IsEqualTo(expectedFileSecurity); - } + // Assert + await That(fileSecurity).IsEqualTo(expectedFileSecurity); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeTests.cs index f56803a17..7a6a86d6d 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeTests.cs @@ -1,50 +1,49 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetCreationTimeTests { - [TestFixture] - public class MockFileGetCreationTimeTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetCreationTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_GetCreationTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Action action = () => fileSystem.File.GetCreationTime(path); - - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } - - [Test] - public async Task MockFile_GetCreationTime_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualCreationTime = fileSystem.File.GetCreationTime(@"c:\does\not\exist.txt"); - - // Assert - await That(actualCreationTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); - } - - [Test] - public async Task MockFile_GetCreationTime_ShouldBeSet() - { - var now = DateTime.Now.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => now); - fileSystem.File.WriteAllText("foo.txt", "xyz"); - - var result = fileSystem.File.GetCreationTime("foo.txt"); - - await That(result.Kind).IsEqualTo(DateTimeKind.Local); - await That(result).IsEqualTo(now.ToLocalTime()); - } + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetCreationTime(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetCreationTime_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualCreationTime = fileSystem.File.GetCreationTime(@"c:\does\not\exist.txt"); + + // Assert + await That(actualCreationTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); + } + + [Test] + public async Task MockFile_GetCreationTime_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetCreationTime("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Local); + await That(result).IsEqualTo(now.ToLocalTime()); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeUtcTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeUtcTests.cs index b9ce08caa..d351291ab 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeUtcTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetCreationTimeUtcTests.cs @@ -1,50 +1,49 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetCreationTimeUtcTests { - [TestFixture] - public class MockFileGetCreationTimeUtcTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetCreationTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_GetCreationTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Action action = () => fileSystem.File.GetCreationTimeUtc(path); - - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } - - [Test] - public async Task MockFile_GetCreationTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualCreationTime = fileSystem.File.GetCreationTimeUtc(@"c:\does\not\exist.txt"); - - // Assert - await That(actualCreationTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); - } - - [Test] - public async Task MockFile_GetCreationTimeUtc_ShouldBeSet() - { - var now = DateTime.Now.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => now); - fileSystem.File.WriteAllText("foo.txt", "xyz"); - - var result = fileSystem.File.GetCreationTimeUtc("foo.txt"); - - await That(result.Kind).IsEqualTo(DateTimeKind.Utc); - await That(result).IsEqualTo(now.ToUniversalTime()); - } + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetCreationTimeUtc(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetCreationTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualCreationTime = fileSystem.File.GetCreationTimeUtc(@"c:\does\not\exist.txt"); + + // Assert + await That(actualCreationTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); + } + + [Test] + public async Task MockFile_GetCreationTimeUtc_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetCreationTimeUtc("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Utc); + await That(result).IsEqualTo(now.ToUniversalTime()); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeTests.cs index 23e9659cf..fc6a71b27 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeTests.cs @@ -1,50 +1,49 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetLastAccessTimeTests { - [TestFixture] - public class MockFileGetLastAccessTimeTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastAccessTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_GetLastAccessTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Action action = () => fileSystem.File.GetLastAccessTime(path); - - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } - - [Test] - public async Task MockFile_GetLastAccessTime_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastAccessTime = fileSystem.File.GetLastAccessTime(@"c:\does\not\exist.txt"); - - // Assert - await That(actualLastAccessTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); - } - - [Test] - public async Task MockFile_GetLastAccessTime_ShouldBeSet() - { - var now = DateTime.Now.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => now); - fileSystem.File.WriteAllText("foo.txt", "xyz"); - - var result = fileSystem.File.GetLastAccessTime("foo.txt"); - - await That(result.Kind).IsEqualTo(DateTimeKind.Local); - await That(result).IsEqualTo(now.ToLocalTime()); - } + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastAccessTime(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastAccessTime_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastAccessTime = fileSystem.File.GetLastAccessTime(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastAccessTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); + } + + [Test] + public async Task MockFile_GetLastAccessTime_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastAccessTime("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Local); + await That(result).IsEqualTo(now.ToLocalTime()); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs index 5b0b4cb3f..7d0c97f33 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastAccessTimeUtcTests.cs @@ -1,50 +1,49 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetLastAccessTimeUtcTests { - [TestFixture] - public class MockFileGetLastAccessTimeUtcTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastAccessTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_GetLastAccessTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Action action = () => fileSystem.File.GetLastAccessTimeUtc(path); - - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } - - [Test] - public async Task MockFile_GetLastAccessTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc(@"c:\does\not\exist.txt"); - - // Assert - await That(actualLastAccessTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); - } - - [Test] - public async Task MockFile_GetLastAccessTimeUtc_ShouldBeSet() - { - var now = DateTime.Now.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => now); - fileSystem.File.WriteAllText("foo.txt", "xyz"); - - var result = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); - - await That(result.Kind).IsEqualTo(DateTimeKind.Utc); - await That(result).IsEqualTo(now.ToUniversalTime()); - } + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastAccessTimeUtc(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastAccessTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastAccessTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); + } + + [Test] + public async Task MockFile_GetLastAccessTimeUtc_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastAccessTimeUtc("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Utc); + await That(result).IsEqualTo(now.ToUniversalTime()); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeTests.cs index 97cb8d384..bc8ec5a65 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeTests.cs @@ -1,50 +1,49 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileGetLastWriteTimeTests { - [TestFixture] - public class MockFileGetLastWriteTimeTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastWriteTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_GetLastWriteTime_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Action action = () => fileSystem.File.GetLastWriteTime(path); - - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } - - [Test] - public async Task MockFile_GetLastWriteTime_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastWriteTime = fileSystem.File.GetLastWriteTime(@"c:\does\not\exist.txt"); - - // Assert - await That(actualLastWriteTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); - } - - [Test] - public async Task MockFile_GetLastWriteTime_ShouldBeSet() - { - var now = DateTime.Now.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => now); - fileSystem.File.WriteAllText("foo.txt", "xyz"); - - var result = fileSystem.File.GetLastWriteTime("foo.txt"); - - await That(result.Kind).IsEqualTo(DateTimeKind.Local); - await That(result).IsEqualTo(now.ToLocalTime()); - } + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastWriteTime(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastWriteTime_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastWriteTime = fileSystem.File.GetLastWriteTime(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastWriteTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime()); + } + + [Test] + public async Task MockFile_GetLastWriteTime_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastWriteTime("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Local); + await That(result).IsEqualTo(now.ToLocalTime()); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs index 143bc72d6..5be530a15 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileGetLastWriteTimeUtcTests.cs @@ -1,49 +1,48 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileGetLastWriteTimeUtcTests { - public class MockFileGetLastWriteTimeUtcTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_GetLastWriteTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_GetLastWriteTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - Action action = () => fileSystem.File.GetLastWriteTimeUtc(path); - - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } - - [Test] - public async Task MockFile_GetLastWriteTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - - // Act - var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc(@"c:\does\not\exist.txt"); - - // Assert - await That(actualLastWriteTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); - } - - [Test] - public async Task MockFile_GetLastWriteTimeUtc_ShouldBeSet() - { - var now = DateTime.Now.AddDays(10); - var fileSystem = new MockFileSystem() - .MockTime(() => now); - fileSystem.File.WriteAllText("foo.txt", "xyz"); - - var result = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); - - await That(result.Kind).IsEqualTo(DateTimeKind.Utc); - await That(result).IsEqualTo(now.ToUniversalTime()); - } + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetLastWriteTimeUtc(path); + + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } + + [Test] + public async Task MockFile_GetLastWriteTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + var actualLastWriteTime = fileSystem.File.GetLastWriteTimeUtc(@"c:\does\not\exist.txt"); + + // Assert + await That(actualLastWriteTime).IsEqualTo(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc)); + } + + [Test] + public async Task MockFile_GetLastWriteTimeUtc_ShouldBeSet() + { + var now = DateTime.Now.AddDays(10); + var fileSystem = new MockFileSystem() + .MockTime(() => now); + fileSystem.File.WriteAllText("foo.txt", "xyz"); + + var result = fileSystem.File.GetLastWriteTimeUtc("foo.txt"); + + await That(result.Kind).IsEqualTo(DateTimeKind.Utc); + await That(result).IsEqualTo(now.ToUniversalTime()); } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoAccessControlTests.cs index ecebad139..889d4bd3b 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoAccessControlTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoAccessControlTests.cs @@ -4,62 +4,61 @@ using System.Security.AccessControl; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockFileInfoAccessControlTests { - [TestFixture] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - [SupportedOSPlatform("windows")] - public class MockFileInfoAccessControlTests + [Test] + public async Task MockFileInfo_GetAccessControl_ShouldReturnAccessControlOfFileData() { - [Test] - public async Task MockFileInfo_GetAccessControl_ShouldReturnAccessControlOfFileData() + // Arrange + var expectedFileSecurity = new FileSecurity(); + expectedFileSecurity.SetAccessRuleProtection(false, false); + + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content") { - // Arrange - var expectedFileSecurity = new FileSecurity(); - expectedFileSecurity.SetAccessRuleProtection(false, false); + AccessControl = expectedFileSecurity, + }; - var filePath = XFS.Path(@"c:\a.txt"); - var fileData = new MockFileData("Test content") - { - AccessControl = expectedFileSecurity, - }; + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + var fileInfo = fileSystem.FileInfo.New(filePath); - var fileInfo = fileSystem.FileInfo.New(filePath); + // Act + var fileSecurity = fileInfo.GetAccessControl(); - // Act - var fileSecurity = fileInfo.GetAccessControl(); + // Assert + await That(fileSecurity).IsEqualTo(expectedFileSecurity); + } - // Assert - await That(fileSecurity).IsEqualTo(expectedFileSecurity); - } + [Test] + public async Task MockFile_SetAccessControl_ShouldSetAccessControlOfFileData() + { + // Arrange + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content"); - [Test] - public async Task MockFile_SetAccessControl_ShouldSetAccessControlOfFileData() + var fileSystem = new MockFileSystem(new Dictionary() { - // Arrange - var filePath = XFS.Path(@"c:\a.txt"); - var fileData = new MockFileData("Test content"); - - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + { filePath, fileData } + }); - var fileInfo = fileSystem.FileInfo.New(filePath); + var fileInfo = fileSystem.FileInfo.New(filePath); - // Act - var expectedAccessControl = new FileSecurity(); - expectedAccessControl.SetAccessRuleProtection(false, false); - fileInfo.SetAccessControl(expectedAccessControl); + // Act + var expectedAccessControl = new FileSecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + fileInfo.SetAccessControl(expectedAccessControl); - // Assert - var accessControl = fileInfo.GetAccessControl(); - await That(accessControl).IsEqualTo(expectedAccessControl); - } + // Assert + var accessControl = fileInfo.GetAccessControl(); + await That(accessControl).IsEqualTo(expectedAccessControl); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoFactoryTests.cs index 6ec322ca4..b08e166ac 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoFactoryTests.cs @@ -1,66 +1,65 @@ using System.Collections.Generic; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileInfoFactoryTests { - [TestFixture] - public class MockFileInfoFactoryTests + [Test] + public async Task MockFileInfoFactory_New_ShouldReturnFileInfoForExistingFile() { - [Test] - public async Task MockFileInfoFactory_New_ShouldReturnFileInfoForExistingFile() + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\a.txt", new MockFileData("Demo text content") }, - { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, - }); - var fileInfoFactory = new MockFileInfoFactory(fileSystem); + { @"c:\a.txt", new MockFileData("Demo text content") }, + { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, + }); + var fileInfoFactory = new MockFileInfoFactory(fileSystem); - // Act - var result = fileInfoFactory.New(@"c:\a.txt"); + // Act + var result = fileInfoFactory.New(@"c:\a.txt"); - // Assert - await That(result).IsNotNull(); - } + // Assert + await That(result).IsNotNull(); + } - [Test] - public async Task MockFileInfoFactory_New_ShouldReturnFileInfoForNonExistentFile() + [Test] + public async Task MockFileInfoFactory_New_ShouldReturnFileInfoForNonExistentFile() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\a.txt", new MockFileData("Demo text content") }, - { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, - }); - var fileInfoFactory = new MockFileInfoFactory(fileSystem); + { @"c:\a.txt", new MockFileData("Demo text content") }, + { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, + }); + var fileInfoFactory = new MockFileInfoFactory(fileSystem); - // Act - var result = fileInfoFactory.New(@"c:\foo.txt"); + // Act + var result = fileInfoFactory.New(@"c:\foo.txt"); - // Assert - await That(result).IsNotNull(); - } + // Assert + await That(result).IsNotNull(); + } - [Test] - public async Task MockFileInfoFactory_Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFileInfoFactory_Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new MockFileSystem(); - var result = fileSystem.FileInfo.Wrap(null); + var result = fileSystem.FileInfo.Wrap(null); - await That(result).IsNull(); - } + await That(result).IsNull(); + } - [Test] - public async Task MockFileInfoFactory_Wrap_ShouldKeepNameAndFullName() - { - var fs = new MockFileSystem(); - var fileInfo = new FileInfo(@"C:\subfolder\file"); - var wrappedFileInfo = fs.FileInfo.Wrap(fileInfo); + [Test] + public async Task MockFileInfoFactory_Wrap_ShouldKeepNameAndFullName() + { + var fs = new MockFileSystem(); + var fileInfo = new FileInfo(@"C:\subfolder\file"); + var wrappedFileInfo = fs.FileInfo.Wrap(fileInfo); - await That(wrappedFileInfo.FullName).IsEqualTo(fileInfo.FullName); - await That(wrappedFileInfo.Name).IsEqualTo(fileInfo.Name); - } + await That(wrappedFileInfo.FullName).IsEqualTo(fileInfo.FullName); + await That(wrappedFileInfo.Name).IsEqualTo(fileInfo.Name); } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoSymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoSymlinkTests.cs index 1bc25fbd9..185439633 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoSymlinkTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoSymlinkTests.cs @@ -4,66 +4,65 @@ using System.Security.AccessControl; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; - [TestFixture] - public class MockFileInfoSymlinkTests - { +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileInfoSymlinkTests +{ #if FEATURE_CREATE_SYMBOLIC_LINK - [Test] - public async Task MockFileInfo_ResolveLinkTarget_ShouldReturnPathOfTargetLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - fileSystem.File.CreateSymbolicLink("foo", "bar"); + [Test] + public async Task MockFileInfo_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); - var result = fileSystem.FileInfo.New("foo").ResolveLinkTarget(false); + var result = fileSystem.FileInfo.New("foo").ResolveLinkTarget(false); - await That(result.Name).IsEqualTo("bar"); - } + await That(result.Name).IsEqualTo("bar"); + } - [Test] - public async Task MockFileInfo_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - fileSystem.File.CreateSymbolicLink("foo", "bar"); - fileSystem.File.CreateSymbolicLink("foo1", "foo"); + [Test] + public async Task MockFileInfo_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + fileSystem.File.CreateSymbolicLink("foo1", "foo"); - var result = fileSystem.FileInfo.New("foo1").ResolveLinkTarget(true); + var result = fileSystem.FileInfo.New("foo1").ResolveLinkTarget(true); - await That(result.Name).IsEqualTo("bar"); - } + await That(result.Name).IsEqualTo("bar"); + } - [Test] - public async Task MockFileInfo_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - fileSystem.File.CreateSymbolicLink("foo", "bar"); - fileSystem.File.CreateSymbolicLink("foo1", "foo"); + [Test] + public async Task MockFileInfo_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + fileSystem.File.CreateSymbolicLink("foo1", "foo"); - var result = fileSystem.FileInfo.New("foo1").ResolveLinkTarget(false); + var result = fileSystem.FileInfo.New("foo1").ResolveLinkTarget(false); - await That(result.Name).IsEqualTo("foo"); - } + await That(result.Name).IsEqualTo("foo"); + } - [Test] - public async Task MockFileInfo_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - fileSystem.File.CreateSymbolicLink("foo", "bar"); + [Test] + public async Task MockFileInfo_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); - await That(() => - { - fileSystem.FileInfo.New("bar").ResolveLinkTarget(false); - }).Throws(); - } -#endif + await That(() => + { + fileSystem.FileInfo.New("bar").ResolveLinkTarget(false); + }).Throws(); } +#endif } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoTests.cs index be607ac6c..751b259e1 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileInfoTests.cs @@ -2,981 +2,980 @@ using System.Globalization; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; - [TestFixture] - public class MockFileInfoTests +[TestFixture] +public class MockFileInfoTests +{ + [Test] + public async Task MockFileInfo_NullPath_ThrowArgumentNullException() { - [Test] - public async Task MockFileInfo_NullPath_ThrowArgumentNullException() - { - var fileSystem = new MockFileSystem(); + var fileSystem = new MockFileSystem(); - Action action = () => new MockFileInfo(fileSystem, null); + Action action = () => new MockFileInfo(fileSystem, null); - await That(action).Throws(); + await That(action).Throws(); - } + } - [Test] - public async Task MockFileInfo_Exists_ShouldReturnTrueIfFileExistsInMemoryFileSystem() + [Test] + public async Task MockFileInfo_Exists_ShouldReturnTrueIfFileExistsInMemoryFileSystem() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.Exists; + var result = fileInfo.Exists; - await That(result).IsTrue(); - } + await That(result).IsTrue(); + } - [Test] - public async Task MockFileInfo_Exists_ShouldReturnFalseIfFileDoesNotExistInMemoryFileSystem() + [Test] + public async Task MockFileInfo_Exists_ShouldReturnFalseIfFileDoesNotExistInMemoryFileSystem() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); + { XFS.Path(@"c:\a.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); - var result = fileInfo.Exists; + var result = fileInfo.Exists; - await That(result).IsFalse(); - } + await That(result).IsFalse(); + } - [Test] - public async Task MockFileInfo_Exists_ShouldReturnFalseIfPathLeadsToDirectory() + [Test] + public async Task MockFileInfo_Exists_ShouldReturnFalseIfPathLeadsToDirectory() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a\b")); + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData("Demo text content") }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a\b")); - var result = fileInfo.Exists; + var result = fileInfo.Exists; - await That(result).IsFalse(); - } + await That(result).IsFalse(); + } - [Test] - public async Task MockFileInfo_Length_ShouldReturnLengthOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_Length_ShouldReturnLengthOfFileInMemoryFileSystem() + { + const string fileContent = "Demo text content"; + var fileSystem = new MockFileSystem(new Dictionary { - const string fileContent = "Demo text content"; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.Length; + var result = fileInfo.Length; - await That(result).IsEqualTo(fileContent.Length); - } + await That(result).IsEqualTo(fileContent.Length); + } - [Test] - public async Task MockFileInfo_Length_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMemoryFileSystem() + [Test] + public async Task MockFileInfo_Length_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMemoryFileSystem() + { + const string fileContent = "Demo text content"; + var fileSystem = new MockFileSystem(new Dictionary { - const string fileContent = "Demo text content"; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); + { XFS.Path(@"c:\a.txt"), new MockFileData(fileContent) }, + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\foo.txt")); - var ex = await That(() => fileInfo.Length.ToString(CultureInfo.InvariantCulture)).Throws(); + var ex = await That(() => fileInfo.Length.ToString(CultureInfo.InvariantCulture)).Throws(); - await That(ex.FileName).IsEqualTo(XFS.Path(@"c:\foo.txt")); - } + await That(ex.FileName).IsEqualTo(XFS.Path(@"c:\foo.txt")); + } - [Test] - public async Task MockFileInfo_Length_ShouldThrowFileNotFoundExceptionIfPathLeadsToDirectory() + [Test] + public async Task MockFileInfo_Length_ShouldThrowFileNotFoundExceptionIfPathLeadsToDirectory() + { + const string fileContent = "Demo text content"; + var fileSystem = new MockFileSystem(new Dictionary { - const string fileContent = "Demo text content"; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a\b")); + { XFS.Path(@"c:\a\b\c.txt"), new MockFileData(fileContent) }, + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a\b")); - var ex = await That(() => fileInfo.Length.ToString(CultureInfo.InvariantCulture)).Throws(); + var ex = await That(() => fileInfo.Length.ToString(CultureInfo.InvariantCulture)).Throws(); - await That(ex.FileName).IsEqualTo(XFS.Path(@"c:\a\b")); - } + await That(ex.FileName).IsEqualTo(XFS.Path(@"c:\a\b")); + } - [Test] - public async Task MockFileInfo_CreationTimeUtc_ShouldReturnCreationTimeUtcOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_CreationTimeUtc_ShouldReturnCreationTimeUtcOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.CreationTimeUtc; + var result = fileInfo.CreationTimeUtc; - await That(result).IsEqualTo(creationTime.ToUniversalTime()); - } + await That(result).IsEqualTo(creationTime.ToUniversalTime()); + } - [Test] - public async Task MockFileInfo_CreationTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + [Test] + public async Task MockFileInfo_CreationTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); - var result = fileInfo.CreationTimeUtc; + var result = fileInfo.CreationTimeUtc; - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } - [Test] - public async Task MockFileInfo_CreationTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_CreationTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var newUtcTime = DateTime.UtcNow; - fileInfo.CreationTimeUtc = newUtcTime; + var newUtcTime = DateTime.UtcNow; + fileInfo.CreationTimeUtc = newUtcTime; - await That(fileInfo.CreationTimeUtc).IsEqualTo(newUtcTime); - } + await That(fileInfo.CreationTimeUtc).IsEqualTo(newUtcTime); + } - [Test] - public async Task MockFileInfo_CreationTime_ShouldReturnCreationTimeOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_CreationTime_ShouldReturnCreationTimeOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.CreationTime; + var result = fileInfo.CreationTime; - await That(result).IsEqualTo(creationTime); - } + await That(result).IsEqualTo(creationTime); + } - [Test] - public async Task MockFileInfo_CreationTime_ShouldReturnDefaultTimeForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + [Test] + public async Task MockFileInfo_CreationTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); - var result = fileInfo.CreationTime; + var result = fileInfo.CreationTime; - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } - [Test] - public async Task MockFileInfo_CreationTime_ShouldSetCreationTimeOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_CreationTime_ShouldSetCreationTimeOfFileInMemoryFileSystem() + { + var creationTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var creationTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { CreationTime = creationTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var newTime = DateTime.Now; + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + var newTime = DateTime.Now; - fileInfo.CreationTime = newTime; + fileInfo.CreationTime = newTime; - await That(fileInfo.CreationTime).IsEqualTo(newTime); - } + await That(fileInfo.CreationTime).IsEqualTo(newTime); + } - [Test] - public async Task MockFileInfo_Attributes_ShouldReturnMinusOneForNonExistingFile() - { - var fileSystem = new MockFileSystem(); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - FileAttributes expected = (FileAttributes)(-1); + [Test] + public async Task MockFileInfo_Attributes_ShouldReturnMinusOneForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + FileAttributes expected = (FileAttributes)(-1); - await That(fileInfo.Attributes).IsEqualTo(expected); - } + await That(fileInfo.Attributes).IsEqualTo(expected); + } - [Test] - public async Task MockFileInfo_Attributes_SetterShouldThrowFileNotFoundExceptionOnNonExistingFileOrDirectory() - { - var fileSystem = new MockFileSystem(); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + [Test] + public async Task MockFileInfo_Attributes_SetterShouldThrowFileNotFoundExceptionOnNonExistingFileOrDirectory() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); - await That(() => fileInfo.Attributes = FileAttributes.Hidden).Throws(); - } + await That(() => fileInfo.Attributes = FileAttributes.Hidden).Throws(); + } - [Test] - public async Task MockFileInfo_IsReadOnly_ShouldSetReadOnlyAttributeOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_IsReadOnly_ShouldSetReadOnlyAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary { - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - fileInfo.IsReadOnly = true; + fileInfo.IsReadOnly = true; - await That(fileData.Attributes & FileAttributes.ReadOnly).IsEqualTo(FileAttributes.ReadOnly); - } + await That(fileData.Attributes & FileAttributes.ReadOnly).IsEqualTo(FileAttributes.ReadOnly); + } - [Test] - public async Task MockFileInfo_IsReadOnly_ShouldSetNotReadOnlyAttributeOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_IsReadOnly_ShouldSetNotReadOnlyAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content") { Attributes = FileAttributes.ReadOnly }; + var fileSystem = new MockFileSystem(new Dictionary { - var fileData = new MockFileData("Demo text content") { Attributes = FileAttributes.ReadOnly }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - fileInfo.IsReadOnly = false; + fileInfo.IsReadOnly = false; - await That(fileData.Attributes & FileAttributes.ReadOnly).IsNotEqualTo(FileAttributes.ReadOnly); - } + await That(fileData.Attributes & FileAttributes.ReadOnly).IsNotEqualTo(FileAttributes.ReadOnly); + } - [Test] - public async Task MockFileInfo_AppendText_ShouldAddTextToFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_AppendText_ShouldAddTextToFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary { - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - using (var file = fileInfo.AppendText()) - file.WriteLine("This should be at the end"); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - string newcontents; - using (var newfile = fileInfo.OpenText()) - { - newcontents = newfile.ReadToEnd(); - } + using (var file = fileInfo.AppendText()) + file.WriteLine("This should be at the end"); - await That(newcontents).IsEqualTo($"Demo text contentThis should be at the end{Environment.NewLine}"); - } - - [Test] - public async Task MockFileInfo_AppendText_ShouldCreateFileIfMissing() + string newcontents; + using (var newfile = fileInfo.OpenText()) { - var fileSystem = new MockFileSystem(); - var targetFile = XFS.Path(@"c:\a.txt"); - var fileInfo = new MockFileInfo(fileSystem, targetFile); - - using (var file = fileInfo.AppendText()) - file.WriteLine("This should be the contents"); - - string newcontents; - using (var newfile = fileInfo.OpenText()) - { - newcontents = newfile.ReadToEnd(); - } - - await That(fileSystem.File.Exists(targetFile)).IsTrue(); - await That(newcontents).IsEqualTo($"This should be the contents{Environment.NewLine}"); + newcontents = newfile.ReadToEnd(); } - [Test] - public async Task MockFileInfo_OpenWrite_ShouldAddDataToFileInMemoryFileSystem() - { - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var bytesToAdd = new byte[] { 65, 66, 67, 68, 69 }; - - - using (var file = fileInfo.OpenWrite()) - { - file.Write(bytesToAdd, 0, bytesToAdd.Length); - } + await That(newcontents).IsEqualTo($"Demo text contentThis should be at the end{Environment.NewLine}"); + } - string newcontents; - using (var newfile = fileInfo.OpenText()) - { - newcontents = newfile.ReadToEnd(); - } + [Test] + public async Task MockFileInfo_AppendText_ShouldCreateFileIfMissing() + { + var fileSystem = new MockFileSystem(); + var targetFile = XFS.Path(@"c:\a.txt"); + var fileInfo = new MockFileInfo(fileSystem, targetFile); - await That(newcontents).IsEqualTo("ABCDEtext content"); - } + using (var file = fileInfo.AppendText()) + file.WriteLine("This should be the contents"); - [Test] - public async Task MockFileInfo_Encrypt_ShouldSetEncryptedAttributeOfFileInMemoryFileSystem() + string newcontents; + using (var newfile = fileInfo.OpenText()) { - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - fileInfo.Encrypt(); - - await That(fileData.Attributes & FileAttributes.Encrypted).IsEqualTo(FileAttributes.Encrypted); + newcontents = newfile.ReadToEnd(); } - [Test] - public async Task MockFileInfo_Decrypt_ShouldUnsetEncryptedAttributeOfFileInMemoryFileSystem() + await That(fileSystem.File.Exists(targetFile)).IsTrue(); + await That(newcontents).IsEqualTo($"This should be the contents{Environment.NewLine}"); + } + + [Test] + public async Task MockFileInfo_OpenWrite_ShouldAddDataToFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary { - var fileData = new MockFileData("Demo text content"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - fileInfo.Encrypt(); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + var bytesToAdd = new byte[] { 65, 66, 67, 68, 69 }; - fileInfo.Decrypt(); - await That(fileData.Attributes & FileAttributes.Encrypted).IsNotEqualTo(FileAttributes.Encrypted); + using (var file = fileInfo.OpenWrite()) + { + file.Write(bytesToAdd, 0, bytesToAdd.Length); } - [Test] - public async Task MockFileInfo_LastAccessTimeUtc_ShouldReturnLastAccessTimeUtcOfFileInMemoryFileSystem() + string newcontents; + using (var newfile = fileInfo.OpenText()) { - var lastAccessTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - - var result = fileInfo.LastAccessTimeUtc; - - await That(result).IsEqualTo(lastAccessTime.ToUniversalTime()); + newcontents = newfile.ReadToEnd(); } - [Test] - public async Task MockFileInfo_LastAccessTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + await That(newcontents).IsEqualTo("ABCDEtext content"); + } + + [Test] + public async Task MockFileInfo_Encrypt_ShouldSetEncryptedAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.LastAccessTimeUtc; + fileInfo.Encrypt(); - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + await That(fileData.Attributes & FileAttributes.Encrypted).IsEqualTo(FileAttributes.Encrypted); + } - [Test] - public async Task MockFileInfo_LastAccessTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() + [Test] + public async Task MockFileInfo_Decrypt_ShouldUnsetEncryptedAttributeOfFileInMemoryFileSystem() + { + var fileData = new MockFileData("Demo text content"); + var fileSystem = new MockFileSystem(new Dictionary { - var lastAccessTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + fileInfo.Encrypt(); - var newUtcTime = DateTime.UtcNow; - fileInfo.LastAccessTimeUtc = newUtcTime; + fileInfo.Decrypt(); - await That(fileInfo.LastAccessTimeUtc).IsEqualTo(newUtcTime); - } + await That(fileData.Attributes & FileAttributes.Encrypted).IsNotEqualTo(FileAttributes.Encrypted); + } - [Test] - public async Task MockFileInfo_LastWriteTime_ShouldReturnDefaultTimeForNonExistingFile() + [Test] + public async Task MockFileInfo_LastAccessTimeUtc_ShouldReturnLastAccessTimeUtcOfFileInMemoryFileSystem() + { + var lastAccessTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.LastWriteTime; + var result = fileInfo.LastAccessTimeUtc; - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); - } + await That(result).IsEqualTo(lastAccessTime.ToUniversalTime()); + } - [Test] - public async Task MockFileInfo_LastWriteTimeUtc_ShouldReturnLastWriteTimeUtcOfFileInMemoryFileSystem() - { - var lastWriteTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + [Test] + public async Task MockFileInfo_LastAccessTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); - var result = fileInfo.LastWriteTimeUtc; + var result = fileInfo.LastAccessTimeUtc; - await That(result).IsEqualTo(lastWriteTime.ToUniversalTime()); - } + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } - [Test] - public async Task MockFileInfo_LastWriteTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + [Test] + public async Task MockFileInfo_LastAccessTimeUtc_ShouldSetCreationTimeUtcOfFileInMemoryFileSystem() + { + var lastAccessTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastAccessTime = lastAccessTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.LastWriteTimeUtc; + var newUtcTime = DateTime.UtcNow; + fileInfo.LastAccessTimeUtc = newUtcTime; - await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); - } + await That(fileInfo.LastAccessTimeUtc).IsEqualTo(newUtcTime); + } - [Test] - public async Task MockFileInfo_LastWriteTimeUtc_ShouldSetLastWriteTimeUtcOfFileInMemoryFileSystem() - { - var lastWriteTime = DateTime.Now.AddHours(-4); - var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\a.txt"), fileData } - }); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + [Test] + public async Task MockFileInfo_LastWriteTime_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); - var newUtcTime = DateTime.UtcNow; - fileInfo.LastWriteTimeUtc = newUtcTime; + var result = fileInfo.LastWriteTime; - await That(fileInfo.LastWriteTimeUtc).IsEqualTo(newUtcTime); - } + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.LocalDateTime); + } - [Test] - public async Task MockFileInfo_GetExtension_ShouldReturnExtension() + [Test] + public async Task MockFileInfo_LastWriteTimeUtc_ShouldReturnLastWriteTimeUtcOfFileInMemoryFileSystem() + { + var lastWriteTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary()); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.Extension; + var result = fileInfo.LastWriteTimeUtc; - await That(result).IsEqualTo(".txt"); - } + await That(result).IsEqualTo(lastWriteTime.ToUniversalTime()); + } - [Test] - public async Task MockFileInfo_GetExtensionWithoutExtension_ShouldReturnEmptyString() - { - var fileSystem = new MockFileSystem(new Dictionary()); - var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a")); + [Test] + public async Task MockFileInfo_LastWriteTimeUtc_ShouldReturnDefaultTimeForNonExistingFile() + { + var fileSystem = new MockFileSystem(); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\non\existing\file.txt")); - var result = fileInfo.Extension; + var result = fileInfo.LastWriteTimeUtc; - await That(result).IsEmpty(); - } + await That(result).IsEqualTo(MockFileData.DefaultDateTimeOffset.UtcDateTime); + } - [Test] - public async Task MockFileInfo_GetDirectoryName_ShouldReturnCompleteDirectoryPath() + [Test] + public async Task MockFileInfo_LastWriteTimeUtc_ShouldSetLastWriteTimeUtcOfFileInMemoryFileSystem() + { + var lastWriteTime = DateTime.Now.AddHours(-4); + var fileData = new MockFileData("Demo text content") { LastWriteTime = lastWriteTime }; + var fileSystem = new MockFileSystem(new Dictionary { - var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); + { XFS.Path(@"c:\a.txt"), fileData } + }); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.DirectoryName; + var newUtcTime = DateTime.UtcNow; + fileInfo.LastWriteTimeUtc = newUtcTime; - await That(result).IsEqualTo(XFS.Path(@"c:\temp\level1\level2")); - } + await That(fileInfo.LastWriteTimeUtc).IsEqualTo(newUtcTime); + } - [Test] - public async Task MockFileInfo_GetDirectory_ShouldReturnDirectoryInfoWithCorrectPath() - { - var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); + [Test] + public async Task MockFileInfo_GetExtension_ShouldReturnExtension() + { + var fileSystem = new MockFileSystem(new Dictionary()); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a.txt")); - var result = fileInfo.Directory; + var result = fileInfo.Extension; - await That(result.FullName).IsEqualTo(XFS.Path(@"c:\temp\level1\level2")); - } + await That(result).IsEqualTo(".txt"); + } - [Test] - public async Task MockFileInfo_OpenRead_ShouldReturnByteContentOfFile() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(new byte[] { 1, 2 })); - var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + [Test] + public async Task MockFileInfo_GetExtensionWithoutExtension_ShouldReturnEmptyString() + { + var fileSystem = new MockFileSystem(new Dictionary()); + var fileInfo = new MockFileInfo(fileSystem, XFS.Path(@"c:\a")); - byte[] result = new byte[2]; - using (var stream = fileInfo.OpenRead()) - { -#pragma warning disable CA2022 - // ReSharper disable once MustUseReturnValue - stream.Read(result, 0, 2); -#pragma warning restore CA2022 - } + var result = fileInfo.Extension; - await That(result).IsEqualTo(new byte[] { 1, 2 }); - } + await That(result).IsEmpty(); + } - [Test] - public async Task MockFileInfo_OpenText_ShouldReturnStringContentOfFile() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); - var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + [Test] + public async Task MockFileInfo_GetDirectoryName_ShouldReturnCompleteDirectoryPath() + { + var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); - string result; - using (var streamReader = fileInfo.OpenText()) - { - result = streamReader.ReadToEnd(); - } + var result = fileInfo.DirectoryName; - await That(result).IsEqualTo(@"line 1\r\nline 2"); - } + await That(result).IsEqualTo(XFS.Path(@"c:\temp\level1\level2")); + } - [Test] - public async Task MockFileInfo_MoveTo_NonExistentDestination_ShouldUpdateFileInfoDirectoryAndFullName() - { - var fileSystem = new MockFileSystem(); - var sourcePath = XFS.Path(@"c:\temp\file.txt"); - var destinationFolder = XFS.Path(@"c:\temp2"); - var destinationPath = XFS.Path(destinationFolder + @"\file.txt"); - fileSystem.AddFile(sourcePath, new MockFileData("1")); - var fileInfo = fileSystem.FileInfo.New(sourcePath); - fileSystem.AddDirectory(destinationFolder); + [Test] + public async Task MockFileInfo_GetDirectory_ShouldReturnDirectoryInfoWithCorrectPath() + { + var fileInfo = new MockFileInfo(new MockFileSystem(), XFS.Path(@"c:\temp\level1\level2\file.txt")); - fileInfo.MoveTo(destinationPath); + var result = fileInfo.Directory; - await That(fileInfo.DirectoryName).IsEqualTo(destinationFolder); - await That(fileInfo.FullName).IsEqualTo(destinationPath); - } + await That(result.FullName).IsEqualTo(XFS.Path(@"c:\temp\level1\level2")); + } - [Test] - public async Task MockFileInfo_MoveTo_NonExistentDestinationFolder_ShouldThrowDirectoryNotFoundException() - { - var fileSystem = new MockFileSystem(); - var sourcePath = XFS.Path(@"c:\temp\file.txt"); - var destinationPath = XFS.Path(@"c:\temp2\file.txt"); - fileSystem.AddFile(sourcePath, new MockFileData("1")); - var fileInfo = fileSystem.FileInfo.New(sourcePath); + [Test] + public async Task MockFileInfo_OpenRead_ShouldReturnByteContentOfFile() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(new byte[] { 1, 2 })); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); - await That(() => fileInfo.MoveTo(destinationPath)).Throws(); + byte[] result = new byte[2]; + using (var stream = fileInfo.OpenRead()) + { +#pragma warning disable CA2022 + // ReSharper disable once MustUseReturnValue + stream.Read(result, 0, 2); +#pragma warning restore CA2022 } - [Test] - public async Task MockFileInfo_MoveTo_ExistingDestination_ShouldThrowExceptionAboutFileAlreadyExisting() - { - var fileSystem = new MockFileSystem(); - var sourcePath = XFS.Path(@"c:\temp\file.txt"); - var destinationPath = XFS.Path(@"c:\temp2\file.txt"); - fileSystem.AddFile(sourcePath, new MockFileData("1")); - var fileInfo = fileSystem.FileInfo.New(sourcePath); - fileSystem.AddFile(destinationPath, new MockFileData("2")); + await That(result).IsEqualTo(new byte[] { 1, 2 }); + } - await That(() => fileInfo.MoveTo(destinationPath)).Throws(); - } + [Test] + public async Task MockFileInfo_OpenText_ShouldReturnStringContentOfFile() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); - [Test] - public async Task MockFileInfo_MoveTo_SameSourceAndTargetIsANoOp() + string result; + using (var streamReader = fileInfo.OpenText()) { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); - var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); - string destination = XFS.Path(XFS.Path(@"c:\temp\file.txt")); + result = streamReader.ReadToEnd(); + } - fileInfo.MoveTo(destination); + await That(result).IsEqualTo(@"line 1\r\nline 2"); + } - await That(fileInfo.FullName).IsEqualTo(destination); - await That(fileInfo.Exists).IsTrue(); - } + [Test] + public async Task MockFileInfo_MoveTo_NonExistentDestination_ShouldUpdateFileInfoDirectoryAndFullName() + { + var fileSystem = new MockFileSystem(); + var sourcePath = XFS.Path(@"c:\temp\file.txt"); + var destinationFolder = XFS.Path(@"c:\temp2"); + var destinationPath = XFS.Path(destinationFolder + @"\file.txt"); + fileSystem.AddFile(sourcePath, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(sourcePath); + fileSystem.AddDirectory(destinationFolder); + + fileInfo.MoveTo(destinationPath); + + await That(fileInfo.DirectoryName).IsEqualTo(destinationFolder); + await That(fileInfo.FullName).IsEqualTo(destinationPath); + } - [Test] - public async Task MockFileInfo_MoveTo_SameSourceAndTargetThrowsExceptionIfSourceDoesNotExist() - { - var fileSystem = new MockFileSystem(); - var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); - string destination = XFS.Path(XFS.Path(@"c:\temp\file.txt")); + [Test] + public async Task MockFileInfo_MoveTo_NonExistentDestinationFolder_ShouldThrowDirectoryNotFoundException() + { + var fileSystem = new MockFileSystem(); + var sourcePath = XFS.Path(@"c:\temp\file.txt"); + var destinationPath = XFS.Path(@"c:\temp2\file.txt"); + fileSystem.AddFile(sourcePath, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(sourcePath); - Action action = () => fileInfo.MoveTo(destination); + await That(() => fileInfo.MoveTo(destinationPath)).Throws(); + } - await That(action).Throws(); - } + [Test] + public async Task MockFileInfo_MoveTo_ExistingDestination_ShouldThrowExceptionAboutFileAlreadyExisting() + { + var fileSystem = new MockFileSystem(); + var sourcePath = XFS.Path(@"c:\temp\file.txt"); + var destinationPath = XFS.Path(@"c:\temp2\file.txt"); + fileSystem.AddFile(sourcePath, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(sourcePath); + fileSystem.AddFile(destinationPath, new MockFileData("2")); + + await That(() => fileInfo.MoveTo(destinationPath)).Throws(); + } - [Test] - public async Task MockFileInfo_MoveTo_ThrowsExceptionIfSourceDoesNotExist() - { - var fileSystem = new MockFileSystem(); - var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); - string destination = XFS.Path(XFS.Path(@"c:\temp\file2.txt")); + [Test] + public async Task MockFileInfo_MoveTo_SameSourceAndTargetIsANoOp() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"c:\temp\file.txt"), new MockFileData(@"line 1\r\nline 2")); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file.txt")); - Action action = () => fileInfo.MoveTo(destination); + fileInfo.MoveTo(destination); - await That(action).Throws(); - } + await That(fileInfo.FullName).IsEqualTo(destination); + await That(fileInfo.Exists).IsTrue(); + } + [Test] + public async Task MockFileInfo_MoveTo_SameSourceAndTargetThrowsExceptionIfSourceDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file.txt")); + Action action = () => fileInfo.MoveTo(destination); -#if FEATURE_FILE_MOVE_WITH_OVERWRITE - [Test] - public async Task MockFileInfo_MoveToWithOverwrite_ShouldSucceedWhenTargetAlreadyExists() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent)}, - {destFilePath, new MockFileData(sourceFileContent)} - }); + await That(action).Throws(); + } - fileSystem.FileInfo.New(sourceFilePath).MoveTo(destFilePath, overwrite: true); + [Test] + public async Task MockFileInfo_MoveTo_ThrowsExceptionIfSourceDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file2.txt")); - await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent); - } -#endif + Action action = () => fileInfo.MoveTo(destination); - [Test] - public async Task MockFileInfo_MoveToOnlyCaseChanging_ShouldSucceed() - { - string sourceFilePath = XFS.Path(@"c:\temp\file.txt"); - string destFilePath = XFS.Path(@"c:\temp\FILE.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData("1")}, - }); + await That(action).Throws(); + } - var fileInfo = fileSystem.FileInfo.New(sourceFilePath); - fileInfo.MoveTo(destFilePath); - await That(fileInfo.FullName).IsEqualTo(destFilePath); - await That(fileInfo.Exists).IsTrue(); - } - [Test] - public async Task MockFileInfo_CopyTo_ThrowsExceptionIfSourceDoesNotExist() +#if FEATURE_FILE_MOVE_WITH_OVERWRITE + [Test] + public async Task MockFileInfo_MoveToWithOverwrite_ShouldSucceedWhenTargetAlreadyExists() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(); - var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); - string destination = XFS.Path(XFS.Path(@"c:\temp\file2.txt")); + {sourceFilePath, new MockFileData(sourceFileContent)}, + {destFilePath, new MockFileData(sourceFileContent)} + }); - Action action = () => fileInfo.CopyTo(destination); + fileSystem.FileInfo.New(sourceFilePath).MoveTo(destFilePath, overwrite: true); - await That(action).Throws(); - } + await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent); + } +#endif - [TestCase(@"..\..\..\c.txt")] - [TestCase(@"c:\a\b\c.txt")] - [TestCase(@"c:\a\c.txt")] - [TestCase(@"c:\c.txt")] - public async Task MockFileInfo_ToString_ShouldReturnOriginalFilePath(string path) + [Test] + public async Task MockFileInfo_MoveToOnlyCaseChanging_ShouldSucceed() + { + string sourceFilePath = XFS.Path(@"c:\temp\file.txt"); + string destFilePath = XFS.Path(@"c:\temp\FILE.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - //Arrange - var filePath = XFS.Path(path); - - //Act - var mockFileInfo = new MockFileInfo(new MockFileSystem(), filePath); + {sourceFilePath, new MockFileData("1")}, + }); - //Assert - await That(mockFileInfo.ToString()).IsEqualTo(filePath); - } + var fileInfo = fileSystem.FileInfo.New(sourceFilePath); + fileInfo.MoveTo(destFilePath); + await That(fileInfo.FullName).IsEqualTo(destFilePath); + await That(fileInfo.Exists).IsTrue(); + } - /// - /// Normalize, tested with Path.GetFullPath and new FileInfo().FullName; - /// - [TestCaseSource(nameof(New_Paths_NormalizePaths_Cases))] - public async Task New_Paths_NormalizePaths(string input, string expected) - { - // Arrange - var mockFs = new MockFileSystem(); + [Test] + public async Task MockFileInfo_CopyTo_ThrowsExceptionIfSourceDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var fileInfo = fileSystem.FileInfo.New(XFS.Path(@"c:\temp\file.txt")); + string destination = XFS.Path(XFS.Path(@"c:\temp\file2.txt")); - // Act - var mockFileInfo = mockFs.FileInfo.New(input); - var result = mockFileInfo.FullName; + Action action = () => fileInfo.CopyTo(destination); - // Assert - await That(result).IsEqualTo(expected); - } + await That(action).Throws(); + } - public static IEnumerable New_Paths_NormalizePaths_Cases - { - get - { - yield return new[] { XFS.Path(@"c:\top\..\most\file"), XFS.Path(@"c:\most\file") }; - yield return new[] { XFS.Path(@"c:\top\..\most\..\dir\file"), XFS.Path(@"c:\dir\file") }; - yield return new[] { XFS.Path(@"\file"), XFS.Path(@"C:\file") }; - yield return new[] { XFS.Path(@"c:\top\../..\most\file"), XFS.Path(@"c:\most\file") }; - } - } + [TestCase(@"..\..\..\c.txt")] + [TestCase(@"c:\a\b\c.txt")] + [TestCase(@"c:\a\c.txt")] + [TestCase(@"c:\c.txt")] + public async Task MockFileInfo_ToString_ShouldReturnOriginalFilePath(string path) + { + //Arrange + var filePath = XFS.Path(path); - [Test] - public async Task MockFileInfo_Replace_ShouldReplaceFileContents() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - fileSystem.AddFile(path2, new MockFileData("2")); - var fileInfo1 = fileSystem.FileInfo.New(path1); - var fileInfo2 = fileSystem.FileInfo.New(path2); + //Act + var mockFileInfo = new MockFileInfo(new MockFileSystem(), filePath); - // Act - fileInfo1.Replace(path2, null); + //Assert + await That(mockFileInfo.ToString()).IsEqualTo(filePath); + } - await That(fileInfo2.OpenText().ReadToEnd()).IsEqualTo("1"); - } - [Test] - public async Task MockFileInfo_Replace_ShouldCreateBackup() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - var path3 = XFS.Path(@"c:\temp\file3.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - fileSystem.AddFile(path2, new MockFileData("2")); - var fileInfo1 = fileSystem.FileInfo.New(path1); - var fileInfo3 = fileSystem.FileInfo.New(path3); + /// + /// Normalize, tested with Path.GetFullPath and new FileInfo().FullName; + /// + [TestCaseSource(nameof(New_Paths_NormalizePaths_Cases))] + public async Task New_Paths_NormalizePaths(string input, string expected) + { + // Arrange + var mockFs = new MockFileSystem(); - // Act - fileInfo1.Replace(path2, path3); + // Act + var mockFileInfo = mockFs.FileInfo.New(input); + var result = mockFileInfo.FullName; - await That(fileInfo3.OpenText().ReadToEnd()).IsEqualTo("2"); - } + // Assert + await That(result).IsEqualTo(expected); + } - [Test] - public async Task MockFileInfo_Replace_ShouldThrowIfDirectoryOfBackupPathDoesNotExist() + public static IEnumerable New_Paths_NormalizePaths_Cases + { + get { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - var path3 = XFS.Path(@"c:\temp\subdirectory\file3.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - fileSystem.AddFile(path2, new MockFileData("2")); - var fileInfo1 = fileSystem.FileInfo.New(path1); - - // Act - await That(() => fileInfo1.Replace(path2, path3)).Throws(); + yield return new[] { XFS.Path(@"c:\top\..\most\file"), XFS.Path(@"c:\most\file") }; + yield return new[] { XFS.Path(@"c:\top\..\most\..\dir\file"), XFS.Path(@"c:\dir\file") }; + yield return new[] { XFS.Path(@"\file"), XFS.Path(@"C:\file") }; + yield return new[] { XFS.Path(@"c:\top\../..\most\file"), XFS.Path(@"c:\most\file") }; } + } - [Test] - public async Task MockFileInfo_Replace_ShouldReturnDestinationFileInfo() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - fileSystem.AddFile(path2, new MockFileData("2")); - var fileInfo1 = fileSystem.FileInfo.New(path1); - var fileInfo2 = fileSystem.FileInfo.New(path2); - - // Act - var result = fileInfo1.Replace(path2, null); + [Test] + public async Task MockFileInfo_Replace_ShouldReplaceFileContents() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + var fileInfo2 = fileSystem.FileInfo.New(path2); + + // Act + fileInfo1.Replace(path2, null); + + await That(fileInfo2.OpenText().ReadToEnd()).IsEqualTo("1"); + } - await That(result.FullName).IsEqualTo(fileInfo2.FullName); - } + [Test] + public async Task MockFileInfo_Replace_ShouldCreateBackup() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + var fileInfo3 = fileSystem.FileInfo.New(path3); + + // Act + fileInfo1.Replace(path2, path3); + + await That(fileInfo3.OpenText().ReadToEnd()).IsEqualTo("2"); + } - [Test] - public async Task MockFileInfo_Replace_ShouldThrowIfSourceFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - fileSystem.AddFile(path2, new MockFileData("1")); - var fileInfo = fileSystem.FileInfo.New(path1); + [Test] + public async Task MockFileInfo_Replace_ShouldThrowIfDirectoryOfBackupPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\subdirectory\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + + // Act + await That(() => fileInfo1.Replace(path2, path3)).Throws(); + } - await That(() => fileInfo.Replace(path2, null)).Throws(); - } + [Test] + public async Task MockFileInfo_Replace_ShouldReturnDestinationFileInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + var fileInfo1 = fileSystem.FileInfo.New(path1); + var fileInfo2 = fileSystem.FileInfo.New(path2); + + // Act + var result = fileInfo1.Replace(path2, null); + + await That(result.FullName).IsEqualTo(fileInfo2.FullName); + } - [Test] - public async Task MockFileInfo_Replace_ShouldThrowIfDestinationFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - var fileInfo = fileSystem.FileInfo.New(path1); + [Test] + public async Task MockFileInfo_Replace_ShouldThrowIfSourceFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path2, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(path1); + + await That(() => fileInfo.Replace(path2, null)).Throws(); + } - await That(() => fileInfo.Replace(path2, null)).Throws(); - } + [Test] + public async Task MockFileInfo_Replace_ShouldThrowIfDestinationFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + var fileInfo = fileSystem.FileInfo.New(path1); + + await That(() => fileInfo.Replace(path2, null)).Throws(); + } - [Test] - public async Task MockFileInfo_Exists_ShouldReturnCachedData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var fileInfo = fileSystem.FileInfo.New(path1); + [Test] + public async Task MockFileInfo_Exists_ShouldReturnCachedData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var fileInfo = fileSystem.FileInfo.New(path1); - // Act - fileSystem.AddFile(path1, new MockFileData("1")); + // Act + fileSystem.AddFile(path1, new MockFileData("1")); - // Assert - await That(fileInfo.Exists).IsFalse(); - } + // Assert + await That(fileInfo.Exists).IsFalse(); + } - [Test] - public async Task MockFileInfo_Exists_ShouldUpdateCachedDataOnRefresh() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var fileInfo = fileSystem.FileInfo.New(path1); + [Test] + public async Task MockFileInfo_Exists_ShouldUpdateCachedDataOnRefresh() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var fileInfo = fileSystem.FileInfo.New(path1); - // Act - fileSystem.AddFile(path1, new MockFileData("1")); - fileInfo.Refresh(); + // Act + fileSystem.AddFile(path1, new MockFileData("1")); + fileInfo.Refresh(); - // Assert - await That(fileInfo.Exists).IsTrue(); - } + // Assert + await That(fileInfo.Exists).IsTrue(); + } - [Test] - public async Task MockFileInfo_Create_ShouldUpdateCachedDataAndReturnTrueForExists() - { - IFileSystem fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\temp\file1.txt"); - IFileInfo fileInfo = fileSystem.FileInfo.New(path); + [Test] + public async Task MockFileInfo_Create_ShouldUpdateCachedDataAndReturnTrueForExists() + { + IFileSystem fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\temp\file1.txt"); + IFileInfo fileInfo = fileSystem.FileInfo.New(path); - // Act - fileInfo.Create().Dispose(); + // Act + fileInfo.Create().Dispose(); - // Assert - var result = fileInfo.Exists; - await That(result).IsTrue(); - } + // Assert + var result = fileInfo.Exists; + await That(result).IsTrue(); + } - [Test] - public async Task MockFileInfo_CreateText_ShouldUpdateCachedDataAndReturnTrueForExists() - { - IFileSystem fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\temp\file1.txt"); - IFileInfo fileInfo = fileSystem.FileInfo.New(path); + [Test] + public async Task MockFileInfo_CreateText_ShouldUpdateCachedDataAndReturnTrueForExists() + { + IFileSystem fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\temp\file1.txt"); + IFileInfo fileInfo = fileSystem.FileInfo.New(path); - // Act - fileInfo.CreateText().Dispose(); + // Act + fileInfo.CreateText().Dispose(); - // Assert - await That(fileInfo.Exists).IsTrue(); - } + // Assert + await That(fileInfo.Exists).IsTrue(); + } - [Test] - public async Task MockFileInfo_Delete_ShouldUpdateCachedDataAndReturnFalseForExists() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\temp\file1.txt"); - IFileInfo fileInfo = fileSystem.FileInfo.New(path); + [Test] + public async Task MockFileInfo_Delete_ShouldUpdateCachedDataAndReturnFalseForExists() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\temp\file1.txt"); + IFileInfo fileInfo = fileSystem.FileInfo.New(path); - // Act - fileInfo.Delete(); + // Act + fileInfo.Delete(); - // Assert - await That(fileInfo.Exists).IsFalse(); - } + // Assert + await That(fileInfo.Exists).IsFalse(); + } - [Test] - public async Task MockFileInfo_Delete_ShouldThrowIfFileAccessShareHasNoWriteOrDeleteAccess() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile( - @"c:\bar\foo.txt", - new MockFileData("text contents") { AllowedFileShare = FileShare.None }); + [Test] + public async Task MockFileInfo_Delete_ShouldThrowIfFileAccessShareHasNoWriteOrDeleteAccess() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile( + @"c:\bar\foo.txt", + new MockFileData("text contents") { AllowedFileShare = FileShare.None }); - var fi = fileSystem.FileInfo.New(@"c:\bar\foo.txt"); + var fi = fileSystem.FileInfo.New(@"c:\bar\foo.txt"); - await That(() => fi.Delete()).Throws(); - } + await That(() => fi.Delete()).Throws(); + } - [Test] - public async Task MockFileInfo_LastAccessTimeUtcWithUnspecifiedDateTimeKind_ShouldSetLastAccessTimeUtcOfFileInFileSystem() + [Test] + public async Task MockFileInfo_LastAccessTimeUtcWithUnspecifiedDateTimeKind_ShouldSetLastAccessTimeUtcOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") { - var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(@"c:\test"); - fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); - var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") - { - LastAccessTimeUtc = date - }; + LastAccessTimeUtc = date + }; - await That(fileInfo.LastAccessTimeUtc).IsEqualTo(date); - await That(fileInfo.LastAccessTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); - } + await That(fileInfo.LastAccessTimeUtc).IsEqualTo(date); + await That(fileInfo.LastAccessTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } - [Test] - public async Task MockFileInfo_LastAccessTimeWithUnspecifiedDateTimeKind_ShouldSetLastAccessTimeOfFileInFileSystem() + [Test] + public async Task MockFileInfo_LastAccessTimeWithUnspecifiedDateTimeKind_ShouldSetLastAccessTimeOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") { - var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(@"c:\test"); - fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); - var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") - { - LastAccessTime = date - }; + LastAccessTime = date + }; - await That(fileInfo.LastAccessTime).IsEqualTo(date); - await That(fileInfo.LastAccessTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); - } + await That(fileInfo.LastAccessTime).IsEqualTo(date); + await That(fileInfo.LastAccessTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } - [Test] - public async Task MockFileInfo_CreationTimeUtcWithUnspecifiedDateTimeKind_ShouldSetCreationTimeUtcOfFileInFileSystem() + [Test] + public async Task MockFileInfo_CreationTimeUtcWithUnspecifiedDateTimeKind_ShouldSetCreationTimeUtcOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") { - var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(@"c:\test"); - fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); - var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") - { - CreationTimeUtc = date - }; + CreationTimeUtc = date + }; - await That(fileInfo.CreationTimeUtc).IsEqualTo(date); - await That(fileInfo.CreationTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); - } + await That(fileInfo.CreationTimeUtc).IsEqualTo(date); + await That(fileInfo.CreationTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } - [Test] - public async Task MockFileInfo_CreationTimeWithUnspecifiedDateTimeKind_ShouldSetCreationTimeOfFileInFileSystem() + [Test] + public async Task MockFileInfo_CreationTimeWithUnspecifiedDateTimeKind_ShouldSetCreationTimeOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") { - var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(@"c:\test"); - fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); - var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") - { - CreationTime = date - }; + CreationTime = date + }; - await That(fileInfo.CreationTime).IsEqualTo(date); - await That(fileInfo.CreationTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); - } + await That(fileInfo.CreationTime).IsEqualTo(date); + await That(fileInfo.CreationTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } - [Test] - public async Task MockFileInfo_LastWriteTimeUtcWithUnspecifiedDateTimeKind_ShouldSetLastWriteTimeUtcOfFileInFileSystem() + [Test] + public async Task MockFileInfo_LastWriteTimeUtcWithUnspecifiedDateTimeKind_ShouldSetLastWriteTimeUtcOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") { - var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(@"c:\test"); - fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); - var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") - { - LastWriteTimeUtc = date - }; + LastWriteTimeUtc = date + }; - await That(fileInfo.LastWriteTimeUtc).IsEqualTo(date); - await That(fileInfo.LastWriteTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); - } + await That(fileInfo.LastWriteTimeUtc).IsEqualTo(date); + await That(fileInfo.LastWriteTimeUtc.Kind).IsNotEqualTo(DateTimeKind.Unspecified); + } - [Test] - public async Task MockFileInfo_LastWriteTimeWithUnspecifiedDateTimeKind_ShouldSetLastWriteTimeOfFileInFileSystem() + [Test] + public async Task MockFileInfo_LastWriteTimeWithUnspecifiedDateTimeKind_ShouldSetLastWriteTimeOfFileInFileSystem() + { + var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); + var fileSystem = new MockFileSystem(); + fileSystem.Directory.CreateDirectory(@"c:\test"); + fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); + var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") { - var date = DateTime.SpecifyKind(DateTime.Now.AddHours(-4), DateTimeKind.Unspecified); - var fileSystem = new MockFileSystem(); - fileSystem.Directory.CreateDirectory(@"c:\test"); - fileSystem.File.WriteAllText(@"c:\test\a.txt", "Demo text content"); - var fileInfo = new MockFileInfo(fileSystem, @"c:\test\a.txt") - { - LastWriteTime = date - }; + LastWriteTime = date + }; - await That(fileInfo.LastWriteTime).IsEqualTo(date); - await That(fileInfo.LastWriteTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); - } + await That(fileInfo.LastWriteTime).IsEqualTo(date); + await That(fileInfo.LastWriteTime.Kind).IsNotEqualTo(DateTimeKind.Unspecified); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs index 5349a3609..f54d74274 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileLockTests.cs @@ -1,191 +1,190 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; - using NUnit.Framework; - using NUnit.Framework.Constraints; - using XFS = MockUnixSupport; - class MockFileLockTests +using NUnit.Framework; +using NUnit.Framework.Constraints; +using XFS = MockUnixSupport; +class MockFileLockTests +{ + [Test] + public async Task MockFile_Lock_FileShareNoneThrows() { - [Test] - public async Task MockFile_Lock_FileShareNoneThrows() + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).Throws(); - } - [Test] - public async Task MockFile_Lock_FileShareReadDoesNotThrowOnRead() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).Throws(); + } + [Test] + public async Task MockFile_Lock_FileShareReadDoesNotThrowOnRead() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Read }} - }); - - await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).DoesNotThrow(); - } - [Test] - public async Task MockFile_Lock_FileShareReadThrowsOnWrite() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Read }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).DoesNotThrow(); + } + [Test] + public async Task MockFile_Lock_FileShareReadThrowsOnWrite() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Read }} - }); - - await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Write, FileShare.Read)).Throws(); - } - [Test] - public async Task MockFile_Lock_FileShareWriteThrowsOnRead() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Read }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Write, FileShare.Read)).Throws(); + } + [Test] + public async Task MockFile_Lock_FileShareWriteThrowsOnRead() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Write }} - }); - - await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).Throws(); - } - [Test] - public async Task MockFile_Lock_FileShareWriteDoesNotThrowOnWrite() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Write }} + }); + + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)).Throws(); + } + [Test] + public async Task MockFile_Lock_FileShareWriteDoesNotThrowOnWrite() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Write }} - }); + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Write }} + }); - await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Write, FileShare.Read)).DoesNotThrow(); - } + await That(() => filesystem.File.Open(filepath, FileMode.Open, FileAccess.Write, FileShare.Read)).DoesNotThrow(); + } - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsOnOpenRead() - { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.OpenRead(filepath)).Throws(); - await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); - } - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsOnWriteAllLines() + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnOpenRead() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.WriteAllLines(filepath, new string[] { "hello", "world" })).Throws(); - await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); - } - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllLines() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.OpenRead(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnWriteAllLines() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.ReadAllLines(filepath)).Throws(); - await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); - } - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllText() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.WriteAllLines(filepath, new string[] { "hello", "world" })).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllLines() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.ReadAllText(filepath)).Throws(); - await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); - } - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllBytes() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.ReadAllLines(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllText() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.ReadAllBytes(filepath)).Throws(); - await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); - } - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsOnAppendLines() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.ReadAllText(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnReadAllBytes() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.AppendAllLines(filepath, new string[] { "hello", "world" })).Throws(); - await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); - } - - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsFileMove() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.ReadAllBytes(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsOnAppendLines() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - string target = XFS.Path(@"c:\something\does\notexist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.Move(filepath, target)).Throws(); - await That(exception.Message).IsEqualTo("The process cannot access the file because it is being used by another process."); - } - [Test] - public async Task MockFile_Lock_FileShareDeleteDoesNotThrowFileMove() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.AppendAllLines(filepath, new string[] { "hello", "world" })).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsFileMove() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + string target = XFS.Path(@"c:\something\does\notexist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - string target = XFS.Path(@"c:\something\does\notexist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Delete }} - }); - - await That(() => filesystem.File.Move(filepath, target)).DoesNotThrow(); - } - [Test] - public async Task MockFile_Lock_FileShareNoneThrowsDelete() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); + + var exception = await That(() => filesystem.File.Move(filepath, target)).Throws(); + await That(exception.Message).IsEqualTo("The process cannot access the file because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareDeleteDoesNotThrowFileMove() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + string target = XFS.Path(@"c:\something\does\notexist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} - }); - - var exception = await That(() => filesystem.File.Delete(filepath)).Throws(); - await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); - } - [Test] - public async Task MockFile_Lock_FileShareDeleteDoesNotThrowDelete() + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Delete }} + }); + + await That(() => filesystem.File.Move(filepath, target)).DoesNotThrow(); + } + [Test] + public async Task MockFile_Lock_FileShareNoneThrowsDelete() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Delete }} - }); + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.None }} + }); - await That(() => filesystem.File.Delete(filepath)).DoesNotThrow(); - } + var exception = await That(() => filesystem.File.Delete(filepath)).Throws(); + await That(exception.Message).IsEqualTo($"The process cannot access the file '{filepath}' because it is being used by another process."); + } + [Test] + public async Task MockFile_Lock_FileShareDeleteDoesNotThrowDelete() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary + { + { filepath, new MockFileData("I'm here") { AllowedFileShare = FileShare.Delete }} + }); - private static IResolveConstraint IOException() => Is.TypeOf().And.Property("HResult").EqualTo(unchecked((int)0x80070020)); + await That(() => filesystem.File.Delete(filepath)).DoesNotThrow(); } -} + + private static IResolveConstraint IOException() => Is.TypeOf().And.Property("HResult").EqualTo(unchecked((int)0x80070020)); +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileMoveTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileMoveTests.cs index 258e182db..54a8881c7 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileMoveTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileMoveTests.cs @@ -1,456 +1,455 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - using Linq; - using NUnit.Framework; - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; +using Linq; +using NUnit.Framework; +using XFS = MockUnixSupport; - public class MockFileMoveTests +public class MockFileMoveTests +{ + [Test] + public async Task MockFile_Move_ShouldMoveFileWithinMemoryFileSystem() { - [Test] - public async Task MockFile_Move_ShouldMoveFileWithinMemoryFileSystem() + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + var fileSystem = new MockFileSystem(new Dictionary { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent)}, - {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} - }); + {sourceFilePath, new MockFileData(sourceFileContent)}, + {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} + }); - string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); - fileSystem.File.Move(sourceFilePath, destFilePath); + fileSystem.File.Move(sourceFilePath, destFilePath); - await That(fileSystem.FileExists(destFilePath)).IsTrue(); - await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); - await That(fileSystem.FileExists(sourceFilePath)).IsFalse(); - } + await That(fileSystem.FileExists(destFilePath)).IsTrue(); + await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); + await That(fileSystem.FileExists(sourceFilePath)).IsFalse(); + } - [Test] - public async Task MockFile_Move_WithReadOnlyAttribute_ShouldThrowUnauthorizedAccessExceptionAndNotMoveFile() - { - var sourceFilePath = @"c:\foo.txt"; - var destFilePath = @"c:\bar.txt"; - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText(sourceFilePath, "this is some content"); - fileSystem.File.SetAttributes(sourceFilePath, FileAttributes.ReadOnly); + [Test] + public async Task MockFile_Move_WithReadOnlyAttribute_ShouldThrowUnauthorizedAccessExceptionAndNotMoveFile() + { + var sourceFilePath = @"c:\foo.txt"; + var destFilePath = @"c:\bar.txt"; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText(sourceFilePath, "this is some content"); + fileSystem.File.SetAttributes(sourceFilePath, FileAttributes.ReadOnly); - await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(fileSystem.File.Exists(sourceFilePath)).IsEqualTo(true); - await That(fileSystem.File.Exists(destFilePath)).IsEqualTo(false); - } + await That(fileSystem.File.Exists(sourceFilePath)).IsEqualTo(true); + await That(fileSystem.File.Exists(destFilePath)).IsEqualTo(false); + } - [Test] - public async Task MockFile_Move_SameSourceAndTargetIsANoOp() + [Test] + public async Task MockFile_Move_SameSourceAndTargetIsANoOp() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + var fileSystem = new MockFileSystem(new Dictionary { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent)}, - {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} - }); + {sourceFilePath, new MockFileData(sourceFileContent)}, + {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} + }); - string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt"); + string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt"); - fileSystem.File.Move(sourceFilePath, destFilePath); + fileSystem.File.Move(sourceFilePath, destFilePath); - await That(fileSystem.FileExists(destFilePath)).IsTrue(); - await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); - } + await That(fileSystem.FileExists(destFilePath)).IsTrue(); + await That(fileSystem.GetFile(destFilePath).TextContents).IsEqualTo(sourceFileContent); + } - [Test] - public async Task MockFile_Move_ShouldThrowIOExceptionWhenTargetAlreadyExists() + [Test] + public async Task MockFile_Move_ShouldThrowIOExceptionWhenTargetAlreadyExists() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent)}, - {destFilePath, new MockFileData(sourceFileContent)} - }); - - var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - - await That(exception.Message).IsEqualTo("A file can not be created if it already exists."); - } + {sourceFilePath, new MockFileData(sourceFileContent)}, + {destFilePath, new MockFileData(sourceFileContent)} + }); + + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + + await That(exception.Message).IsEqualTo("A file can not be created if it already exists."); + } #if FEATURE_FILE_MOVE_WITH_OVERWRITE - [Test] - public async Task MockFile_MoveWithOverwrite_ShouldSucceedWhenTargetAlreadyExists() + [Test] + public async Task MockFile_MoveWithOverwrite_ShouldSucceedWhenTargetAlreadyExists() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent)}, - {destFilePath, new MockFileData(sourceFileContent)} - }); - - fileSystem.File.Move(sourceFilePath, destFilePath, overwrite: true); - - await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent); - } + {sourceFilePath, new MockFileData(sourceFileContent)}, + {destFilePath, new MockFileData(sourceFileContent)} + }); + + fileSystem.File.Move(sourceFilePath, destFilePath, overwrite: true); + + await That(fileSystem.File.ReadAllText(destFilePath)).IsEqualTo(sourceFileContent); + } #endif - [Test] - public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(null, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(null, destFilePath)).Throws(); - await That(exception.Message).StartsWith("File name cannot be null."); - } + await That(exception.Message).StartsWith("File name cannot be null."); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(null, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(null, destFilePath)).Throws(); - await That(exception.ParamName).IsEqualTo("sourceFileName"); - } + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceFileNameContainsInvalidChars_Message() - { - var destFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); - var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceFileNameContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) - { - var sourceFilePath = @"c:\something\demo.txt" + invalidChar; + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) + { + var sourceFilePath = @"c:\something\demo.txt" + invalidChar; - var exception = - await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourcePathContainsInvalidChars_Message() - { - var destFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourcePathContainsInvalidChars_Message() + { + var destFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var sourceFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) + { + var sourceFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; - var exception = - await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetPathContainsInvalidChars_Message() - { - var sourceFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetPathContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); - foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) - { - var destFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; + foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) + { + var destFilePath = @"c:\some" + invalidChar + @"thing\demo.txt"; - var exception = - await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetFileNameContainsInvalidChars_Message() - { - var sourceFilePath = @"c:\something\demo.txt"; - var fileSystem = new MockFileSystem(); - var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetFileNameContainsInvalidChars_Message() + { + var sourceFilePath = @"c:\something\demo.txt"; + var fileSystem = new MockFileSystem(); + var excludeChars = Shared.SpecialInvalidPathChars(fileSystem); - foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) - { - var destFilePath = @"c:\something\demo.txt" + invalidChar; + foreach (var invalidChar in fileSystem.Path.GetInvalidFileNameChars().Except(excludeChars)) + { + var destFilePath = @"c:\something\demo.txt" + invalidChar; - var exception = - await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path.") - .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); - } + await That(exception.Message).IsEqualTo("Illegal characters in path.") + .Because(string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidUseOfDriveSeparator() - { - var badSourcePath = @"C::\something\demo.txt"; - var destinationPath = @"C:\elsewhere\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidUseOfDriveSeparator() + { + var badSourcePath = @"C::\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Move(badSourcePath, destinationPath); + Action action = () => fileSystem.File.Move(badSourcePath, destinationPath); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidDriveLetter() - { - var badSourcePath = @"0:\something\demo.txt"; - var destinationPath = @"C:\elsewhere\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidDriveLetter() + { + var badSourcePath = @"0:\something\demo.txt"; + var destinationPath = @"C:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Move(badSourcePath, destinationPath); + Action action = () => fileSystem.File.Move(badSourcePath, destinationPath); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidUseOfDriveSeparator() - { - var sourcePath = @"C:\something\demo.txt"; - var badDestinationPath = @"C:\elsewhere:\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidUseOfDriveSeparator() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"C:\elsewhere:\demo.txt"; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Move(sourcePath, badDestinationPath); + Action action = () => fileSystem.File.Move(sourcePath, badDestinationPath); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidDriveLetter() - { - var sourcePath = @"C:\something\demo.txt"; - var badDestinationPath = @"^:\elsewhere\demo.txt"; - var fileSystem = new MockFileSystem(); + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFile_Move_ShouldThrowNotSupportedExceptionWhenDestinationPathContainsInvalidDriveLetter() + { + var sourcePath = @"C:\something\demo.txt"; + var badDestinationPath = @"^:\elsewhere\demo.txt"; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.Move(sourcePath, badDestinationPath); + Action action = () => fileSystem.File.Move(sourcePath, badDestinationPath); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_Message() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(string.Empty, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(string.Empty, destFilePath)).Throws(); - await That(exception.Message).StartsWith("Empty file name is not legal."); - } + await That(exception.Message).StartsWith("Empty file name is not legal."); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() - { - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsEmpty_ParamName() + { + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(string.Empty, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(string.Empty, destFilePath)).Throws(); - await That(exception.ParamName).IsEqualTo("sourceFileName"); - } + await That(exception.ParamName).IsEqualTo("sourceFileName"); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() - { - string sourceFilePath = " "; - string destFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenSourceIsStringOfBlanks() + { + string sourceFilePath = " "; + string destFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).StartsWith("The path is not of a legal form."); - } + await That(exception.Message).StartsWith("The path is not of a legal form."); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, null)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, null)).Throws(); - await That(exception.Message).StartsWith("File name cannot be null."); - } + await That(exception.Message).StartsWith("File name cannot be null."); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentNullExceptionWhenTargetIsNull_ParamName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, null)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, null)).Throws(); - await That(exception.ParamName).IsEqualTo("destFileName"); - } + await That(exception.ParamName).IsEqualTo("destFileName"); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = " "; - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsStringOfBlanks() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = " "; + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).StartsWith("The path is not of a legal form."); - } + await That(exception.Message).StartsWith("The path is not of a legal form."); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, string.Empty)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, string.Empty)).Throws(); - await That(exception.Message).StartsWith("Empty file name is not legal."); - } + await That(exception.Message).StartsWith("Empty file name is not legal."); + } - [Test] - public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_ParamName() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowArgumentExceptionWhenTargetIsEmpty_ParamName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, string.Empty)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, string.Empty)).Throws(); - await That(exception.ParamName).IsEqualTo("destFileName"); - } + await That(exception.ParamName).IsEqualTo("destFileName"); + } - [Test] - public async Task MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_Message() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = XFS.Path(@"c:\something\demo1.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = XFS.Path(@"c:\something\demo1.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.Message).IsEqualTo("Could not find file '" + XFS.Path("c:\\something\\demo.txt") + "'."); - } + await That(exception.Message).IsEqualTo("Could not find file '" + XFS.Path("c:\\something\\demo.txt") + "'."); + } - [Test] - public async Task MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_FileName() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = XFS.Path(@"c:\something\demo1.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_Move_ShouldThrowFileNotFoundExceptionWhenSourceDoesNotExist_FileName() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = XFS.Path(@"c:\something\demo1.txt"); + var fileSystem = new MockFileSystem(); - var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); + var exception = await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)).Throws(); - await That(exception.FileName).IsEqualTo(XFS.Path(@"c:\something\demo.txt")); - } + await That(exception.FileName).IsEqualTo(XFS.Path(@"c:\something\demo.txt")); + } - [Test] - public async Task MockFile_Move_ShouldThrowDirectoryNotFoundExceptionWhenSourcePathDoesNotExist_Message() + [Test] + public async Task MockFile_Move_ShouldThrowDirectoryNotFoundExceptionWhenSourcePathDoesNotExist_Message() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(new byte[] {0})} - }); - - await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)) - .Throws() - .WithMessage(@"Could not find a part of the path*").AsWildcard(); - } + {sourceFilePath, new MockFileData(new byte[] {0})} + }); - [Test] - public async Task MockFile_Move_ShouldThrowExceptionWhenSourceDoesNotExist() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + await That(() => fileSystem.File.Move(sourceFilePath, destFilePath)) + .Throws() + .WithMessage(@"Could not find a part of the path*").AsWildcard(); + } - Action action = () => fileSystem.File.Move(sourceFilePath, XFS.Path(@"c:\something\demo2.txt")); + [Test] + public async Task MockFile_Move_ShouldThrowExceptionWhenSourceDoesNotExist() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - await That(action).Throws(); - } + Action action = () => fileSystem.File.Move(sourceFilePath, XFS.Path(@"c:\something\demo2.txt")); - [Test] - public async Task MockFile_Move_ShouldThrowExceptionWhenSourceDoesNotExist_EvenWhenCopyingToItself() - { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); + await That(action).Throws(); + } - Action action = () => fileSystem.File.Move(sourceFilePath, XFS.Path(@"c:\something\demo.txt")); + [Test] + public async Task MockFile_Move_ShouldThrowExceptionWhenSourceDoesNotExist_EvenWhenCopyingToItself() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); - await That(action).Throws(); - } + Action action = () => fileSystem.File.Move(sourceFilePath, XFS.Path(@"c:\something\demo.txt")); - [Test] - public async Task MockFile_Move_ShouldRetainMetadata() + await That(action).Throws(); + } + + [Test] + public async Task MockFile_Move_ShouldRetainMetadata() + { + string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); + string sourceFileContent = "this is some content"; + DateTimeOffset creationTime = DateTimeOffset.Now; + var fileSystem = new MockFileSystem(new Dictionary { - string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); - string sourceFileContent = "this is some content"; - DateTimeOffset creationTime = DateTimeOffset.Now; - var fileSystem = new MockFileSystem(new Dictionary - { - {sourceFilePath, new MockFileData(sourceFileContent){CreationTime = creationTime}}, - {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} - }); + {sourceFilePath, new MockFileData(sourceFileContent){CreationTime = creationTime}}, + {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})} + }); - string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); + string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt"); - fileSystem.File.Move(sourceFilePath, destFilePath); + fileSystem.File.Move(sourceFilePath, destFilePath); + + await That(fileSystem.File.GetCreationTimeUtc(destFilePath)).IsEqualTo(creationTime.UtcDateTime); + } - await That(fileSystem.File.GetCreationTimeUtc(destFilePath)).IsEqualTo(creationTime.UtcDateTime); + [Test] + public async Task MockFile_Move_ShouldThrowExceptionWhenSourceFileShare_Is_Not_Delete() + { + string sourceFileReadDelete = XFS.Path(@"c:\something\IHaveReadDelete.txt"); + string sourceFileDelete = XFS.Path(@"c:\something\IHaveDelete.txt"); + string sourceFileRead = XFS.Path(@"c:\something\IHaveRead.txt"); + string sourceFileNone = XFS.Path(@"c:\something\IHaveNone.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + { sourceFileDelete, new MockFileData("") { AllowedFileShare = FileShare.Delete } }, + { sourceFileRead, new MockFileData("") { AllowedFileShare = FileShare.Read } }, + { sourceFileReadDelete, new MockFileData("") { AllowedFileShare = FileShare.Delete | FileShare.Read } }, + { sourceFileNone, new MockFileData("") { AllowedFileShare = FileShare.None } }, + }); + + await AssertMoveSuccess(sourceFileReadDelete); + await AssertMoveSuccess(sourceFileDelete); + await AssertMoveThrowsIOException(sourceFileRead); + await AssertMoveThrowsIOException(sourceFileNone); + + async Task AssertMoveThrowsIOException(string sourceFile) + { + var target = sourceFile + ".moved"; + await That(() => fileSystem.File.Move(sourceFile, target)).Throws(); } - [Test] - public async Task MockFile_Move_ShouldThrowExceptionWhenSourceFileShare_Is_Not_Delete() + async Task AssertMoveSuccess(string sourceFile) { - string sourceFileReadDelete = XFS.Path(@"c:\something\IHaveReadDelete.txt"); - string sourceFileDelete = XFS.Path(@"c:\something\IHaveDelete.txt"); - string sourceFileRead = XFS.Path(@"c:\something\IHaveRead.txt"); - string sourceFileNone = XFS.Path(@"c:\something\IHaveNone.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { sourceFileDelete, new MockFileData("") { AllowedFileShare = FileShare.Delete } }, - { sourceFileRead, new MockFileData("") { AllowedFileShare = FileShare.Read } }, - { sourceFileReadDelete, new MockFileData("") { AllowedFileShare = FileShare.Delete | FileShare.Read } }, - { sourceFileNone, new MockFileData("") { AllowedFileShare = FileShare.None } }, - }); - - await AssertMoveSuccess(sourceFileReadDelete); - await AssertMoveSuccess(sourceFileDelete); - await AssertMoveThrowsIOException(sourceFileRead); - await AssertMoveThrowsIOException(sourceFileNone); - - async Task AssertMoveThrowsIOException(string sourceFile) - { - var target = sourceFile + ".moved"; - await That(() => fileSystem.File.Move(sourceFile, target)).Throws(); - } - - async Task AssertMoveSuccess(string sourceFile) - { - var target = sourceFile + ".moved"; - fileSystem.File.Move(sourceFile, target); - await That(fileSystem.File.Exists(target)).IsTrue(); - } + var target = sourceFile + ".moved"; + fileSystem.File.Move(sourceFile, target); + await That(fileSystem.File.Exists(target)).IsTrue(); } } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs index a77a2c414..ec1896ad9 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileOpenTests.cs @@ -1,382 +1,381 @@ using System.Threading.Tasks; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; - using NUnit.Framework; +using NUnit.Framework; - using XFS = MockUnixSupport; +using XFS = MockUnixSupport; - public class MockFileOpenTests +public class MockFileOpenTests +{ + [Test] + public async Task MockFile_Open_ThrowsOnCreateNewWithExistingFile() { - [Test] - public async Task MockFile_Open_ThrowsOnCreateNewWithExistingFile() + string filepath = XFS.Path(@"c:\something\already\exists.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\already\exists.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); + { filepath, new MockFileData("I'm here") } + }); - await That(() => filesystem.File.Open(filepath, FileMode.CreateNew)).Throws(); - } + await That(() => filesystem.File.Open(filepath, FileMode.CreateNew)).Throws(); + } - [Test] - public async Task MockFile_Open_ThrowsOnOpenWithMissingFile() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); + [Test] + public async Task MockFile_Open_ThrowsOnOpenWithMissingFile() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); - await That(() => filesystem.File.Open(filepath, FileMode.Open)).Throws(); - } + await That(() => filesystem.File.Open(filepath, FileMode.Open)).Throws(); + } - [Test] - public async Task MockFile_Open_ThrowsOnTruncateWithMissingFile() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); + [Test] + public async Task MockFile_Open_ThrowsOnTruncateWithMissingFile() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); - await That(() => filesystem.File.Open(filepath, FileMode.Truncate)).Throws(); - } + await That(() => filesystem.File.Open(filepath, FileMode.Truncate)).Throws(); + } - [Test] - public async Task MockFile_Open_CreatesNewFileFileOnCreate() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + [Test] + public async Task MockFile_Open_CreatesNewFileFileOnCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); - var stream = filesystem.File.Open(filepath, FileMode.Create); + var stream = filesystem.File.Open(filepath, FileMode.Create); - await That(filesystem.File.Exists(filepath)).IsTrue(); - await That(stream.Position).IsEqualTo(0); - await That(stream.Length).IsEqualTo(0); - } + await That(filesystem.File.Exists(filepath)).IsTrue(); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + } - [Test] - public async Task MockFile_Open_AllowsReadWriteOnCreate() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + [Test] + public async Task MockFile_Open_AllowsReadWriteOnCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); - var stream = filesystem.File.Open(filepath, FileMode.Create); + var stream = filesystem.File.Open(filepath, FileMode.Create); - await That(stream.CanRead).IsTrue(); - await That(stream.CanWrite).IsTrue(); - } + await That(stream.CanRead).IsTrue(); + await That(stream.CanWrite).IsTrue(); + } - [Test] - public async Task MockFile_Open_CreatesNewFileFileOnCreateNew() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + [Test] + public async Task MockFile_Open_CreatesNewFileFileOnCreateNew() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); - var stream = filesystem.File.Open(filepath, FileMode.CreateNew); + var stream = filesystem.File.Open(filepath, FileMode.CreateNew); - await That(filesystem.File.Exists(filepath)).IsTrue(); - await That(stream.Position).IsEqualTo(0); - await That(stream.Length).IsEqualTo(0); - } + await That(filesystem.File.Exists(filepath)).IsTrue(); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + } - [Test] - public async Task MockFile_Open_OpensExistingFileOnAppend() + [Test] + public async Task MockFile_Open_OpensExistingFileOnAppend() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); + { filepath, new MockFileData("I'm here") } + }); - var stream = filesystem.File.Open(filepath, FileMode.Append); - var file = filesystem.GetFile(filepath); + var stream = filesystem.File.Open(filepath, FileMode.Append); + var file = filesystem.GetFile(filepath); - await That(stream.Position).IsEqualTo(file.Contents.Length); - await That(stream.Length).IsEqualTo(file.Contents.Length); - } + await That(stream.Position).IsEqualTo(file.Contents.Length); + await That(stream.Length).IsEqualTo(file.Contents.Length); + } - [Test] - public async Task MockFile_Open_OpensExistingFileOnTruncate() + [Test] + public async Task MockFile_Open_OpensExistingFileOnTruncate() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - var stream = filesystem.File.Open(filepath, FileMode.Truncate); - var file = filesystem.GetFile(filepath); - - await That(stream.Position).IsEqualTo(0); - await That(stream.Length).IsEqualTo(0); - await That(file.Contents.Length).IsEqualTo(0); - } + { filepath, new MockFileData("I'm here") } + }); - [Test] - public async Task MockFile_Open_OpensExistingFileOnOpen() + var stream = filesystem.File.Open(filepath, FileMode.Truncate); + var file = filesystem.GetFile(filepath); + + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + await That(file.Contents.Length).IsEqualTo(0); + } + + [Test] + public async Task MockFile_Open_OpensExistingFileOnOpen() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); + { filepath, new MockFileData("I'm here") } + }); - var stream = filesystem.File.Open(filepath, FileMode.Open); - var file = filesystem.GetFile(filepath); + var stream = filesystem.File.Open(filepath, FileMode.Open); + var file = filesystem.GetFile(filepath); - await That(stream.Position).IsEqualTo(0); - await That(stream.Length).IsEqualTo(file.Contents.Length); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(file.Contents.Length); - byte[] data; - using (var br = new BinaryReader(stream)) - data = br.ReadBytes((int)stream.Length); + byte[] data; + using (var br = new BinaryReader(stream)) + data = br.ReadBytes((int)stream.Length); - await That(data).IsEqualTo(file.Contents); - } + await That(data).IsEqualTo(file.Contents); + } - [Test] - public async Task MockFile_Open_OpensExistingFileOnOpenOrCreate() + [Test] + public async Task MockFile_Open_OpensExistingFileOnOpenOrCreate() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); + { filepath, new MockFileData("I'm here") } + }); - var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); - var file = filesystem.GetFile(filepath); + var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); + var file = filesystem.GetFile(filepath); - await That(stream.Position).IsEqualTo(0); - await That(stream.Length).IsEqualTo(file.Contents.Length); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(file.Contents.Length); - byte[] data; - using (var br = new BinaryReader(stream)) - data = br.ReadBytes((int)stream.Length); + byte[] data; + using (var br = new BinaryReader(stream)) + data = br.ReadBytes((int)stream.Length); - await That(data).IsEqualTo(file.Contents); - } + await That(data).IsEqualTo(file.Contents); + } - [Test] - public async Task MockFile_Open_CreatesNewFileOnOpenOrCreate() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + [Test] + public async Task MockFile_Open_CreatesNewFileOnOpenOrCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); - var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); + var stream = filesystem.File.Open(filepath, FileMode.OpenOrCreate); - await That(filesystem.File.Exists(filepath)).IsTrue(); - await That(stream.Position).IsEqualTo(0); - await That(stream.Length).IsEqualTo(0); - } + await That(filesystem.File.Exists(filepath)).IsTrue(); + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + } - [Test] - public async Task MockFile_Open_OverwritesExistingFileOnCreate() + [Test] + public async Task MockFile_Open_OverwritesExistingFileOnCreate() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here") } - }); - - var stream = filesystem.File.Open(filepath, FileMode.Create); - var file = filesystem.GetFile(filepath); - - await That(stream.Position).IsEqualTo(0); - await That(stream.Length).IsEqualTo(0); - await That(file.Contents.Length).IsEqualTo(0); - } + { filepath, new MockFileData("I'm here") } + }); - [Test] - public async Task MockFile_OpenText_ShouldRetainLastWriteTime() + var stream = filesystem.File.Open(filepath, FileMode.Create); + var file = filesystem.GetFile(filepath); + + await That(stream.Position).IsEqualTo(0); + await That(stream.Length).IsEqualTo(0); + await That(file.Contents.Length).IsEqualTo(0); + } + + [Test] + public async Task MockFile_OpenText_ShouldRetainLastWriteTime() + { + // Arrange + var fs = new MockFileSystem(); + string filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(@"I'm here"); + var lastWriteTime = new DateTime(2012, 03, 21); + file.LastWriteTime = lastWriteTime; + fs.AddFile(filepath, file); + + // Act + using (var reader = fs.File.OpenText(filepath)) { - // Arrange - var fs = new MockFileSystem(); - string filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(@"I'm here"); - var lastWriteTime = new DateTime(2012, 03, 21); - file.LastWriteTime = lastWriteTime; - fs.AddFile(filepath, file); - - // Act - using (var reader = fs.File.OpenText(filepath)) - { - reader.ReadLine(); - } - - // Assert - await That(fs.FileInfo.New(filepath).LastWriteTime).IsEqualTo(lastWriteTime); + reader.ReadLine(); } - [Test] - public async Task MockFile_OpenText_ShouldUpdateLastAccessTime() + // Assert + await That(fs.FileInfo.New(filepath).LastWriteTime).IsEqualTo(lastWriteTime); + } + + [Test] + public async Task MockFile_OpenText_ShouldUpdateLastAccessTime() + { + // Arrange + var fs = new MockFileSystem(); + string filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(@"I'm here"); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + fs.AddFile(filepath, file); + + // Act + using (var reader = fs.File.OpenText(filepath)) { - // Arrange - var fs = new MockFileSystem(); - string filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(@"I'm here"); - var lastAccessTime = new DateTime(2012, 03, 21); - file.LastAccessTime = lastAccessTime; - fs.AddFile(filepath, file); - - // Act - using (var reader = fs.File.OpenText(filepath)) - { - reader.ReadLine(); - } - - // Assert - await That(DateTime.Now - fs.FileInfo.New(filepath).LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + reader.ReadLine(); } - [Test] - public async Task MockFile_Read_ShouldRetainCreationTimeAndUpdateLastAccessTime() - { - // Arrange - var fs = new MockFileSystem(); - var filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(new byte[] { 1, 2, 3 }); - var lastAccessTime = new DateTime(2012, 03, 21); - file.LastAccessTime = lastAccessTime; - var creationTime = new DateTime(2012, 03, 20); - file.CreationTime = creationTime; - fs.AddFile(filepath, file); - - var fi = fs.FileInfo.New(filepath); - var stream = fi.OpenRead(); - var buffer = new byte[16]; + // Assert + await That(DateTime.Now - fs.FileInfo.New(filepath).LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } + + [Test] + public async Task MockFile_Read_ShouldRetainCreationTimeAndUpdateLastAccessTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenRead(); + var buffer = new byte[16]; #pragma warning disable CA2022 - stream.Read(buffer, 0, buffer.Length); + stream.Read(buffer, 0, buffer.Length); #pragma warning restore CA2022 - fi.Refresh(); - // Assert - await That(fi.CreationTime).IsEqualTo(creationTime); - await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); - } + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } - [Test] - public async Task MockFile_ReadAsync_ShouldRetainCreationTimeAndUpdateLastAccessTime() - { - // Arrange - var fs = new MockFileSystem(); - var filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(new byte[] { 1, 2, 3 }); - var lastAccessTime = new DateTime(2012, 03, 21); - file.LastAccessTime = lastAccessTime; - var creationTime = new DateTime(2012, 03, 20); - file.CreationTime = creationTime; - fs.AddFile(filepath, file); - - var fi = fs.FileInfo.New(filepath); - var stream = fi.OpenRead(); - var buffer = new byte[16]; + [Test] + public async Task MockFile_ReadAsync_ShouldRetainCreationTimeAndUpdateLastAccessTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenRead(); + var buffer = new byte[16]; #pragma warning disable CA1835 #pragma warning disable CA2022 - // ReSharper disable once MustUseReturnValue - await stream.ReadAsync(buffer, 0, buffer.Length); + // ReSharper disable once MustUseReturnValue + await stream.ReadAsync(buffer, 0, buffer.Length); #pragma warning restore CA2022 #pragma warning restore CA1835 - fi.Refresh(); - // Assert - await That(fi.CreationTime).IsEqualTo(creationTime); - await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); - } + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } - [Test] - public async Task MockFile_Write_ShouldRetainCreationTimeAndUpdateLastAccessTimeAndLastWriteTime() - { - // Arrange - var fs = new MockFileSystem(); - var filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(new byte[] { 1, 2, 3 }); - var lastAccessTime = new DateTime(2012, 03, 21); - file.LastAccessTime = lastAccessTime; - var creationTime = new DateTime(2012, 03, 20); - file.CreationTime = creationTime; - fs.AddFile(filepath, file); - - var fi = fs.FileInfo.New(filepath); - var stream = fi.OpenWrite(); - var buffer = new byte[16]; - stream.Write(buffer, 0, buffer.Length); - fi.Refresh(); - // Assert - await That(fi.CreationTime).IsEqualTo(creationTime); - await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); - await That(DateTime.Now - fi.LastWriteTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); - } + [Test] + public async Task MockFile_Write_ShouldRetainCreationTimeAndUpdateLastAccessTimeAndLastWriteTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenWrite(); + var buffer = new byte[16]; + stream.Write(buffer, 0, buffer.Length); + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + await That(DateTime.Now - fi.LastWriteTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } - [Test] - public async Task MockFile_WriteAsync_ShouldRetainCreationTimeAndUpdateLastAccessTimeAndLastWriteTime() - { - // Arrange - var fs = new MockFileSystem(); - var filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(new byte[] { 1, 2, 3 }); - var lastAccessTime = new DateTime(2012, 03, 21); - file.LastAccessTime = lastAccessTime; - var creationTime = new DateTime(2012, 03, 20); - file.CreationTime = creationTime; - fs.AddFile(filepath, file); - - var fi = fs.FileInfo.New(filepath); - var stream = fi.OpenWrite(); - var buffer = new byte[16]; - await stream.WriteAsync(buffer, 0, buffer.Length); - fi.Refresh(); - // Assert - await That(fi.CreationTime).IsEqualTo(creationTime); - await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); - await That(DateTime.Now - fi.LastWriteTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); - } + [Test] + public async Task MockFile_WriteAsync_ShouldRetainCreationTimeAndUpdateLastAccessTimeAndLastWriteTime() + { + // Arrange + var fs = new MockFileSystem(); + var filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(new byte[] { 1, 2, 3 }); + var lastAccessTime = new DateTime(2012, 03, 21); + file.LastAccessTime = lastAccessTime; + var creationTime = new DateTime(2012, 03, 20); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + var fi = fs.FileInfo.New(filepath); + var stream = fi.OpenWrite(); + var buffer = new byte[16]; + await stream.WriteAsync(buffer, 0, buffer.Length); + fi.Refresh(); + // Assert + await That(fi.CreationTime).IsEqualTo(creationTime); + await That(DateTime.Now - fi.LastAccessTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + await That(DateTime.Now - fi.LastWriteTime).IsLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + } - [Test] - public async Task MockFile_OpenText_ShouldRetainCreationTime() + [Test] + public async Task MockFile_OpenText_ShouldRetainCreationTime() + { + // Arrange + var fs = new MockFileSystem(); + string filepath = XFS.Path(@"C:\TestData\test.txt"); + var file = new MockFileData(@"I'm here"); + var creationTime = new DateTime(2012, 03, 21); + file.CreationTime = creationTime; + fs.AddFile(filepath, file); + + // Act + using (var reader = fs.File.OpenText(filepath)) { - // Arrange - var fs = new MockFileSystem(); - string filepath = XFS.Path(@"C:\TestData\test.txt"); - var file = new MockFileData(@"I'm here"); - var creationTime = new DateTime(2012, 03, 21); - file.CreationTime = creationTime; - fs.AddFile(filepath, file); - - // Act - using (var reader = fs.File.OpenText(filepath)) - { - reader.ReadLine(); - } - - // Assert - await That(fs.FileInfo.New(filepath).CreationTime).IsEqualTo(creationTime); + reader.ReadLine(); } - [Test] - public async Task MockFile_Open_ShouldThrowDirectoryNotFoundExceptionIfFileModeCreateAndParentPathDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - var file = XFS.Path("C:\\path\\NotFound.ext"); + // Assert + await That(fs.FileInfo.New(filepath).CreationTime).IsEqualTo(creationTime); + } - // Act - Action action = () => fileSystem.File.Open(file, FileMode.Create); + [Test] + public async Task MockFile_Open_ShouldThrowDirectoryNotFoundExceptionIfFileModeCreateAndParentPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var file = XFS.Path("C:\\path\\NotFound.ext"); - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Could not find a part of the path"); - } + // Act + Action action = () => fileSystem.File.Open(file, FileMode.Create); - [Test] - public async Task MockFile_OpenWrite_ShouldWorkWithRelativePath() - { - var file = "file.txt"; - var fileSystem = new MockFileSystem(); + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Could not find a part of the path"); + } - fileSystem.File.OpenWrite(file).Close(); + [Test] + public async Task MockFile_OpenWrite_ShouldWorkWithRelativePath() + { + var file = "file.txt"; + var fileSystem = new MockFileSystem(); - await That(fileSystem.File.Exists(file)).IsTrue(); - } + fileSystem.File.OpenWrite(file).Close(); + + await That(fileSystem.File.Exists(file)).IsTrue(); } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllBytesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllBytesTests.cs index faff0e0a4..f0df4969a 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllBytesTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllBytesTests.cs @@ -4,150 +4,149 @@ using System.Threading.Tasks; using System.Threading; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileReadAllBytesTests { - public class MockFileReadAllBytesTests + [Test] + public async Task MockFile_ReadAllBytes_ShouldReturnOriginalByteData() { - [Test] - public async Task MockFile_ReadAllBytes_ShouldReturnOriginalByteData() + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - var result = file.ReadAllBytes(XFS.Path(@"c:\something\other.gif")); + var result = file.ReadAllBytes(XFS.Path(@"c:\something\other.gif")); - await That(result) - .IsEqualTo(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }); - } + await That(result) + .IsEqualTo(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }); + } - [Test] - public async Task MockFile_ReadAllBytes_ShouldReturnDataSavedByWriteAllBytes() - { - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var fileContent = new byte[] { 1, 2, 3, 4 }; - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + [Test] + public async Task MockFile_ReadAllBytes_ShouldReturnDataSavedByWriteAllBytes() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var fileContent = new byte[] { 1, 2, 3, 4 }; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - fileSystem.File.WriteAllBytes(path, fileContent); + fileSystem.File.WriteAllBytes(path, fileContent); - await That(fileSystem.File.ReadAllBytes(path)).IsEqualTo(fileContent); - } + await That(fileSystem.File.ReadAllBytes(path)).IsEqualTo(fileContent); + } - [Test] - public async Task MockFile_ReadAllBytes_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() - { - var fileSystem = new MockFileSystem(); - var file = new MockFile(fileSystem); + [Test] + public async Task MockFile_ReadAllBytes_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var file = new MockFile(fileSystem); - Action action = () => file.ReadAllBytes(@"C:\a.txt"); + Action action = () => file.ReadAllBytes(@"C:\a.txt"); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_ReadAllBytes_ShouldTolerateAltDirectorySeparatorInPath() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:" + fileSystem.Path.DirectorySeparatorChar + "test.dat"); - var altPath = XFS.Path("C:" + fileSystem.Path.AltDirectorySeparatorChar + "test.dat"); - var data = new byte[] { 0x12, 0x34, 0x56, 0x78 }; + [Test] + public async Task MockFile_ReadAllBytes_ShouldTolerateAltDirectorySeparatorInPath() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:" + fileSystem.Path.DirectorySeparatorChar + "test.dat"); + var altPath = XFS.Path("C:" + fileSystem.Path.AltDirectorySeparatorChar + "test.dat"); + var data = new byte[] { 0x12, 0x34, 0x56, 0x78 }; - fileSystem.AddFile(path, new MockFileData(data)); + fileSystem.AddFile(path, new MockFileData(data)); - await That(fileSystem.File.ReadAllBytes(altPath)).IsEqualTo(data); - } + await That(fileSystem.File.ReadAllBytes(altPath)).IsEqualTo(data); + } - [Test] - public async Task MockFile_ReadAllBytes_ShouldReturnANewCopyOfTheFileContents() + [Test] + public async Task MockFile_ReadAllBytes_ShouldReturnANewCopyOfTheFileContents() + { + var path = XFS.Path(@"c:\something\demo.bin"); + var fileSystem = new MockFileSystem(new Dictionary { - var path = XFS.Path(@"c:\something\demo.bin"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData(new byte[] { 1, 2, 3, 4 }) } - }); - - var firstRead = fileSystem.File.ReadAllBytes(path); + { path, new MockFileData(new byte[] { 1, 2, 3, 4 }) } + }); - var secondRead = fileSystem.File.ReadAllBytes(path); + var firstRead = fileSystem.File.ReadAllBytes(path); - for (int i = 0; i < firstRead.Length; i++) - { - firstRead[i] += 1; - } + var secondRead = fileSystem.File.ReadAllBytes(path); - await That(firstRead).IsNotEqualTo(secondRead); + for (int i = 0; i < firstRead.Length; i++) + { + firstRead[i] += 1; } + await That(firstRead).IsNotEqualTo(secondRead); + } + #if FEATURE_ASYNC_FILE - [Test] - public async Task MockFile_ReadAllBytesAsync_ShouldReturnOriginalByteData() + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldReturnOriginalByteData() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - var result = await file.ReadAllBytesAsync(XFS.Path(@"c:\something\other.gif")); + var result = await file.ReadAllBytesAsync(XFS.Path(@"c:\something\other.gif")); - await That(result) - .IsEqualTo(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }); - } + await That(result) + .IsEqualTo(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }); + } - [Test] - public async Task MockFile_ReadAllBytesAsync_ShouldReturnDataSavedByWriteAllBytes() - { - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var fileContent = new byte[] { 1, 2, 3, 4 }; - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldReturnDataSavedByWriteAllBytes() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var fileContent = new byte[] { 1, 2, 3, 4 }; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - fileSystem.File.WriteAllBytes(path, fileContent); + fileSystem.File.WriteAllBytes(path, fileContent); - await That(await fileSystem.File.ReadAllBytesAsync(path)).IsEqualTo(fileContent); - } + await That(await fileSystem.File.ReadAllBytesAsync(path)).IsEqualTo(fileContent); + } - [Test] - public async Task MockFile_ReadAllBytesAsync_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() - { - var fileSystem = new MockFileSystem(); - var file = new MockFile(fileSystem); + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() + { + var fileSystem = new MockFileSystem(); + var file = new MockFile(fileSystem); - Func action = async () => await file.ReadAllBytesAsync(@"C:\a.txt"); + Func action = async () => await file.ReadAllBytesAsync(@"C:\a.txt"); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_ReadAllBytesAsync_ShouldThrowOperationCanceledExceptionIfCanceled() - { - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldThrowOperationCanceledExceptionIfCanceled() + { + var fileSystem = new MockFileSystem(); - Func action = async () => - await fileSystem.File.ReadAllBytesAsync(@"C:\a.txt", new CancellationToken(canceled: true)); + Func action = async () => + await fileSystem.File.ReadAllBytesAsync(@"C:\a.txt", new CancellationToken(canceled: true)); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_ReadAllBytesAsync_ShouldTolerateAltDirectorySeparatorInPath() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:" + fileSystem.Path.DirectorySeparatorChar + "test.dat"); - var altPath = XFS.Path("C:" + fileSystem.Path.AltDirectorySeparatorChar + "test.dat"); - var data = new byte[] { 0x12, 0x34, 0x56, 0x78 }; + [Test] + public async Task MockFile_ReadAllBytesAsync_ShouldTolerateAltDirectorySeparatorInPath() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:" + fileSystem.Path.DirectorySeparatorChar + "test.dat"); + var altPath = XFS.Path("C:" + fileSystem.Path.AltDirectorySeparatorChar + "test.dat"); + var data = new byte[] { 0x12, 0x34, 0x56, 0x78 }; - fileSystem.AddFile(path, new MockFileData(data)); + fileSystem.AddFile(path, new MockFileData(data)); - await That(await fileSystem.File.ReadAllBytesAsync(altPath)).IsEqualTo(data); - } -#endif + await That(await fileSystem.File.ReadAllBytesAsync(altPath)).IsEqualTo(data); } -} +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs index 374fd489d..3c6e1b294 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadAllLinesTests.cs @@ -1,155 +1,155 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; - using Collections.Specialized; - using Threading; - using Threading.Tasks; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; +using Collections.Specialized; +using Threading; +using Threading.Tasks; - using NUnit.Framework; +using NUnit.Framework; - using Text; +using Text; - using XFS = MockUnixSupport; +using XFS = MockUnixSupport; - public class MockFileReadAllLinesTests +public class MockFileReadAllLinesTests +{ + [Test] + public async Task MockFile_ReadAllLines_ShouldReturnOriginalTextData() { - [Test] - public async Task MockFile_ReadAllLines_ShouldReturnOriginalTextData() + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt")); + // Act + var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt")); - // Assert - await That(result) - .IsEqualTo(new[] { "Demo", "text", "content", "value" }); - } + // Assert + await That(result) + .IsEqualTo(new[] { "Demo", "text", "content", "value" }); + } - [Test] - public async Task MockFile_ReadAllLines_ShouldReturnOriginalDataWithCustomEncoding() + [Test] + public async Task MockFile_ReadAllLines_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello\r\nthere\rBob\nBob!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string text = "Hello\r\nthere\rBob\nBob!"; - var encodedText = Encoding.BigEndianUnicode.GetBytes(text); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - - // Assert - await That(result) - .IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); - } + var file = new MockFile(fileSystem); - [Test] - public async Task MockFile_ReadAllLines_NotExistingFile_ThrowsCorrectFileNotFoundException() - { - var absentFileNameFullPath = XFS.Path(@"c:\you surely don't have such file.hope-so"); - var mockFileSystem = new MockFileSystem(); + // Act + var result = file.ReadAllLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - var act = new Action(() => - mockFileSystem.File.ReadAllLines(absentFileNameFullPath) - ); + // Assert + await That(result) + .IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); + } - var exception = await That(act).Throws(); - await That(exception.FileName).IsEqualTo(absentFileNameFullPath); - await That(exception.Message).IsEqualTo("Could not find file '" + absentFileNameFullPath + "'."); - } + [Test] + public async Task MockFile_ReadAllLines_NotExistingFile_ThrowsCorrectFileNotFoundException() + { + var absentFileNameFullPath = XFS.Path(@"c:\you surely don't have such file.hope-so"); + var mockFileSystem = new MockFileSystem(); - [Test] - public async Task MockFile_ReadAllLines_ShouldNotReturnBom() - { - // Arrange - var testFilePath = XFS.Path(@"c:\a test file.txt"); - const string testText = "Hello World"; - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllLines(testFilePath, new[] { testText }, Encoding.UTF8); + var act = new Action(() => + mockFileSystem.File.ReadAllLines(absentFileNameFullPath) + ); - // Act - var result = fileSystem.File.ReadAllLines(testFilePath, Encoding.UTF8); + var exception = await That(act).Throws(); + await That(exception.FileName).IsEqualTo(absentFileNameFullPath); + await That(exception.Message).IsEqualTo("Could not find file '" + absentFileNameFullPath + "'."); + } - // Assert - await That(result.Length).IsEqualTo(1); - await That(result[0]).IsEqualTo(testText); - } + [Test] + public async Task MockFile_ReadAllLines_ShouldNotReturnBom() + { + // Arrange + var testFilePath = XFS.Path(@"c:\a test file.txt"); + const string testText = "Hello World"; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllLines(testFilePath, new[] { testText }, Encoding.UTF8); + + // Act + var result = fileSystem.File.ReadAllLines(testFilePath, Encoding.UTF8); + + // Assert + await That(result.Length).IsEqualTo(1); + await That(result[0]).IsEqualTo(testText); + } #if FEATURE_ASYNC_FILE - [Test] - public async Task MockFile_ReadAllLinesAsync_ShouldReturnOriginalTextData() + [Test] + public async Task MockFile_ReadAllLinesAsync_ShouldReturnOriginalTextData() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - var result = await file.ReadAllLinesAsync(XFS.Path(@"c:\something\demo.txt")); + // Act + var result = await file.ReadAllLinesAsync(XFS.Path(@"c:\something\demo.txt")); - // Assert - await That(result).IsEqualTo(new[] { "Demo", "text", "content", "value" }); - } + // Assert + await That(result).IsEqualTo(new[] { "Demo", "text", "content", "value" }); + } - [Test] - public async Task MockFile_ReadAllLinesAsync_ShouldReturnOriginalDataWithCustomEncoding() + [Test] + public async Task MockFile_ReadAllLinesAsync_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello\r\nthere\rBob\nBob!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string text = "Hello\r\nthere\rBob\nBob!"; - var encodedText = Encoding.BigEndianUnicode.GetBytes(text); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - var result = await file.ReadAllLinesAsync(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + // Act + var result = await file.ReadAllLinesAsync(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - // Assert - await That(result).IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); - } + // Assert + await That(result).IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); + } - [Test] - public async Task MockFile_ReadAllLinesAsync_ShouldThrowOperationCanceledExceptionIfCanceled() - { - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_ReadAllLinesAsync_ShouldThrowOperationCanceledExceptionIfCanceled() + { + var fileSystem = new MockFileSystem(); - Func action = async () => - await fileSystem.File.ReadAllLinesAsync(@"C:\a.txt", new CancellationToken(canceled: true)); + Func action = async () => + await fileSystem.File.ReadAllLinesAsync(@"C:\a.txt", new CancellationToken(canceled: true)); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_ReadAllLinesAsync_NotExistingFile_ThrowsCorrectFileNotFoundException() - { - var absentFileNameFullPath = XFS.Path(@"c:\you surely don't have such file.hope-so"); - var mockFileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_ReadAllLinesAsync_NotExistingFile_ThrowsCorrectFileNotFoundException() + { + var absentFileNameFullPath = XFS.Path(@"c:\you surely don't have such file.hope-so"); + var mockFileSystem = new MockFileSystem(); - var act = new Func(async () => - await mockFileSystem.File.ReadAllLinesAsync(absentFileNameFullPath) - ); + var act = new Func(async () => + await mockFileSystem.File.ReadAllLinesAsync(absentFileNameFullPath) + ); - var exception = await That(act).Throws(); - await That(exception.FileName).IsEqualTo(absentFileNameFullPath); - await That(exception.Message).IsEqualTo("Could not find file '" + absentFileNameFullPath + "'."); - } + var exception = await That(act).Throws(); + await That(exception.FileName).IsEqualTo(absentFileNameFullPath); + await That(exception.Message).IsEqualTo("Could not find file '" + absentFileNameFullPath + "'."); + } #if FEATURE_READ_LINES_ASYNC [Test] @@ -229,5 +229,4 @@ public async Task MockFile_ReadLinesAsync_NotExistingFile_ThrowsCorrectFileNotFo } #endif #endif - } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadLinesTests.cs index 3f8e99951..7f477b2a2 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadLinesTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileReadLinesTests.cs @@ -1,52 +1,51 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; - using NUnit.Framework; +using NUnit.Framework; - using Text; +using Text; - using XFS = MockUnixSupport; +using XFS = MockUnixSupport; - public class MockFileReadLinesTests +public class MockFileReadLinesTests +{ + [Test] + public async Task MockFile_ReadLines_ShouldReturnOriginalTextData() { - [Test] - public async Task MockFile_ReadLines_ShouldReturnOriginalTextData() + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt")); + // Act + var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt")); - // Assert - await That(result).IsEqualTo(new[] { "Demo", "text", "content", "value" }); - } + // Assert + await That(result).IsEqualTo(new[] { "Demo", "text", "content", "value" }); + } - [Test] - public async Task MockFile_ReadLines_ShouldReturnOriginalDataWithCustomEncoding() + [Test] + public async Task MockFile_ReadLines_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello\r\nthere\rBob\nBob!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string text = "Hello\r\nthere\rBob\nBob!"; - var encodedText = Encoding.BigEndianUnicode.GetBytes(text); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } - }); - - var file = new MockFile(fileSystem); - - // Act - var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - - // Assert - await That(result).IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); - } + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); + + var file = new MockFile(fileSystem); + + // Act + var result = file.ReadLines(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + + // Assert + await That(result).IsEqualTo(new[] { "Hello", "there", "Bob", "Bob!" }); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAccessControlTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAccessControlTests.cs index 802552721..d1e8523bd 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAccessControlTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAccessControlTests.cs @@ -4,65 +4,64 @@ using System.Security.AccessControl; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +[WindowsOnly(WindowsSpecifics.AccessControlLists)] +[SupportedOSPlatform("windows")] +public class MockFileSetAccessControlTests { - [TestFixture] - [WindowsOnly(WindowsSpecifics.AccessControlLists)] - [SupportedOSPlatform("windows")] - public class MockFileSetAccessControlTests + [TestCase(" ")] + [TestCase(" ")] + public async Task MockFile_SetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) { - [TestCase(" ")] - [TestCase(" ")] - public async Task MockFile_SetAccessControl_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path) - { - // Arrange - var fileSystem = new MockFileSystem(); - var fileSecurity = new FileSecurity(); + // Arrange + var fileSystem = new MockFileSystem(); + var fileSecurity = new FileSecurity(); - // Act - Action action = () => fileSystem.File.SetAccessControl(path, fileSecurity); + // Act + Action action = () => fileSystem.File.SetAccessControl(path, fileSecurity); - // Assert - var exception = await That(action).Throws(); - await That(exception.ParamName).IsEqualTo("path"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockFile_SetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() - { - // Arrange - var fileSystem = new MockFileSystem(); - var expectedFileName = XFS.Path(@"c:\a.txt"); - var fileSecurity = new FileSecurity(); + [Test] + public async Task MockFile_SetAccessControl_ShouldThrowFileNotFoundExceptionIfFileDoesNotExistInMockData() + { + // Arrange + var fileSystem = new MockFileSystem(); + var expectedFileName = XFS.Path(@"c:\a.txt"); + var fileSecurity = new FileSecurity(); - // Act - Action action = () => fileSystem.File.SetAccessControl(expectedFileName, fileSecurity); + // Act + Action action = () => fileSystem.File.SetAccessControl(expectedFileName, fileSecurity); - // Assert - var exception = await That(action).Throws(); - await That(exception.FileName).IsEqualTo(expectedFileName); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.FileName).IsEqualTo(expectedFileName); + } - [Test] - public async Task MockFile_SetAccessControl_ShouldSetAccessControlOfFileData() - { - // Arrange - var filePath = XFS.Path(@"c:\a.txt"); - var fileData = new MockFileData("Test content"); + [Test] + public async Task MockFile_SetAccessControl_ShouldSetAccessControlOfFileData() + { + // Arrange + var filePath = XFS.Path(@"c:\a.txt"); + var fileData = new MockFileData("Test content"); - var fileSystem = new MockFileSystem(new Dictionary() - { - { filePath, fileData } - }); + var fileSystem = new MockFileSystem(new Dictionary() + { + { filePath, fileData } + }); - // Act - var expectedAccessControl = new FileSecurity(); - expectedAccessControl.SetAccessRuleProtection(false, false); - fileSystem.File.SetAccessControl(filePath, expectedAccessControl); + // Act + var expectedAccessControl = new FileSecurity(); + expectedAccessControl.SetAccessRuleProtection(false, false); + fileSystem.File.SetAccessControl(filePath, expectedAccessControl); - // Assert - var accessControl = fileSystem.File.GetAccessControl(filePath); - await That(accessControl).IsEqualTo(expectedAccessControl); - } + // Assert + var accessControl = fileSystem.File.GetAccessControl(filePath); + await That(accessControl).IsEqualTo(expectedAccessControl); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs index 953715939..ef597c6d5 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs @@ -2,65 +2,64 @@ using NUnit.Framework; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSetAttributesTests { - [TestFixture] - public class MockFileSetAttributesTests + [Test] + public async Task MockFile_SetAttributes_ShouldSetAttributesOnFile() { - [Test] - public async Task MockFile_SetAttributes_ShouldSetAttributesOnFile() + var path = XFS.Path(@"c:\something\demo.txt"); + var filedata = new MockFileData("test"); + var fileSystem = new MockFileSystem(new Dictionary { - var path = XFS.Path(@"c:\something\demo.txt"); - var filedata = new MockFileData("test"); - var fileSystem = new MockFileSystem(new Dictionary - { - {path, filedata}, - }); + {path, filedata}, + }); - fileSystem.File.SetAttributes(path, FileAttributes.Hidden); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - var attributes = fileSystem.File.GetAttributes(path); - await That(attributes).IsEqualTo(FileAttributes.Hidden); - } + var attributes = fileSystem.File.GetAttributes(path); + await That(attributes).IsEqualTo(FileAttributes.Hidden); + } - [Test] - public async Task MockFile_SetAttributes_ShouldSetAttributesOnDirectory() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something"); - fileSystem.AddDirectory(path); - var directoryInfo = fileSystem.DirectoryInfo.New(path); - directoryInfo.Attributes = FileAttributes.Directory | FileAttributes.Normal; + [Test] + public async Task MockFile_SetAttributes_ShouldSetAttributesOnDirectory() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something"); + fileSystem.AddDirectory(path); + var directoryInfo = fileSystem.DirectoryInfo.New(path); + directoryInfo.Attributes = FileAttributes.Directory | FileAttributes.Normal; - fileSystem.File.SetAttributes(path, FileAttributes.Directory | FileAttributes.Hidden); + fileSystem.File.SetAttributes(path, FileAttributes.Directory | FileAttributes.Hidden); - var attributes = fileSystem.File.GetAttributes(path); - await That(attributes).IsEqualTo(FileAttributes.Directory | FileAttributes.Hidden); - } + var attributes = fileSystem.File.GetAttributes(path); + await That(attributes).IsEqualTo(FileAttributes.Directory | FileAttributes.Hidden); + } - [Test] - [TestCase("", FileAttributes.Normal)] - [TestCase(" ", FileAttributes.Normal)] - public async Task MockFile_SetAttributes_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path, FileAttributes attributes) - { - var fileSystem = new MockFileSystem(); + [Test] + [TestCase("", FileAttributes.Normal)] + [TestCase(" ", FileAttributes.Normal)] + public async Task MockFile_SetAttributes_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path, FileAttributes attributes) + { + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.SetAttributes(path, attributes); + Action action = () => fileSystem.File.SetAttributes(path, attributes); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_SetAttributes_ShouldThrowFileNotFoundExceptionIfMissingDirectory() - { - var path = XFS.Path(@"C:\something"); - var attributes = FileAttributes.Normal; - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_SetAttributes_ShouldThrowFileNotFoundExceptionIfMissingDirectory() + { + var path = XFS.Path(@"C:\something"); + var attributes = FileAttributes.Normal; + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.SetAttributes(path, attributes); + Action action = () => fileSystem.File.SetAttributes(path, attributes); - var exception = await That(action).Throws(); - await That(exception.FileName).IsEqualTo(path); - } + var exception = await That(action).Throws(); + await That(exception.FileName).IsEqualTo(path); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs index 1d3c0c87f..316c61526 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamFactoryTests.cs @@ -2,177 +2,176 @@ using NUnit.Framework; using System.Text; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; - [TestFixture] - public class MockFileStreamFactoryTests +[TestFixture] +public class MockFileStreamFactoryTests +{ + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.Append)] + public async Task MockFileStreamFactory_CreateForExistingFile_ShouldReturnStream(FileMode fileMode) { - [Test] - [TestCase(FileMode.Create)] - [TestCase(FileMode.Append)] - public async Task MockFileStreamFactory_CreateForExistingFile_ShouldReturnStream(FileMode fileMode) + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\existing.txt", string.Empty } - }); + { @"c:\existing.txt", string.Empty } + }); - var fileStreamFactory = new MockFileStreamFactory(fileSystem); + var fileStreamFactory = new MockFileStreamFactory(fileSystem); - // Act - var result = fileStreamFactory.New(@"c:\existing.txt", fileMode, FileAccess.Write); + // Act + var result = fileStreamFactory.New(@"c:\existing.txt", fileMode, FileAccess.Write); - // Assert - await That(result).IsNotNull(); - } + // Assert + await That(result).IsNotNull(); + } - [Test] - [TestCase(FileMode.Create)] - [TestCase(FileMode.Append)] - public async Task MockFileStreamFactory_CreateForNonExistingFile_ShouldReturnStream(FileMode fileMode) - { - // Arrange - var fileSystem = new MockFileSystem(); - var fileStreamFactory = new MockFileStreamFactory(fileSystem); + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.Append)] + public async Task MockFileStreamFactory_CreateForNonExistingFile_ShouldReturnStream(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + var fileStreamFactory = new MockFileStreamFactory(fileSystem); - // Act - var result = fileStreamFactory.New(XFS.Path(@"c:\not_existing.txt"), fileMode, FileAccess.Write); + // Act + var result = fileStreamFactory.New(XFS.Path(@"c:\not_existing.txt"), fileMode, FileAccess.Write); - // Assert - await That(result).IsNotNull(); - } + // Assert + await That(result).IsNotNull(); + } + + [Test] + [TestCase(FileMode.Create)] + public async Task MockFileStreamFactory_CreateForAnExistingFile_ShouldReplaceFileContents(FileMode fileMode) + { + var fileSystem = new MockFileSystem(); + string FilePath = XFS.Path("C:\\File.txt"); - [Test] - [TestCase(FileMode.Create)] - public async Task MockFileStreamFactory_CreateForAnExistingFile_ShouldReplaceFileContents(FileMode fileMode) + using (var stream = fileSystem.FileStream.New(FilePath, fileMode, System.IO.FileAccess.Write)) { - var fileSystem = new MockFileSystem(); - string FilePath = XFS.Path("C:\\File.txt"); - - using (var stream = fileSystem.FileStream.New(FilePath, fileMode, System.IO.FileAccess.Write)) - { - var data = Encoding.UTF8.GetBytes("1234567890"); - stream.Write(data, 0, data.Length); - } - - using (var stream = fileSystem.FileStream.New(FilePath, fileMode, System.IO.FileAccess.Write)) - { - var data = Encoding.UTF8.GetBytes("AAAAA"); - stream.Write(data, 0, data.Length); - } - - var text = fileSystem.File.ReadAllText(FilePath); - await That(text).IsEqualTo("AAAAA"); + var data = Encoding.UTF8.GetBytes("1234567890"); + stream.Write(data, 0, data.Length); } - [Test] - [TestCase(FileMode.Create)] - [TestCase(FileMode.Open)] - [TestCase(FileMode.CreateNew)] - public async Task MockFileStreamFactory_CreateInNonExistingDirectory_ShouldThrowDirectoryNotFoundException(FileMode fileMode) + using (var stream = fileSystem.FileStream.New(FilePath, fileMode, System.IO.FileAccess.Write)) { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + var data = Encoding.UTF8.GetBytes("AAAAA"); + stream.Write(data, 0, data.Length); + } - // Act - var fileStreamFactory = new MockFileStreamFactory(fileSystem); + var text = fileSystem.File.ReadAllText(FilePath); + await That(text).IsEqualTo("AAAAA"); + } - // Assert - await That(() => fileStreamFactory.New(XFS.Path(@"C:\Test\NonExistingDirectory\some_random_file.txt"), fileMode)).Throws(); - } + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.Open)] + [TestCase(FileMode.CreateNew)] + public async Task MockFileStreamFactory_CreateInNonExistingDirectory_ShouldThrowDirectoryNotFoundException(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - [Test] - public async Task MockFileStreamFactory_AppendAccessWithReadWriteMode_ShouldThrowArgumentException() - { - var fileSystem = new MockFileSystem(); - - await That(() => - { - fileSystem.FileStream.New(XFS.Path(@"c:\path.txt"), FileMode.Append, FileAccess.ReadWrite); - }).Throws(); - } + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); - [Test] - [TestCase(FileMode.Append)] - [TestCase(FileMode.Truncate)] - [TestCase(FileMode.Create)] - [TestCase(FileMode.CreateNew)] - [TestCase(FileMode.Append)] - public async Task MockFileStreamFactory_InvalidModeForReadAccess_ShouldThrowArgumentException(FileMode fileMode) + // Assert + await That(() => fileStreamFactory.New(XFS.Path(@"C:\Test\NonExistingDirectory\some_random_file.txt"), fileMode)).Throws(); + } + + [Test] + public async Task MockFileStreamFactory_AppendAccessWithReadWriteMode_ShouldThrowArgumentException() + { + var fileSystem = new MockFileSystem(); + + await That(() => { - var fileSystem = new MockFileSystem(); + fileSystem.FileStream.New(XFS.Path(@"c:\path.txt"), FileMode.Append, FileAccess.ReadWrite); + }).Throws(); + } - await That(() => - { - fileSystem.FileStream.New(XFS.Path(@"c:\path.txt"), fileMode, FileAccess.Read); - }).Throws(); - } + [Test] + [TestCase(FileMode.Append)] + [TestCase(FileMode.Truncate)] + [TestCase(FileMode.Create)] + [TestCase(FileMode.CreateNew)] + [TestCase(FileMode.Append)] + public async Task MockFileStreamFactory_InvalidModeForReadAccess_ShouldThrowArgumentException(FileMode fileMode) + { + var fileSystem = new MockFileSystem(); - [Test] - [TestCase(FileMode.Open)] - [TestCase(FileMode.Truncate)] - public async Task MockFileStreamFactory_OpenNonExistingFile_ShouldThrowFileNotFoundException(FileMode fileMode) + await That(() => { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + fileSystem.FileStream.New(XFS.Path(@"c:\path.txt"), fileMode, FileAccess.Read); + }).Throws(); + } - // Act - var fileStreamFactory = new MockFileStreamFactory(fileSystem); + [Test] + [TestCase(FileMode.Open)] + [TestCase(FileMode.Truncate)] + public async Task MockFileStreamFactory_OpenNonExistingFile_ShouldThrowFileNotFoundException(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - // Assert - await That(() => fileStreamFactory.New(XFS.Path(@"C:\Test\some_random_file.txt"), fileMode)).Throws(); - } + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); - [Test] - [TestCase(FileMode.CreateNew)] - public async Task MockFileStreamFactory_CreateExistingFile_Should_Throw_IOException(FileMode fileMode) - { - // Arrange - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"C:\Test\some_random_file.txt"); - fileSystem.AddFile(path, string.Empty); + // Assert + await That(() => fileStreamFactory.New(XFS.Path(@"C:\Test\some_random_file.txt"), fileMode)).Throws(); + } + + [Test] + [TestCase(FileMode.CreateNew)] + public async Task MockFileStreamFactory_CreateExistingFile_Should_Throw_IOException(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\Test\some_random_file.txt"); + fileSystem.AddFile(path, string.Empty); - // Act - var fileStreamFactory = new MockFileStreamFactory(fileSystem); + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); - // Assert - await That(() => fileStreamFactory.New(path, fileMode)).Throws(); + // Assert + await That(() => fileStreamFactory.New(path, fileMode)).Throws(); - } + } - [Test] - [TestCase(FileMode.Create)] - [TestCase(FileMode.CreateNew)] - [TestCase(FileMode.OpenOrCreate)] - public async Task MockFileStreamFactory_CreateWithRelativePath_CreatesFileInCurrentDirectory(FileMode fileMode) - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + [TestCase(FileMode.Create)] + [TestCase(FileMode.CreateNew)] + [TestCase(FileMode.OpenOrCreate)] + public async Task MockFileStreamFactory_CreateWithRelativePath_CreatesFileInCurrentDirectory(FileMode fileMode) + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - var fileStreamFactory = new MockFileStreamFactory(fileSystem); - fileStreamFactory.New("some_random_file.txt", fileMode); + // Act + var fileStreamFactory = new MockFileStreamFactory(fileSystem); + fileStreamFactory.New("some_random_file.txt", fileMode); - // Assert - await That(fileSystem.File.Exists(XFS.Path("./some_random_file.txt"))).IsTrue(); - } + // Assert + await That(fileSystem.File.Exists(XFS.Path("./some_random_file.txt"))).IsTrue(); + } - [Test] - public async Task MockFileStream_CanRead_ReturnsFalseForAWriteOnlyStream() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFileStream_CanRead_ReturnsFalseForAWriteOnlyStream() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - var fileStream = fileSystem.FileStream.New("file.txt", FileMode.CreateNew, FileAccess.Write); + // Act + var fileStream = fileSystem.FileStream.New("file.txt", FileMode.CreateNew, FileAccess.Write); - // Assert - await That(fileStream.CanRead).IsFalse(); - } + // Assert + await That(fileStream.CanRead).IsFalse(); } } \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamTests.cs index f06053715..b82566d9a 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileStreamTests.cs @@ -1,394 +1,393 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using System.Collections.Generic; - using System.Threading.Tasks; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using System.Collections.Generic; +using System.Threading.Tasks; - using NUnit.Framework; +using NUnit.Framework; - using XFS = MockUnixSupport; +using XFS = MockUnixSupport; - [TestFixture] - public class MockFileStreamTests +[TestFixture] +public class MockFileStreamTests +{ + [Test] + public async Task MockFileStream_Flush_WritesByteToFile() { - [Test] - public async Task MockFileStream_Flush_WritesByteToFile() - { - // Arrange - var filepath = XFS.Path(@"C:\something\foo.txt"); - var fileSystem = new MockFileSystem(new Dictionary()); - fileSystem.AddDirectory(XFS.Path(@"C:\something")); + // Arrange + var filepath = XFS.Path(@"C:\something\foo.txt"); + var fileSystem = new MockFileSystem(new Dictionary()); + fileSystem.AddDirectory(XFS.Path(@"C:\something")); - var cut = new MockFileStream(fileSystem, filepath, FileMode.Create); + var cut = new MockFileStream(fileSystem, filepath, FileMode.Create); - // Act - cut.WriteByte(255); - cut.Flush(); + // Act + cut.WriteByte(255); + cut.Flush(); - // Assert - await That(fileSystem.GetFile(filepath).Contents) - .IsEqualTo(new byte[] { 255 }); - } + // Assert + await That(fileSystem.GetFile(filepath).Contents) + .IsEqualTo(new byte[] { 255 }); + } - [Test] - public async Task MockFileStream_FlushAsync_WritesByteToFile() - { - // bug replication test for issue - // https://github.com/TestableIO/System.IO.Abstractions/issues/959 + [Test] + public async Task MockFileStream_FlushAsync_WritesByteToFile() + { + // bug replication test for issue + // https://github.com/TestableIO/System.IO.Abstractions/issues/959 - // Arrange - var filepath = XFS.Path(@"C:\something\foo.txt"); - var fileSystem = new MockFileSystem(new Dictionary()); - fileSystem.AddDirectory(XFS.Path(@"C:\something")); + // Arrange + var filepath = XFS.Path(@"C:\something\foo.txt"); + var fileSystem = new MockFileSystem(new Dictionary()); + fileSystem.AddDirectory(XFS.Path(@"C:\something")); - var cut = new MockFileStream(fileSystem, filepath, FileMode.Create); + var cut = new MockFileStream(fileSystem, filepath, FileMode.Create); - // Act - await cut.WriteAsync(new byte[] { 255 }, 0, 1); - await cut.FlushAsync(); + // Act + await cut.WriteAsync(new byte[] { 255 }, 0, 1); + await cut.FlushAsync(); - // Assert - await That(fileSystem.GetFile(filepath).Contents) - .IsEqualTo(new byte[] { 255 }); - } + // Assert + await That(fileSystem.GetFile(filepath).Contents) + .IsEqualTo(new byte[] { 255 }); + } - [Test] - public async Task MockFileStream_Dispose_ShouldNotResurrectFile() - { - // path in this test case is a subject to Directory.GetParent(path) Linux issue - // https://github.com/TestableIO/System.IO.Abstractions/issues/395 - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\some_folder\\test"); - var directory = fileSystem.Path.GetDirectoryName(path); - fileSystem.AddFile(path, new MockFileData("Bla")); - var stream = fileSystem.File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete); - - var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; - fileSystem.File.Delete(path); - var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; - stream.Dispose(); - var fileCount3 = fileSystem.Directory.GetFiles(directory, "*").Length; - - await That(fileCount1).IsEqualTo(1).Because("File should have existed"); - await That(fileCount2).IsEqualTo(0).Because("File should have been deleted"); - await That(fileCount3).IsEqualTo(0).Because("Disposing stream should not have resurrected the file"); - } + [Test] + public async Task MockFileStream_Dispose_ShouldNotResurrectFile() + { + // path in this test case is a subject to Directory.GetParent(path) Linux issue + // https://github.com/TestableIO/System.IO.Abstractions/issues/395 + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\some_folder\\test"); + var directory = fileSystem.Path.GetDirectoryName(path); + fileSystem.AddFile(path, new MockFileData("Bla")); + var stream = fileSystem.File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete); + + var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length; + fileSystem.File.Delete(path); + var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length; + stream.Dispose(); + var fileCount3 = fileSystem.Directory.GetFiles(directory, "*").Length; + + await That(fileCount1).IsEqualTo(1).Because("File should have existed"); + await That(fileCount2).IsEqualTo(0).Because("File should have been deleted"); + await That(fileCount3).IsEqualTo(0).Because("Disposing stream should not have resurrected the file"); + } - [Test] - public async Task MockFileStream_Constructor_Reading_Nonexistent_File_Throws_Exception() - { - // Arrange - var nonexistentFilePath = XFS.Path(@"c:\something\foo.txt"); - var fileSystem = new MockFileSystem(new Dictionary()); - fileSystem.AddDirectory(XFS.Path(@"C:\something")); + [Test] + public async Task MockFileStream_Constructor_Reading_Nonexistent_File_Throws_Exception() + { + // Arrange + var nonexistentFilePath = XFS.Path(@"c:\something\foo.txt"); + var fileSystem = new MockFileSystem(new Dictionary()); + fileSystem.AddDirectory(XFS.Path(@"C:\something")); - // Act - await That(() => new MockFileStream(fileSystem, nonexistentFilePath, FileMode.Open)).Throws(); + // Act + await That(() => new MockFileStream(fileSystem, nonexistentFilePath, FileMode.Open)).Throws(); - // Assert - expect an exception - } + // Assert - expect an exception + } - [Test] - public async Task MockFileStream_Constructor_ReadTypeNotWritable() + [Test] + public async Task MockFileStream_Constructor_ReadTypeNotWritable() + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var filePath = @"C:\test.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { filePath, new MockFileData("hi") } - }); + { filePath, new MockFileData("hi") } + }); - // Act - var stream = new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Read); + // Act + var stream = new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Read); - await That(stream.CanWrite).IsFalse(); - await That(() => stream.WriteByte(1)).Throws(); - } + await That(stream.CanWrite).IsFalse(); + await That(() => stream.WriteByte(1)).Throws(); + } - [Test] - [TestCase(FileAccess.Write)] - [TestCase(FileAccess.ReadWrite)] - public async Task MockFileStream_Constructor_WriteAccessOnReadOnlyFile_Throws_Exception( - FileAccess fileAccess) + [Test] + [TestCase(FileAccess.Write)] + [TestCase(FileAccess.ReadWrite)] + public async Task MockFileStream_Constructor_WriteAccessOnReadOnlyFile_Throws_Exception( + FileAccess fileAccess) + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var filePath = @"C:\test.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { filePath, new MockFileData("hi") { Attributes = FileAttributes.ReadOnly } } - }); + { filePath, new MockFileData("hi") { Attributes = FileAttributes.ReadOnly } } + }); - // Act - await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).Throws(); - } + // Act + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).Throws(); + } - [Test] - public async Task MockFileStream_Constructor_ReadAccessOnReadOnlyFile_Does_Not_Throw_Exception() + [Test] + public async Task MockFileStream_Constructor_ReadAccessOnReadOnlyFile_Does_Not_Throw_Exception() + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var filePath = @"C:\test.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { filePath, new MockFileData("hi") { Attributes = FileAttributes.ReadOnly } } - }); + { filePath, new MockFileData("hi") { Attributes = FileAttributes.ReadOnly } } + }); - // Act - await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Read)).DoesNotThrow(); - } + // Act + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Read)).DoesNotThrow(); + } - [Test] - public async Task MockFileStream_Constructor_WriteAccessOnNonReadOnlyFile_Does_Not_Throw_Exception() + [Test] + public async Task MockFileStream_Constructor_WriteAccessOnNonReadOnlyFile_Does_Not_Throw_Exception() + { + // Arrange + var filePath = @"C:\test.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var filePath = @"C:\test.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { filePath, new MockFileData("hi") { Attributes = FileAttributes.Normal } } - }); + { filePath, new MockFileData("hi") { Attributes = FileAttributes.Normal } } + }); - // Act - await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Write)).DoesNotThrow(); - } + // Act + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, FileAccess.Write)).DoesNotThrow(); + } - [Test] - [TestCase(FileShare.None, FileAccess.Read)] - [TestCase(FileShare.None, FileAccess.ReadWrite)] - [TestCase(FileShare.None, FileAccess.Write)] - [TestCase(FileShare.Read, FileAccess.Write)] - [TestCase(FileShare.Read, FileAccess.ReadWrite)] - [TestCase(FileShare.Write, FileAccess.Read)] - public async Task MockFileStream_Constructor_Insufficient_FileShare_Throws_Exception( - FileShare allowedFileShare, - FileAccess fileAccess) + [Test] + [TestCase(FileShare.None, FileAccess.Read)] + [TestCase(FileShare.None, FileAccess.ReadWrite)] + [TestCase(FileShare.None, FileAccess.Write)] + [TestCase(FileShare.Read, FileAccess.Write)] + [TestCase(FileShare.Read, FileAccess.ReadWrite)] + [TestCase(FileShare.Write, FileAccess.Read)] + public async Task MockFileStream_Constructor_Insufficient_FileShare_Throws_Exception( + FileShare allowedFileShare, + FileAccess fileAccess) + { + var filePath = @"C:\locked.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - var filePath = @"C:\locked.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { filePath, new MockFileData("cannot access") { AllowedFileShare = allowedFileShare } } - }); + { filePath, new MockFileData("cannot access") { AllowedFileShare = allowedFileShare } } + }); - await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).Throws(); - } + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).Throws(); + } - [Test] - [TestCase(FileShare.Read, FileAccess.Read)] - [TestCase(FileShare.Read | FileShare.Write, FileAccess.Read)] - [TestCase(FileShare.Read | FileShare.Write, FileAccess.ReadWrite)] - [TestCase(FileShare.ReadWrite, FileAccess.Read)] - [TestCase(FileShare.ReadWrite, FileAccess.ReadWrite)] - [TestCase(FileShare.ReadWrite, FileAccess.Write)] - public async Task MockFileStream_Constructor_Sufficient_FileShare_Does_Not_Throw_Exception( - FileShare allowedFileShare, - FileAccess fileAccess) + [Test] + [TestCase(FileShare.Read, FileAccess.Read)] + [TestCase(FileShare.Read | FileShare.Write, FileAccess.Read)] + [TestCase(FileShare.Read | FileShare.Write, FileAccess.ReadWrite)] + [TestCase(FileShare.ReadWrite, FileAccess.Read)] + [TestCase(FileShare.ReadWrite, FileAccess.ReadWrite)] + [TestCase(FileShare.ReadWrite, FileAccess.Write)] + public async Task MockFileStream_Constructor_Sufficient_FileShare_Does_Not_Throw_Exception( + FileShare allowedFileShare, + FileAccess fileAccess) + { + var filePath = @"C:\locked.txt"; + var fileSystem = new MockFileSystem(new Dictionary { - var filePath = @"C:\locked.txt"; - var fileSystem = new MockFileSystem(new Dictionary - { - { filePath, new MockFileData("cannot access") { AllowedFileShare = allowedFileShare } } - }); + { filePath, new MockFileData("cannot access") { AllowedFileShare = allowedFileShare } } + }); - await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).DoesNotThrow(); - } + await That(() => new MockFileStream(fileSystem, filePath, FileMode.Open, fileAccess)).DoesNotThrow(); + } - [Test] - public async Task MockFileStream_Close_MultipleCallsDoNotThrow() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test"); - fileSystem.AddFile(path, new MockFileData("Bla")); - var stream = fileSystem.File.OpenRead(path); + [Test] + public async Task MockFileStream_Close_MultipleCallsDoNotThrow() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData("Bla")); + var stream = fileSystem.File.OpenRead(path); - // Act - stream.Close(); + // Act + stream.Close(); - // Assert - await That(() => stream.Close()).DoesNotThrow(); - } + // Assert + await That(() => stream.Close()).DoesNotThrow(); + } - [Test] - public async Task MockFileStream_Dispose_MultipleCallsDoNotThrow() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test"); - fileSystem.AddFile(path, new MockFileData("Bla")); - var stream = fileSystem.File.OpenRead(path); + [Test] + public async Task MockFileStream_Dispose_MultipleCallsDoNotThrow() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData("Bla")); + var stream = fileSystem.File.OpenRead(path); - // Act - stream.Dispose(); + // Act + stream.Dispose(); - // Assert - await That(() => stream.Dispose()).DoesNotThrow(); - } + // Assert + await That(() => stream.Dispose()).DoesNotThrow(); + } - [Test] - public async Task MockFileStream_Dispose_OperationsAfterDisposeThrow() - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test"); - fileSystem.AddFile(path, new MockFileData(new byte[0])); - var stream = fileSystem.FileInfo.New(path).OpenWrite(); + [Test] + public async Task MockFileStream_Dispose_OperationsAfterDisposeThrow() + { + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData(new byte[0])); + var stream = fileSystem.FileInfo.New(path).OpenWrite(); + + // Act + stream.Dispose(); + // Assert + await That(() => stream.WriteByte(0)).Throws(); + } + + [Test] + public async Task MockFileStream_Flush_ShouldNotChangePosition() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData(new byte[0])); + + using (var stream = fileSystem.FileInfo.New(path).OpenWrite()) + { // Act - stream.Dispose(); + stream.Write(new byte[400], 0, 400); + stream.Seek(200, SeekOrigin.Begin); + stream.Flush(); // Assert - await That(() => stream.WriteByte(0)).Throws(); + await That(stream.Position).IsEqualTo(200); } + } - [Test] - public async Task MockFileStream_Flush_ShouldNotChangePosition() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test"); - fileSystem.AddFile(path, new MockFileData(new byte[0])); - - using (var stream = fileSystem.FileInfo.New(path).OpenWrite()) - { - // Act - stream.Write(new byte[400], 0, 400); - stream.Seek(200, SeekOrigin.Begin); - stream.Flush(); - - // Assert - await That(stream.Position).IsEqualTo(200); - } - } + [Test] + public async Task MockFileStream_FlushBool_ShouldNotChangePosition([Values] bool flushToDisk) + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path("C:\\test"); + fileSystem.AddFile(path, new MockFileData(new byte[0])); - [Test] - public async Task MockFileStream_FlushBool_ShouldNotChangePosition([Values] bool flushToDisk) + using (var stream = fileSystem.FileInfo.New(path).OpenWrite()) { - // Arrange - var fileSystem = new MockFileSystem(); - var path = XFS.Path("C:\\test"); - fileSystem.AddFile(path, new MockFileData(new byte[0])); - - using (var stream = fileSystem.FileInfo.New(path).OpenWrite()) - { - // Act - stream.Write(new byte[400], 0, 400); - stream.Seek(200, SeekOrigin.Begin); - stream.Flush(flushToDisk); - - // Assert - await That(stream.Position).IsEqualTo(200); - } + // Act + stream.Write(new byte[400], 0, 400); + stream.Seek(200, SeekOrigin.Begin); + stream.Flush(flushToDisk); + + // Assert + await That(stream.Position).IsEqualTo(200); } + } - [Test] - public async Task MockFileStream_Null_ShouldReturnSingletonObject() - { - var result1 = MockFileStream.Null; - var result2 = MockFileStream.Null; + [Test] + public async Task MockFileStream_Null_ShouldReturnSingletonObject() + { + var result1 = MockFileStream.Null; + var result2 = MockFileStream.Null; - await That(result1).IsSameAs(result2); - } + await That(result1).IsSameAs(result2); + } - #if FEATURE_ASYNC_FILE - [Test] - public async Task MockFileStream_DisposeAsync_ShouldNotThrow() +#if FEATURE_ASYNC_FILE + [Test] + public async Task MockFileStream_DisposeAsync_ShouldNotThrow() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("foo.txt", ""); - { - await using var reportStream = fileSystem.File.OpenRead("foo.txt"); - } + await using var reportStream = fileSystem.File.OpenRead("foo.txt"); } - #endif + } +#endif - [Test] - public async Task MockFileStream_Null_ShouldHaveExpectedProperties() - { - var result = MockFileStream.Null; + [Test] + public async Task MockFileStream_Null_ShouldHaveExpectedProperties() + { + var result = MockFileStream.Null; - await That(result.Name).IsEqualTo("."); - await That(result.Length).IsEqualTo(0); - await That(result.IsAsync).IsTrue(); - } + await That(result.Name).IsEqualTo("."); + await That(result.Length).IsEqualTo(0); + await That(result.IsAsync).IsTrue(); + } - [Test] - [TestCase(0)] - [TestCase(-1)] - public async Task MockFileStream_WhenBufferSizeIsNotPositive_ShouldThrowArgumentNullException(int bufferSize) - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("foo.txt", ""); - fileSystem.File.WriteAllText("bar.txt", ""); - using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); - using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); - - async Task Act() => - await source.CopyToAsync(destination, bufferSize); - await That(Act).Throws(); - } + [Test] + [TestCase(0)] + [TestCase(-1)] + public async Task MockFileStream_WhenBufferSizeIsNotPositive_ShouldThrowArgumentNullException(int bufferSize) + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); + + async Task Act() => + await source.CopyToAsync(destination, bufferSize); + await That(Act).Throws(); + } - [Test] - public async Task MockFileStream_WhenDestinationIsClosed_ShouldThrowObjectDisposedException() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("foo.txt", ""); - using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); - using var destination = new MemoryStream(); - destination.Close(); - - async Task Act() => - await source.CopyToAsync(destination); - await That(Act).Throws(); - } + [Test] + public async Task MockFileStream_WhenDestinationIsClosed_ShouldThrowObjectDisposedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = new MemoryStream(); + destination.Close(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); + } - [Test] - public async Task MockFileStream_WhenDestinationIsNull_ShouldThrowArgumentNullException() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("foo.txt", ""); - using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + [Test] + public async Task MockFileStream_WhenDestinationIsNull_ShouldThrowArgumentNullException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); - async Task Act() => - await source.CopyToAsync(null); - await That(Act).Throws(); - } + async Task Act() => + await source.CopyToAsync(null); + await That(Act).Throws(); + } - [Test] - public async Task MockFileStream_WhenDestinationIsReadOnly_ShouldThrowNotSupportedException() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("foo.txt", ""); - fileSystem.File.WriteAllText("bar.txt", ""); - using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); - using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenRead(); - - async Task Act() => - await source.CopyToAsync(destination); - await That(Act).Throws(); - } + [Test] + public async Task MockFileStream_WhenDestinationIsReadOnly_ShouldThrowNotSupportedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenRead(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); + } - [Test] - public async Task MockFileStream_WhenSourceIsClosed_ShouldThrowObjectDisposedException() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("foo.txt", ""); - fileSystem.File.WriteAllText("bar.txt", ""); - using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); - using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); - source.Close(); - - async Task Act() => - await source.CopyToAsync(destination); - await That(Act).Throws(); - } + [Test] + public async Task MockFileStream_WhenSourceIsClosed_ShouldThrowObjectDisposedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenRead(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); + source.Close(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); + } - [Test] - public async Task MockFileStream_WhenSourceIsWriteOnly_ShouldThrowNotSupportedException() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("foo.txt", ""); - fileSystem.File.WriteAllText("bar.txt", ""); - using var source = fileSystem.FileInfo.New(@"foo.txt").OpenWrite(); - using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); - - async Task Act() => - await source.CopyToAsync(destination); - await That(Act).Throws(); - } + [Test] + public async Task MockFileStream_WhenSourceIsWriteOnly_ShouldThrowNotSupportedException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("foo.txt", ""); + fileSystem.File.WriteAllText("bar.txt", ""); + using var source = fileSystem.FileInfo.New(@"foo.txt").OpenWrite(); + using var destination = fileSystem.FileInfo.New(@"bar.txt").OpenWrite(); + + async Task Act() => + await source.CopyToAsync(destination); + await That(Act).Throws(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSymlinkTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSymlinkTests.cs index a1add0c40..0b92c94b0 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSymlinkTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSymlinkTests.cs @@ -1,325 +1,324 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; - [TestFixture] - public class MockFileSymlinkTests - { +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileSymlinkTests +{ #if FEATURE_CREATE_SYMBOLIC_LINK - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldReturnFileSystemInfo() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); - var path = XFS.Path(@"C:\bar.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); - - // Act - IFileSystemInfo fileSystemInfo = fileSystem.File.CreateSymbolicLink(path, pathToTarget); - - // Assert - await That(fileSystemInfo.FullName).IsEqualTo(path); - await That(fileSystemInfo.LinkTarget).IsEqualTo(pathToTarget); - } + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldReturnFileSystemInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var path = XFS.Path(@"C:\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + IFileSystemInfo fileSystemInfo = fileSystem.File.CreateSymbolicLink(path, pathToTarget); + + // Assert + await That(fileSystemInfo.FullName).IsEqualTo(path); + await That(fileSystemInfo.LinkTarget).IsEqualTo(pathToTarget); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldSucceedFromFileInfo() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); - var path = XFS.Path(@"C:\bar.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); - - // Act - fileSystem.File.CreateSymbolicLink(path, pathToTarget); - IFileInfo directoryInfo = fileSystem.FileInfo.New(path); - - // Assert - await That(directoryInfo.FullName).IsEqualTo(path); - await That(directoryInfo.LinkTarget).IsEqualTo(pathToTarget); - } + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldSucceedFromFileInfo() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var path = XFS.Path(@"C:\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + fileSystem.File.CreateSymbolicLink(path, pathToTarget); + IFileInfo directoryInfo = fileSystem.FileInfo.New(path); + + // Assert + await That(directoryInfo.FullName).IsEqualTo(path); + await That(directoryInfo.LinkTarget).IsEqualTo(pathToTarget); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithNullPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithNullPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(null, pathToTarget)).Throws(); + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(null, pathToTarget)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("path"); - } + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithNullTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"C:\Folder\foo.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(path, data); + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithNullTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(path, data); - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, null)).Throws(); + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, null)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("pathToTarget"); - } + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithEmptyPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithEmptyPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + var pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink("", pathToTarget)).Throws(); + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink("", pathToTarget)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("path"); - } + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithEmptyTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\Folder\foo.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(path, data); + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithEmptyTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(path, data); - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, "")).Throws(); + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, "")).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("pathToTarget"); - } + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(" ", pathToTarget)).Throws(); + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(" ", pathToTarget)).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("path"); - } + // Assert + await That(ex.ParamName).IsEqualTo("path"); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\Folder\foo.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(path, data); + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(path, data); - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, " ")).Throws(); + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, " ")).Throws(); - // Assert - await That(ex.ParamName).IsEqualTo("pathToTarget"); - } + // Assert + await That(ex.ParamName).IsEqualTo("pathToTarget"); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalCharactersInPath() - { - // Arrange - var fileSystem = new MockFileSystem(); - string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalCharactersInPath() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); - // Act - Action ex = () => fileSystem.File.CreateSymbolicLink(@"C:\bar.txt_?_", pathToTarget); + // Act + Action ex = () => fileSystem.File.CreateSymbolicLink(@"C:\bar.txt_?_", pathToTarget); - // Assert - await That(ex).Throws(); - } + // Assert + await That(ex).Throws(); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalCharactersInTarget() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\Folder\foo.txt"); + public async Task MockFile_CreateSymbolicLink_ShouldFailWithIllegalCharactersInTarget() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); - // Act - Action ex = () => fileSystem.File.CreateSymbolicLink(path, @"C:\bar.txt_?_"); + // Act + Action ex = () => fileSystem.File.CreateSymbolicLink(path, @"C:\bar.txt_?_"); - // Assert - await That(ex).Throws(); - } + // Assert + await That(ex).Throws(); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailIfPathExists() - { - // Arrange - var fileSystem = new MockFileSystem(); - string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); - string path = XFS.Path(@"C:\Folder\bar.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); - fileSystem.AddFile(path, data); - - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); - - // Assert - await That(ex.Message).Contains("path"); - } + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailIfPathExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string pathToTarget = XFS.Path(@"C:\Folder\foo.txt"); + string path = XFS.Path(@"C:\Folder\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + fileSystem.AddFile(path, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains("path"); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailIfTargetDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - string dir = XFS.Path(@"C:\Folder"); - string path = XFS.Path(@"C:\Folder\foo.txt"); - string pathToTarget = XFS.Path(@"C:\bar.txt"); - fileSystem.AddDirectory(dir); - - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); - - // Assert - await That(ex.Message).Contains(pathToTarget); - } + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailIfTargetDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + string dir = XFS.Path(@"C:\Folder"); + string path = XFS.Path(@"C:\Folder\foo.txt"); + string pathToTarget = XFS.Path(@"C:\bar.txt"); + fileSystem.AddDirectory(dir); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains(pathToTarget); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldFailIfPathDirectoryDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"C:\Folder\foo.txt"); - string pathToTarget = XFS.Path(@"C:\bar.txt"); - var data = new MockFileData("foobar"); - fileSystem.AddFile(pathToTarget, data); - - // Act - var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); - - // Assert - await That(ex.Message).Contains(path); - } + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldFailIfPathDirectoryDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"C:\Folder\foo.txt"); + string pathToTarget = XFS.Path(@"C:\bar.txt"); + var data = new MockFileData("foobar"); + fileSystem.AddFile(pathToTarget, data); + + // Act + var ex = await That(() => fileSystem.File.CreateSymbolicLink(path, pathToTarget)).Throws(); + + // Assert + await That(ex.Message).Contains(path); + } - [Test] - public async Task MockFile_CreateSymbolicLink_ShouldSetReparsePointAttribute() - { - var path = "foo.txt"; - var pathToTarget = "bar.txt"; - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText(pathToTarget, "some content"); + [Test] + public async Task MockFile_CreateSymbolicLink_ShouldSetReparsePointAttribute() + { + var path = "foo.txt"; + var pathToTarget = "bar.txt"; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText(pathToTarget, "some content"); - fileSystem.File.CreateSymbolicLink(path, pathToTarget); + fileSystem.File.CreateSymbolicLink(path, pathToTarget); - var attributes = fileSystem.FileInfo.New(path).Attributes; - await That(attributes.HasFlag(FileAttributes.ReparsePoint)).IsTrue(); - } + var attributes = fileSystem.FileInfo.New(path).Attributes; + await That(attributes.HasFlag(FileAttributes.ReparsePoint)).IsTrue(); + } - [Test] - public async Task MockFile_ResolveLinkTarget_ShouldReturnPathOfTargetLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - fileSystem.File.CreateSymbolicLink("foo", "bar"); + [Test] + public async Task MockFile_ResolveLinkTarget_ShouldReturnPathOfTargetLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); - var result = fileSystem.File.ResolveLinkTarget("foo", false); + var result = fileSystem.File.ResolveLinkTarget("foo", false); - await That(result.Name).IsEqualTo("bar"); - } + await That(result.Name).IsEqualTo("bar"); + } - [Test] - public async Task MockFile_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + [Test] + public async Task MockFile_ResolveLinkTarget_WithFinalTarget_ShouldReturnPathOfTargetLink() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) { - // The maximum number of symbolic links that are followed: - // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks - var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - var previousPath = "bar"; - for (int i = 0; i < maxResolveLinks; i++) - { - string newPath = $"foo-{i}"; - fileSystem.File.CreateSymbolicLink(newPath, previousPath); - previousPath = newPath; - } - - var result = fileSystem.File.ResolveLinkTarget(previousPath, true); - - await That(result.Name).IsEqualTo("bar"); + string newPath = $"foo-{i}"; + fileSystem.File.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; } - [Test] - public async Task MockFile_ResolveLinkTarget_WithFinalTargetWithTooManyLinks_ShouldThrowIOException() + var result = fileSystem.File.ResolveLinkTarget(previousPath, true); + + await That(result.Name).IsEqualTo("bar"); + } + + [Test] + public async Task MockFile_ResolveLinkTarget_WithFinalTargetWithTooManyLinks_ShouldThrowIOException() + { + // The maximum number of symbolic links that are followed: + // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks + var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; + maxResolveLinks++; + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + var previousPath = "bar"; + for (int i = 0; i < maxResolveLinks; i++) { - // The maximum number of symbolic links that are followed: - // https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.resolvelinktarget?view=net-6.0#remarks - var maxResolveLinks = XFS.IsWindowsPlatform() ? 63 : 40; - maxResolveLinks++; - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - var previousPath = "bar"; - for (int i = 0; i < maxResolveLinks; i++) - { - string newPath = $"foo-{i}"; - fileSystem.File.CreateSymbolicLink(newPath, previousPath); - previousPath = newPath; - } - - await That(() => fileSystem.File.ResolveLinkTarget(previousPath, true)).Throws(); + string newPath = $"foo-{i}"; + fileSystem.File.CreateSymbolicLink(newPath, previousPath); + previousPath = newPath; } - [Test] - public async Task MockFile_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() - { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - fileSystem.File.CreateSymbolicLink("foo", "bar"); - fileSystem.File.CreateSymbolicLink("foo1", "foo"); + await That(() => fileSystem.File.ResolveLinkTarget(previousPath, true)).Throws(); + } - var result = fileSystem.File.ResolveLinkTarget("foo1", false); + [Test] + public async Task MockFile_ResolveLinkTarget_WithoutFinalTarget_ShouldReturnFirstLink() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + fileSystem.File.CreateSymbolicLink("foo1", "foo"); - await That(result.Name).IsEqualTo("foo"); - } + var result = fileSystem.File.ResolveLinkTarget("foo1", false); + + await That(result.Name).IsEqualTo("foo"); + } - [Test] - public async Task MockFile_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + [Test] + public async Task MockFile_ResolveLinkTarget_WithoutTargetLink_ShouldThrowIOException() + { + var fileSystem = new MockFileSystem(); + fileSystem.File.WriteAllText("bar", "some content"); + fileSystem.File.CreateSymbolicLink("foo", "bar"); + + await That(() => { - var fileSystem = new MockFileSystem(); - fileSystem.File.WriteAllText("bar", "some content"); - fileSystem.File.CreateSymbolicLink("foo", "bar"); - - await That(() => - { - fileSystem.File.ResolveLinkTarget("bar", false); - }).Throws(); - } -#endif + fileSystem.File.ResolveLinkTarget("bar", false); + }).Throws(); } -} +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemOptionTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemOptionTests.cs index 69427f7aa..26cede9c4 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemOptionTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemOptionTests.cs @@ -1,40 +1,39 @@ using NUnit.Framework; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSystemOptionTests { - [TestFixture] - public class MockFileSystemOptionTests + [Test] + [TestCase(true)] + [TestCase(false)] + public async Task CreateDefaultTempDir_ShouldBeConsidered(bool createTempDir) { - [Test] - [TestCase(true)] - [TestCase(false)] - public async Task CreateDefaultTempDir_ShouldBeConsidered(bool createTempDir) + var fileSystem = new MockFileSystem(new MockFileSystemOptions { - var fileSystem = new MockFileSystem(new MockFileSystemOptions - { - CreateDefaultTempDir = createTempDir - }); + CreateDefaultTempDir = createTempDir + }); - var result = fileSystem.Directory.Exists(fileSystem.Path.GetTempPath()); + var result = fileSystem.Directory.Exists(fileSystem.Path.GetTempPath()); - await That(result).IsEqualTo(createTempDir); - } + await That(result).IsEqualTo(createTempDir); + } - [Test] - [TestCase(@"C:\path")] - [TestCase(@"C:\foo\bar")] - public async Task CurrentDirectory_ShouldBeConsidered(string currentDirectory) + [Test] + [TestCase(@"C:\path")] + [TestCase(@"C:\foo\bar")] + public async Task CurrentDirectory_ShouldBeConsidered(string currentDirectory) + { + currentDirectory = XFS.Path(currentDirectory); + var fileSystem = new MockFileSystem(new MockFileSystemOptions { - currentDirectory = XFS.Path(currentDirectory); - var fileSystem = new MockFileSystem(new MockFileSystemOptions - { - CurrentDirectory = currentDirectory - }); + CurrentDirectory = currentDirectory + }); - var result = fileSystem.Directory.GetCurrentDirectory(); + var result = fileSystem.Directory.GetCurrentDirectory(); - await That(result).IsEqualTo(currentDirectory); - } + await That(result).IsEqualTo(currentDirectory); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemTests.cs index b0030aff4..7252317cd 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemTests.cs @@ -7,161 +7,161 @@ using NUnit.Framework; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSystemTests { - [TestFixture] - public class MockFileSystemTests + [Test] + public async Task MockFileSystem_GetFile_ShouldReturnNullWhenFileIsNotRegistered() { - [Test] - public async Task MockFileSystem_GetFile_ShouldReturnNullWhenFileIsNotRegistered() + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\something\demo.txt", new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { @"c:\something\other.gif", new MockFileData("gif content") } - }); + { @"c:\something\demo.txt", new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { @"c:\something\other.gif", new MockFileData("gif content") } + }); - var result = fileSystem.GetFile(@"c:\something\else.txt"); + var result = fileSystem.GetFile(@"c:\something\else.txt"); - await That(result).IsNull(); - } + await That(result).IsNull(); + } - [Test] - public async Task MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructor() + [Test] + public async Task MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructor() + { + var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); + var fileSystem = new MockFileSystem(new Dictionary { - var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\something\demo.txt", file1 }, - { @"c:\something\other.gif", new MockFileData("gif content") } - }); + { @"c:\something\demo.txt", file1 }, + { @"c:\something\other.gif", new MockFileData("gif content") } + }); - var result = fileSystem.GetFile(@"c:\something\demo.txt"); + var result = fileSystem.GetFile(@"c:\something\demo.txt"); - await That(result).IsEqualTo(file1); - } + await That(result).IsEqualTo(file1); + } - [Test] - [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] - public async Task MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructorWhenPathsDifferByCase() + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFileSystem_GetFile_ShouldReturnFileRegisteredInConstructorWhenPathsDifferByCase() + { + var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); + var fileSystem = new MockFileSystem(new Dictionary { - var file1 = new MockFileData("Demo\r\ntext\ncontent\rvalue"); - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\something\demo.txt", file1 }, - { @"c:\something\other.gif", new MockFileData("gif content") } - }); + { @"c:\something\demo.txt", file1 }, + { @"c:\something\other.gif", new MockFileData("gif content") } + }); - var result = fileSystem.GetFile(@"c:\SomeThing\DEMO.txt"); + var result = fileSystem.GetFile(@"c:\SomeThing\DEMO.txt"); - await That(result).IsEqualTo(file1); - } + await That(result).IsEqualTo(file1); + } - [Test] - [UnixOnly(UnixSpecifics.CaseSensitivity)] - public async Task MockFileSystem_GetFile_ShouldNotReturnFileRegisteredInConstructorWhenPathsDifferByCase() + [Test] + [UnixOnly(UnixSpecifics.CaseSensitivity)] + public async Task MockFileSystem_GetFile_ShouldNotReturnFileRegisteredInConstructorWhenPathsDifferByCase() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { "/something/demo.txt", new MockFileData("Demo\r\ntext\ncontent\rvalue") }, - { "/something/other.gif", new MockFileData("gif content") } - }); + { "/something/demo.txt", new MockFileData("Demo\r\ntext\ncontent\rvalue") }, + { "/something/other.gif", new MockFileData("gif content") } + }); - var result = fileSystem.GetFile("/SomeThing/DEMO.txt"); + var result = fileSystem.GetFile("/SomeThing/DEMO.txt"); - await That(result).IsNull(); - } + await That(result).IsNull(); + } - [Test] - public async Task MockFileSystem_AddFile_ShouldHandleUnnormalizedSlashes() - { - var path = XFS.Path(@"c:\d1\d2\file.txt"); - var alternatePath = XFS.Path("c:/d1/d2/file.txt"); - var alternateParentPath = XFS.Path("c://d1//d2/"); - var fs = new MockFileSystem(); - fs.AddFile(path, new MockFileData("Hello")); + [Test] + public async Task MockFileSystem_AddFile_ShouldHandleUnnormalizedSlashes() + { + var path = XFS.Path(@"c:\d1\d2\file.txt"); + var alternatePath = XFS.Path("c:/d1/d2/file.txt"); + var alternateParentPath = XFS.Path("c://d1//d2/"); + var fs = new MockFileSystem(); + fs.AddFile(path, new MockFileData("Hello")); - var fileCount = fs.Directory.GetFiles(alternateParentPath).Length; - var fileExists = fs.File.Exists(alternatePath); + var fileCount = fs.Directory.GetFiles(alternateParentPath).Length; + var fileExists = fs.File.Exists(alternatePath); - await That(fileCount).IsEqualTo(1); - await That(fileExists).IsTrue(); - } + await That(fileCount).IsEqualTo(1); + await That(fileExists).IsTrue(); + } - [Test] - public async Task MockFileSystem_AddFile_ShouldHandleNullFileDataAsEmpty() + [Test] + public async Task MockFileSystem_AddFile_ShouldHandleNullFileDataAsEmpty() + { + var path = XFS.Path(@"c:\something\nullish.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - var path = XFS.Path(@"c:\something\nullish.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, null } - }); + { path, null } + }); - var result = fileSystem.File.ReadAllText(path); + var result = fileSystem.File.ReadAllText(path); - await That(result).IsEmpty().Because("Null MockFileData should be allowed for and result in an empty file."); - } + await That(result).IsEmpty().Because("Null MockFileData should be allowed for and result in an empty file."); + } - [Test] - public async Task MockFileSystem_AddFile_ShouldReplaceExistingFile() + [Test] + public async Task MockFileSystem_AddFile_ShouldReplaceExistingFile() + { + var path = XFS.Path(@"c:\some\file.txt"); + const string existingContent = "Existing content"; + var fileSystem = new MockFileSystem(new Dictionary { - var path = XFS.Path(@"c:\some\file.txt"); - const string existingContent = "Existing content"; - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData(existingContent) } - }); - await That(fileSystem.GetFile(path).TextContents).IsEqualTo(existingContent); + { path, new MockFileData(existingContent) } + }); + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(existingContent); - const string newContent = "New content"; - fileSystem.AddFile(path, new MockFileData(newContent)); + const string newContent = "New content"; + fileSystem.AddFile(path, new MockFileData(newContent)); - await That(fileSystem.GetFile(path).TextContents).IsEqualTo(newContent); - } + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(newContent); + } - [Test] - public async Task MockFileSystem_AddEmptyFile_ShouldBeEmpty() - { - var path = XFS.Path(@"c:\some\file.txt"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFileSystem_AddEmptyFile_ShouldBeEmpty() + { + var path = XFS.Path(@"c:\some\file.txt"); + var fileSystem = new MockFileSystem(); - fileSystem.AddEmptyFile(path); + fileSystem.AddEmptyFile(path); - await That(fileSystem.GetFile(path).TextContents).IsEqualTo(""); - } + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(""); + } - [Test] - public async Task MockFileSystem_AddEmptyFile_ShouldExist() - { - var fileSystem = new MockFileSystem(); - var path = fileSystem.FileInfo.New(XFS.Path(@"c:\some\file.txt")); + [Test] + public async Task MockFileSystem_AddEmptyFile_ShouldExist() + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.FileInfo.New(XFS.Path(@"c:\some\file.txt")); - fileSystem.AddEmptyFile(path); + fileSystem.AddEmptyFile(path); - await That(path.Exists).IsTrue(); - } + await That(path.Exists).IsTrue(); + } - [Test] - public async Task MockFileSystem_AddFile_ShouldExist() - { - var fileSystem = new MockFileSystem(); - var path = fileSystem.FileInfo.New(XFS.Path(@"c:\some\file.txt")); + [Test] + public async Task MockFileSystem_AddFile_ShouldExist() + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.FileInfo.New(XFS.Path(@"c:\some\file.txt")); - fileSystem.AddFile(path, new MockFileData("stuff")); + fileSystem.AddFile(path, new MockFileData("stuff")); - await That(path.Exists).IsTrue(); - } + await That(path.Exists).IsTrue(); + } - [Test] - public async Task MockFileSystem_AddDirectory_ShouldExist() - { - var fileSystem = new MockFileSystem(); - var path = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\thedir")); + [Test] + public async Task MockFileSystem_AddDirectory_ShouldExist() + { + var fileSystem = new MockFileSystem(); + var path = fileSystem.DirectoryInfo.New(XFS.Path(@"c:\thedir")); - fileSystem.AddDirectory(path); + fileSystem.AddDirectory(path); - await That(path.Exists).IsTrue(); - } + await That(path.Exists).IsTrue(); + } #if !NET9_0_OR_GREATER [Test] @@ -185,446 +185,445 @@ public async Task MockFileSystem_ByDefault_IsSerializable() } #endif - [Test] - public async Task MockFileSystem_AddDirectory_ShouldCreateDirectory() - { - string baseDirectory = XFS.Path(@"C:\Test"); - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFileSystem_AddDirectory_ShouldCreateDirectory() + { + string baseDirectory = XFS.Path(@"C:\Test"); + var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(baseDirectory); + fileSystem.AddDirectory(baseDirectory); - await That(fileSystem.Directory.Exists(baseDirectory)).IsTrue(); - } + await That(fileSystem.Directory.Exists(baseDirectory)).IsTrue(); + } - [Test] - public async Task MockFileSystem_AddDirectory_ShouldThrowExceptionIfDirectoryIsReadOnly() - { - string baseDirectory = XFS.Path(@"C:\Test"); - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty)); - fileSystem.File.SetAttributes(baseDirectory, FileAttributes.ReadOnly); + [Test] + public async Task MockFileSystem_AddDirectory_ShouldThrowExceptionIfDirectoryIsReadOnly() + { + string baseDirectory = XFS.Path(@"C:\Test"); + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty)); + fileSystem.File.SetAttributes(baseDirectory, FileAttributes.ReadOnly); - Action action = () => fileSystem.AddDirectory(baseDirectory); + Action action = () => fileSystem.AddDirectory(baseDirectory); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFileSystem_AddDrive_ShouldExist() - { - string name = @"D:\"; - var fileSystem = new MockFileSystem(); - fileSystem.AddDrive(name, new MockDriveData()); + [Test] + public async Task MockFileSystem_AddDrive_ShouldExist() + { + string name = @"D:\"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDrive(name, new MockDriveData()); - var actualResults = fileSystem.DriveInfo.GetDrives().Select(d => d.Name); + var actualResults = fileSystem.DriveInfo.GetDrives().Select(d => d.Name); - await That(actualResults).Contains(name); - } + await That(actualResults).Contains(name); + } - [Test] - public async Task MockFileSystem_DriveInfo_ShouldNotThrowAnyException() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\Test")); + [Test] + public async Task MockFileSystem_DriveInfo_ShouldNotThrowAnyException() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\Test")); - var actualResults = fileSystem.DriveInfo.GetDrives(); + var actualResults = fileSystem.DriveInfo.GetDrives(); - await That(actualResults).IsNotNull(); - } + await That(actualResults).IsNotNull(); + } - [Test] - public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PerfectMatch() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\test")); - fileSystem.AddDirectory(XFS.Path(@"C:\LOUD")); - - fileSystem.AddFile(XFS.Path(@"C:\test\file.txt"), "foo"); - fileSystem.AddFile(XFS.Path(@"C:\LOUD\file.txt"), "foo"); - fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBDirectory")); - fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBDirectory")); - - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\file.txt")); - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\file.txt")); - await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\SUBDirectory")); - await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBDirectory")); - } + [Test] + public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PerfectMatch() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\test")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD")); + + fileSystem.AddFile(XFS.Path(@"C:\test\file.txt"), "foo"); + fileSystem.AddFile(XFS.Path(@"C:\LOUD\file.txt"), "foo"); + fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBDirectory")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBDirectory")); + + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\file.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\file.txt")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\SUBDirectory")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBDirectory")); + } - [Test] - [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] - public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PartialMatch() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\test\subtest")); - fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBLOUD")); - - fileSystem.AddFile(XFS.Path(@"C:\test\SUBTEST\file.txt"), "foo"); - fileSystem.AddFile(XFS.Path(@"C:\LOUD\subloud\file.txt"), "foo"); - fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBTEST\SUBDirectory")); - fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\subloud\SUBDirectory")); - - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\subtest\file.txt")); - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\file.txt")); - await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\subtest\SUBDirectory")); - await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\SUBDirectory")); - } + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PartialMatch() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\test\subtest")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBLOUD")); + + fileSystem.AddFile(XFS.Path(@"C:\test\SUBTEST\file.txt"), "foo"); + fileSystem.AddFile(XFS.Path(@"C:\LOUD\subloud\file.txt"), "foo"); + fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBTEST\SUBDirectory")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\subloud\SUBDirectory")); + + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\subtest\file.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\file.txt")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\subtest\SUBDirectory")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\SUBDirectory")); + } - [Test] - [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] - public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PartialMatch_FurtherLeft() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:\test\subtest")); - fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBLOUD")); - - fileSystem.AddFile(XFS.Path(@"C:\test\SUBTEST\new\file.txt"), "foo"); - fileSystem.AddFile(XFS.Path(@"C:\LOUD\subloud\new\file.txt"), "foo"); - fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBTEST\new\SUBDirectory")); - fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\subloud\new\SUBDirectory")); - - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\subtest\new\file.txt")); - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\file.txt")); - await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\subtest\new\SUBDirectory")); - await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\SUBDirectory")); - } + [Test] + [WindowsOnly(WindowsSpecifics.CaseInsensitivity)] + public async Task MockFileSystem_AddFile_ShouldMatchCapitalization_PartialMatch_FurtherLeft() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:\test\subtest")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\SUBLOUD")); + + fileSystem.AddFile(XFS.Path(@"C:\test\SUBTEST\new\file.txt"), "foo"); + fileSystem.AddFile(XFS.Path(@"C:\LOUD\subloud\new\file.txt"), "foo"); + fileSystem.AddDirectory(XFS.Path(@"C:\test\SUBTEST\new\SUBDirectory")); + fileSystem.AddDirectory(XFS.Path(@"C:\LOUD\subloud\new\SUBDirectory")); + + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\test\subtest\new\file.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\file.txt")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\test\subtest\new\SUBDirectory")); + await That(fileSystem.AllDirectories.ToList()).Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\SUBDirectory")); + } - [Test] - public async Task MockFileSystem_AddFile_InitializesMockFileDataFileVersionInfoIfNull() - { - // Arrange - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFileSystem_AddFile_InitializesMockFileDataFileVersionInfoIfNull() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - fileSystem.AddFile(XFS.Path(@"C:\file.txt"), string.Empty); + // Act + fileSystem.AddFile(XFS.Path(@"C:\file.txt"), string.Empty); - // Assert - IFileVersionInfo fileVersionInfo = fileSystem.FileVersionInfo.GetVersionInfo(XFS.Path(@"C:\file.txt")); - await That(fileVersionInfo).IsNotNull(); - await That(fileVersionInfo.FileName).IsEqualTo(XFS.Path(@"C:\file.txt")); - } + // Assert + IFileVersionInfo fileVersionInfo = fileSystem.FileVersionInfo.GetVersionInfo(XFS.Path(@"C:\file.txt")); + await That(fileVersionInfo).IsNotNull(); + await That(fileVersionInfo.FileName).IsEqualTo(XFS.Path(@"C:\file.txt")); + } - [Test] - public async Task MockFileSystem_AddFileFromEmbeddedResource_ShouldAddTheFile() - { - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFileSystem_AddFileFromEmbeddedResource_ShouldAddTheFile() + { + var fileSystem = new MockFileSystem(); - fileSystem.AddFileFromEmbeddedResource(XFS.Path(@"C:\TestFile.txt"), Assembly.GetExecutingAssembly(), "System.IO.Abstractions.TestingHelpers.Tests.TestFiles.TestFile.txt"); - var result = fileSystem.GetFile(XFS.Path(@"C:\TestFile.txt")); + fileSystem.AddFileFromEmbeddedResource(XFS.Path(@"C:\TestFile.txt"), Assembly.GetExecutingAssembly(), "System.IO.Abstractions.TestingHelpers.Tests.TestFiles.TestFile.txt"); + var result = fileSystem.GetFile(XFS.Path(@"C:\TestFile.txt")); - await That(result.Contents).IsEqualTo(new UTF8Encoding().GetBytes("This is a test file.")); - } + await That(result.Contents).IsEqualTo(new UTF8Encoding().GetBytes("This is a test file.")); + } - [Test] - public async Task MockFileSystem_AddFilesFromEmbeddedResource_ShouldAddAllTheFiles() - { - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFileSystem_AddFilesFromEmbeddedResource_ShouldAddAllTheFiles() + { + var fileSystem = new MockFileSystem(); - fileSystem.AddFilesFromEmbeddedNamespace(XFS.Path(@"C:\"), Assembly.GetExecutingAssembly(), "System.IO.Abstractions.TestingHelpers.Tests.TestFiles"); + fileSystem.AddFilesFromEmbeddedNamespace(XFS.Path(@"C:\"), Assembly.GetExecutingAssembly(), "System.IO.Abstractions.TestingHelpers.Tests.TestFiles"); - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\TestFile.txt")); - await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\SecondTestFile.txt")); - } + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\TestFile.txt")); + await That(fileSystem.AllFiles.ToList()).Contains(XFS.Path(@"C:\SecondTestFile.txt")); + } - [Test] - public async Task MockFileSystem_MoveDirectory_MovesDirectoryWithoutRenamingFiles() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"C:\dir1\dir1\dir1.txt"), string.Empty); + [Test] + public async Task MockFileSystem_MoveDirectory_MovesDirectoryWithoutRenamingFiles() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\dir1\dir1\dir1.txt"), string.Empty); - fileSystem.MoveDirectory(XFS.Path(@"C:\dir1"), XFS.Path(@"C:\dir2")); + fileSystem.MoveDirectory(XFS.Path(@"C:\dir1"), XFS.Path(@"C:\dir2")); - var expected = new[] { XFS.Path(@"C:\dir2\dir1\dir1.txt") }; - await That(fileSystem.AllFiles).IsEqualTo(expected); - } + var expected = new[] { XFS.Path(@"C:\dir2\dir1\dir1.txt") }; + await That(fileSystem.AllFiles).IsEqualTo(expected); + } - [Test] - public async Task MockFileSystem_MoveDirectoryAndFile_ShouldMoveCorrectly() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(XFS.Path(@"C:\source\project.txt"), string.Empty); - fileSystem.AddFile(XFS.Path(@"C:\source\subdir\other.txt"), string.Empty); + [Test] + public async Task MockFileSystem_MoveDirectoryAndFile_ShouldMoveCorrectly() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(XFS.Path(@"C:\source\project.txt"), string.Empty); + fileSystem.AddFile(XFS.Path(@"C:\source\subdir\other.txt"), string.Empty); - fileSystem.Directory.Move(XFS.Path(@"C:\source"), XFS.Path(@"C:\target")); - fileSystem.File.Move(XFS.Path(@"C:\target\project.txt"), XFS.Path(@"C:\target\proj.txt")); + fileSystem.Directory.Move(XFS.Path(@"C:\source"), XFS.Path(@"C:\target")); + fileSystem.File.Move(XFS.Path(@"C:\target\project.txt"), XFS.Path(@"C:\target\proj.txt")); - var expected = new[] { XFS.Path(@"C:\target\proj.txt"), XFS.Path(@"C:\target\subdir\other.txt") }; - await That(fileSystem.AllFiles).IsEqualTo(expected); - } + var expected = new[] { XFS.Path(@"C:\target\proj.txt"), XFS.Path(@"C:\target\subdir\other.txt") }; + await That(fileSystem.AllFiles).IsEqualTo(expected); + } - [Test] - public async Task MockFileSystem_RemoveFile_RemovesFiles() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(@"C:\file.txt", new MockFileData("Content")); + [Test] + public async Task MockFileSystem_RemoveFile_RemovesFiles() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(@"C:\file.txt", new MockFileData("Content")); - fileSystem.RemoveFile(@"C:\file.txt"); + fileSystem.RemoveFile(@"C:\file.txt"); - await That(fileSystem.FileExists(@"C:\file.txt")).IsFalse(); - } + await That(fileSystem.FileExists(@"C:\file.txt")).IsFalse(); + } - [Test] - public async Task MockFileSystem_RemoveFile_ThrowsUnauthorizedAccessExceptionIfFileIsReadOnly() + [Test] + public async Task MockFileSystem_RemoveFile_ThrowsUnauthorizedAccessExceptionIfFileIsReadOnly() + { + var path = XFS.Path(@"C:\file.txt"); + var readOnlyFile = new MockFileData("") { - var path = XFS.Path(@"C:\file.txt"); - var readOnlyFile = new MockFileData("") - { - Attributes = FileAttributes.ReadOnly - }; - var fileSystem = new MockFileSystem(new Dictionary - { - { path, readOnlyFile }, - }); + Attributes = FileAttributes.ReadOnly + }; + var fileSystem = new MockFileSystem(new Dictionary + { + { path, readOnlyFile }, + }); - Action action = () => fileSystem.RemoveFile(path); + Action action = () => fileSystem.RemoveFile(path); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFileSystem_AllNodes_ShouldReturnAllNodes() + [Test] + public async Task MockFileSystem_AllNodes_ShouldReturnAllNodes() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), string.Empty }, - { XFS.Path(@"c:\something\other.gif"), string.Empty }, - { XFS.Path(@"d:\foobar\"), new MockDirectoryData() }, - { XFS.Path(@"d:\foo\bar"), new MockDirectoryData( )} - }); - var expectedNodes = new[] - { - XFS.Path(@"c:\something\demo.txt"), - XFS.Path(@"c:\something\other.gif"), - XFS.Path(@"d:\foobar"), - XFS.Path(@"d:\foo\bar"), - XFS.Path(@"C:\temp") - }; + { XFS.Path(@"c:\something\demo.txt"), string.Empty }, + { XFS.Path(@"c:\something\other.gif"), string.Empty }, + { XFS.Path(@"d:\foobar\"), new MockDirectoryData() }, + { XFS.Path(@"d:\foo\bar"), new MockDirectoryData( )} + }); + var expectedNodes = new[] + { + XFS.Path(@"c:\something\demo.txt"), + XFS.Path(@"c:\something\other.gif"), + XFS.Path(@"d:\foobar"), + XFS.Path(@"d:\foo\bar"), + XFS.Path(@"C:\temp") + }; - var result = fileSystem.AllNodes; + var result = fileSystem.AllNodes; - await That(result).IsEqualTo(expectedNodes); - } + await That(result).IsEqualTo(expectedNodes); + } - [Test] - [TestCase(@"C:\path")] - [TestCase(@"C:\path\")] - public async Task MockFileSystem_AddDirectory_TrailingSlashAllowedButNotRequired(string path) - { - var fileSystem = new MockFileSystem(); - var path2 = XFS.Path(path); + [Test] + [TestCase(@"C:\path")] + [TestCase(@"C:\path\")] + public async Task MockFileSystem_AddDirectory_TrailingSlashAllowedButNotRequired(string path) + { + var fileSystem = new MockFileSystem(); + var path2 = XFS.Path(path); - fileSystem.AddDirectory(path2); + fileSystem.AddDirectory(path2); - await That(fileSystem.FileExists(path2)).IsTrue(); - } + await That(fileSystem.FileExists(path2)).IsTrue(); + } - [Test] - public async Task MockFileSystem_GetFiles_ThrowsArgumentExceptionForInvalidCharacters() - { - // Arrange - const string path = @"c:\"; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(path)); + [Test] + public async Task MockFileSystem_GetFiles_ThrowsArgumentExceptionForInvalidCharacters() + { + // Arrange + const string path = @"c:\"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(path)); - // Act - Action getFilesWithInvalidCharacterInPath = () => fileSystem.Directory.GetFiles($"{path}{'\0'}.txt"); + // Act + Action getFilesWithInvalidCharacterInPath = () => fileSystem.Directory.GetFiles($"{path}{'\0'}.txt"); - // Assert - await That(getFilesWithInvalidCharacterInPath).Throws(); - } + // Assert + await That(getFilesWithInvalidCharacterInPath).Throws(); + } - [Test] - [TestCase(null)] - [TestCase(@"C:\somepath")] - public async Task MockFileSystem_DefaultState_CurrentDirectoryExists(string currentDirectory) - { - var fs = new MockFileSystem(null, XFS.Path(currentDirectory)); + [Test] + [TestCase(null)] + [TestCase(@"C:\somepath")] + public async Task MockFileSystem_DefaultState_CurrentDirectoryExists(string currentDirectory) + { + var fs = new MockFileSystem(null, XFS.Path(currentDirectory)); - var actualCurrentDirectory = fs.DirectoryInfo.New("."); + var actualCurrentDirectory = fs.DirectoryInfo.New("."); - await That(actualCurrentDirectory.Exists).IsTrue(); - } + await That(actualCurrentDirectory.Exists).IsTrue(); + } - [Test] - public async Task MockFileSystem_Constructor_ThrowsForNonRootedCurrentDirectory() - { - await That(() => + [Test] + public async Task MockFileSystem_Constructor_ThrowsForNonRootedCurrentDirectory() + { + await That(() => new MockFileSystem(null, "non-rooted") ).Throws() .WithParamName("currentDirectory"); - } + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFileSystem_Constructor_ShouldSupportDifferentRootDrives() + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFileSystem_Constructor_ShouldSupportDifferentRootDrives() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - [@"c:\"] = new MockDirectoryData(), - [@"z:\"] = new MockDirectoryData(), - [@"d:\"] = new MockDirectoryData(), - }); + [@"c:\"] = new MockDirectoryData(), + [@"z:\"] = new MockDirectoryData(), + [@"d:\"] = new MockDirectoryData(), + }); - var cExists = fileSystem.Directory.Exists(@"c:\"); - var zExists = fileSystem.Directory.Exists(@"z:\"); - var dExists = fileSystem.Directory.Exists(@"d:\"); + var cExists = fileSystem.Directory.Exists(@"c:\"); + var zExists = fileSystem.Directory.Exists(@"z:\"); + var dExists = fileSystem.Directory.Exists(@"d:\"); - await That(fileSystem).IsNotNull(); - await That(cExists).IsTrue(); - await That(zExists).IsTrue(); - await That(dExists).IsTrue(); - } + await That(fileSystem).IsNotNull(); + await That(cExists).IsTrue(); + await That(zExists).IsTrue(); + await That(dExists).IsTrue(); + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFileSystem_Constructor_ShouldAddDifferentDrivesIfNotExist() + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFileSystem_Constructor_ShouldAddDifferentDrivesIfNotExist() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - [@"d:\foo\bar\"] = new MockDirectoryData(), - }); + [@"d:\foo\bar\"] = new MockDirectoryData(), + }); - var drivesInfo = fileSystem.DriveInfo.GetDrives(); - var fooExists = fileSystem.Directory.Exists(@"d:\foo\"); - var barExists = fileSystem.Directory.Exists(@"d:\foo\bar\"); + var drivesInfo = fileSystem.DriveInfo.GetDrives(); + var fooExists = fileSystem.Directory.Exists(@"d:\foo\"); + var barExists = fileSystem.Directory.Exists(@"d:\foo\bar\"); - await That(drivesInfo.Any(d => string.Equals(d.Name, @"D:\", StringComparison.InvariantCultureIgnoreCase))).IsTrue(); - await That(fooExists).IsTrue(); - await That(barExists).IsTrue(); - } + await That(drivesInfo.Any(d => string.Equals(d.Name, @"D:\", StringComparison.InvariantCultureIgnoreCase))).IsTrue(); + await That(fooExists).IsTrue(); + await That(barExists).IsTrue(); + } - [Test] - [WindowsOnly(WindowsSpecifics.Drives)] - public async Task MockFileSystem_Constructor_ShouldNotDuplicateDrives() + [Test] + [WindowsOnly(WindowsSpecifics.Drives)] + public async Task MockFileSystem_Constructor_ShouldNotDuplicateDrives() + { + var fileSystem = new MockFileSystem(new Dictionary { - var fileSystem = new MockFileSystem(new Dictionary - { - [@"d:\foo\bar\"] = new MockDirectoryData(), - [@"d:\"] = new MockDirectoryData() - }); + [@"d:\foo\bar\"] = new MockDirectoryData(), + [@"d:\"] = new MockDirectoryData() + }); - var drivesInfo = fileSystem.DriveInfo.GetDrives(); + var drivesInfo = fileSystem.DriveInfo.GetDrives(); - await That(drivesInfo.Where(d => string.Equals(d.Name, @"D:\", StringComparison.InvariantCultureIgnoreCase))).HasCount().EqualTo(1); - } + await That(drivesInfo.Where(d => string.Equals(d.Name, @"D:\", StringComparison.InvariantCultureIgnoreCase))).HasCount().EqualTo(1); + } - [Test] - public async Task MockFileSystem_DefaultState_DefaultTempDirectoryExists() - { - var tempDirectory = XFS.Path(@"C:\temp"); + [Test] + public async Task MockFileSystem_DefaultState_DefaultTempDirectoryExists() + { + var tempDirectory = XFS.Path(@"C:\temp"); - var mockFileSystem = new MockFileSystem(); - var mockFileSystemOverload = new MockFileSystem(null, string.Empty); + var mockFileSystem = new MockFileSystem(); + var mockFileSystemOverload = new MockFileSystem(null, string.Empty); - await That(mockFileSystem.Directory.Exists(tempDirectory)).IsTrue(); - await That(mockFileSystemOverload.Directory.Exists(tempDirectory)).IsTrue(); - } + await That(mockFileSystem.Directory.Exists(tempDirectory)).IsTrue(); + await That(mockFileSystemOverload.Directory.Exists(tempDirectory)).IsTrue(); + } - [Test] - public async Task MockFileSystem_FileSystemWatcher_Can_Be_Overridden() - { - var path = XFS.Path(@"C:\root"); - var fileSystem = new TestFileSystem(new TestFileSystemWatcherFactory()); - var watcher = fileSystem.FileSystemWatcher.New(path); - await That(watcher.Path).IsEqualTo(path); - } + [Test] + public async Task MockFileSystem_FileSystemWatcher_Can_Be_Overridden() + { + var path = XFS.Path(@"C:\root"); + var fileSystem = new TestFileSystem(new TestFileSystemWatcherFactory()); + var watcher = fileSystem.FileSystemWatcher.New(path); + await That(watcher.Path).IsEqualTo(path); + } - [Test] - public async Task MockFileSystem_DeleteDirectoryRecursive_WithReadOnlyFile_ShouldThrowUnauthorizedException() - { - string baseDirectory = XFS.Path(@"C:\Test"); - string textFile = XFS.Path(@"C:\Test\file.txt"); + [Test] + public async Task MockFileSystem_DeleteDirectoryRecursive_WithReadOnlyFile_ShouldThrowUnauthorizedException() + { + string baseDirectory = XFS.Path(@"C:\Test"); + string textFile = XFS.Path(@"C:\Test\file.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty)); - fileSystem.AddFile(textFile, new MockFileData("Content")); - fileSystem.File.SetAttributes(textFile, FileAttributes.ReadOnly); + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty)); + fileSystem.AddFile(textFile, new MockFileData("Content")); + fileSystem.File.SetAttributes(textFile, FileAttributes.ReadOnly); - Action action = () => fileSystem.Directory.Delete(baseDirectory, true); + Action action = () => fileSystem.Directory.Delete(baseDirectory, true); - await That(action).Throws(); - await That(fileSystem.File.Exists(textFile)).IsTrue(); - await That(fileSystem.Directory.Exists(baseDirectory)).IsTrue(); - } + await That(action).Throws(); + await That(fileSystem.File.Exists(textFile)).IsTrue(); + await That(fileSystem.Directory.Exists(baseDirectory)).IsTrue(); + } + + private class TestFileSystem : MockFileSystem + { + private readonly IFileSystemWatcherFactory fileSystemWatcherFactory; - private class TestFileSystem : MockFileSystem + public TestFileSystem(IFileSystemWatcherFactory fileSystemWatcherFactory) { - private readonly IFileSystemWatcherFactory fileSystemWatcherFactory; + this.fileSystemWatcherFactory = fileSystemWatcherFactory; + } - public TestFileSystem(IFileSystemWatcherFactory fileSystemWatcherFactory) - { - this.fileSystemWatcherFactory = fileSystemWatcherFactory; - } + public override IFileSystemWatcherFactory FileSystemWatcher => fileSystemWatcherFactory; + } - public override IFileSystemWatcherFactory FileSystemWatcher => fileSystemWatcherFactory; - } + private class TestFileSystemWatcherFactory : IFileSystemWatcherFactory + { + public IFileSystemWatcher CreateNew() => New(); + public IFileSystemWatcher CreateNew(string path) => New(path); + public IFileSystemWatcher CreateNew(string path, string filter) => New(path, filter); + public IFileSystemWatcher New() + => new TestFileSystemWatcher(null); - private class TestFileSystemWatcherFactory : IFileSystemWatcherFactory - { - public IFileSystemWatcher CreateNew() => New(); - public IFileSystemWatcher CreateNew(string path) => New(path); - public IFileSystemWatcher CreateNew(string path, string filter) => New(path, filter); - public IFileSystemWatcher New() - => new TestFileSystemWatcher(null); + public IFileSystemWatcher New(string path) + => new TestFileSystemWatcher(path); - public IFileSystemWatcher New(string path) - => new TestFileSystemWatcher(path); + public IFileSystemWatcher New(string path, string filter) + => new TestFileSystemWatcher(path, filter); - public IFileSystemWatcher New(string path, string filter) - => new TestFileSystemWatcher(path, filter); + public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) + => new TestFileSystemWatcher(fileSystemWatcher.Path, fileSystemWatcher.Filter); - public IFileSystemWatcher Wrap(FileSystemWatcher fileSystemWatcher) - => new TestFileSystemWatcher(fileSystemWatcher.Path, fileSystemWatcher.Filter); + public IFileSystemWatcher FromPath(string path) => new TestFileSystemWatcher(path); + public IFileSystem FileSystem => null!; + } - public IFileSystemWatcher FromPath(string path) => new TestFileSystemWatcher(path); - public IFileSystem FileSystem => null!; - } + private class TestFileSystemWatcher : FileSystemWatcherBase + { + public TestFileSystemWatcher(string path) => Path = path; - private class TestFileSystemWatcher : FileSystemWatcherBase + public TestFileSystemWatcher(string path, string filter) { - public TestFileSystemWatcher(string path) => Path = path; + Path = path; + Filter = filter; + } - public TestFileSystemWatcher(string path, string filter) - { - Path = path; - Filter = filter; - } - - public override string Path { get; set; } - public override IFileSystem FileSystem { get; } - public override bool IncludeSubdirectories { get; set; } - public override IContainer Container { get; } - public override bool EnableRaisingEvents { get; set; } - public override string Filter { get; set; } - public override int InternalBufferSize { get; set; } - public override NotifyFilters NotifyFilter { get; set; } - public override ISite Site { get; set; } - public override ISynchronizeInvoke SynchronizingObject { get; set; } + public override string Path { get; set; } + public override IFileSystem FileSystem { get; } + public override bool IncludeSubdirectories { get; set; } + public override IContainer Container { get; } + public override bool EnableRaisingEvents { get; set; } + public override string Filter { get; set; } + public override int InternalBufferSize { get; set; } + public override NotifyFilters NotifyFilter { get; set; } + public override ISite Site { get; set; } + public override ISynchronizeInvoke SynchronizingObject { get; set; } #if FEATURE_FILE_SYSTEM_WATCHER_FILTERS - public override Collection Filters { get; } + public override Collection Filters { get; } #endif - public override void BeginInit() { } - public override void EndInit() { } - public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) - { - _ = changeType; - return default(IWaitForChangedResult); - } + public override void BeginInit() { } + public override void EndInit() { } + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) + { + _ = changeType; + return default(IWaitForChangedResult); + } - public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) - { - _ = changeType; - _ = timeout; - return default(IWaitForChangedResult); - } + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) + { + _ = changeType; + _ = timeout; + return default(IWaitForChangedResult); + } #if FEATURE_FILE_SYSTEM_WATCHER_WAIT_WITH_TIMESPAN - public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout) - { - _ = changeType; - _ = timeout; - return default(IWaitForChangedResult); - } -#endif + public override IWaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout) + { + _ = changeType; + _ = timeout; + return default(IWaitForChangedResult); } +#endif } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemWatcherFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemWatcherFactoryTests.cs index 513307897..12b6a34ad 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemWatcherFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSystemWatcherFactoryTests.cs @@ -1,51 +1,50 @@ using NUnit.Framework; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileSystemWatcherFactoryTests { - [TestFixture] - public class MockFileSystemWatcherFactoryTests + [Test] + public async Task MockFileSystemWatcherFactory_CreateNew_ShouldThrowNotImplementedException() + { + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New()).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_CreateNewWithPath_ShouldThrowNotImplementedException() { - [Test] - public async Task MockFileSystemWatcherFactory_CreateNew_ShouldThrowNotImplementedException() - { - var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); - await That(() => factory.New()).Throws(); - } - - [Test] - public async Task MockFileSystemWatcherFactory_CreateNewWithPath_ShouldThrowNotImplementedException() - { - var path = XFS.Path(@"y:\test"); - var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); - await That(() => factory.New(path)).Throws(); - } - - [Test] - public async Task MockFileSystemWatcherFactory_CreateNewWithPathAndFilter_ShouldThrowNotImplementedException() - { - var path = XFS.Path(@"y:\test"); - var filter = "*.txt"; - var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); - await That(() => factory.New(path, filter)).Throws(); - } - - [Test] - public async Task MockFileSystemWatcherFactory_FromPath_ShouldThrowNotImplementedException() - { - var path = XFS.Path(@"y:\test"); - var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); - await That(() => factory.New(path)).Throws(); - } - - [Test] - public async Task MockFileSystemWatcherFactory_Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new MockFileSystem(); - - var result = fileSystem.FileSystemWatcher.Wrap(null); - - await That(result).IsNull(); - } + var path = XFS.Path(@"y:\test"); + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New(path)).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_CreateNewWithPathAndFilter_ShouldThrowNotImplementedException() + { + var path = XFS.Path(@"y:\test"); + var filter = "*.txt"; + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New(path, filter)).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_FromPath_ShouldThrowNotImplementedException() + { + var path = XFS.Path(@"y:\test"); + var factory = new MockFileSystemWatcherFactory(new MockFileSystem()); + await That(() => factory.New(path)).Throws(); + } + + [Test] + public async Task MockFileSystemWatcherFactory_Wrap_WithNull_ShouldReturnNull() + { + var fileSystem = new MockFileSystem(); + + var result = fileSystem.FileSystemWatcher.Wrap(null); + + await That(result).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileTests.cs index 043306154..9cda3d7b2 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileTests.cs @@ -5,730 +5,729 @@ using System.Text; using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +[TestFixture] +public class MockFileTests { - using XFS = MockUnixSupport; + [Test] + public async Task MockFile_Constructor_ShouldThrowArgumentNullExceptionIfMockFileDataAccessorIsNull() + { + // Arrange + // nothing to do + + // Act + Action action = () => new MockFile(null); + + // Assert + await That(action).Throws(); + } - [TestFixture] - public class MockFileTests + [Test] + public async Task MockFile_GetSetCreationTime_ShouldPersist() { - [Test] - public async Task MockFile_Constructor_ShouldThrowArgumentNullExceptionIfMockFileDataAccessorIsNull() + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - // nothing to do + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); - // Act - Action action = () => new MockFile(null); + // Act + var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetCreationTime(path, creationTime); + var result = file.GetCreationTime(path); - // Assert - await That(action).Throws(); - } + // Assert + await That(result).IsEqualTo(creationTime); + } - [Test] - public async Task MockFile_GetSetCreationTime_ShouldPersist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetCreationTime(path, creationTime); - var result = file.GetCreationTime(path); - - // Assert - await That(result).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_SetCreationTimeUtc_ShouldAffectCreationTime() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetCreationTimeUtc(path, creationTime.ToUniversalTime()); - var result = file.GetCreationTime(path); - - // Assert - await That(result).IsEqualTo(creationTime); - } - - [Test] - public async Task MockFile_SetCreationTime_ShouldAffectCreationTimeUtc() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetCreationTime(path, creationTime); - var result = file.GetCreationTimeUtc(path); - - // Assert - await That(result).IsEqualTo(creationTime.ToUniversalTime()); - } - - [Test] - public async Task MockFile_GetSetLastAccessTime_ShouldPersist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastAccessTime(path, lastAccessTime); - var result = file.GetLastAccessTime(path); - - // Assert - await That(result).IsEqualTo(lastAccessTime); - } - - [Test] - public async Task MockFile_SetLastAccessTimeUtc_ShouldAffectLastAccessTime() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); - var result = file.GetLastAccessTime(path); - - // Assert - await That(result).IsEqualTo(lastAccessTime); - } - - [Test] - public async Task MockFile_SetLastAccessTime_ShouldAffectLastAccessTimeUtc() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastAccessTime(path, lastAccessTime); - var result = file.GetLastAccessTimeUtc(path); - - // Assert - await That(result).IsEqualTo(lastAccessTime.ToUniversalTime()); - } - - [Test] - public async Task MockFile_GetSetLastWriteTime_ShouldPersist() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastWriteTime(path, lastWriteTime); - var result = file.GetLastWriteTime(path); - - // Assert - await That(result).IsEqualTo(lastWriteTime); - } - - static async Task ExecuteDefaultValueTest(Func getDateValue) + [Test] + public async Task MockFile_SetCreationTimeUtc_ShouldAffectCreationTime() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - var expected = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var file = new MockFile(fileSystem); + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); - var actual = getDateValue(file, path); + // Act + var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetCreationTimeUtc(path, creationTime.ToUniversalTime()); + var result = file.GetCreationTime(path); - await That(actual.ToUniversalTime()).IsEqualTo(expected); - } + // Assert + await That(result).IsEqualTo(creationTime); + } - [Test] - public async Task MockFile_GetLastWriteTimeOfNonExistentFile_ShouldReturnDefaultValue() + [Test] + public async Task MockFile_SetCreationTime_ShouldAffectCreationTimeUtc() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - await ExecuteDefaultValueTest((f, p) => f.GetLastWriteTime(p)); - } + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); - [Test] - public async Task MockFile_GetLastWriteTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() - { - await ExecuteDefaultValueTest((f, p) => f.GetLastWriteTimeUtc(p)); - } + // Act + var creationTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetCreationTime(path, creationTime); + var result = file.GetCreationTimeUtc(path); + + // Assert + await That(result).IsEqualTo(creationTime.ToUniversalTime()); + } - [Test] - public async Task MockFile_GetLastAccessTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() + [Test] + public async Task MockFile_GetSetLastAccessTime_ShouldPersist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - await ExecuteDefaultValueTest((f, p) => f.GetLastAccessTimeUtc(p)); - } + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastAccessTime(path, lastAccessTime); + var result = file.GetLastAccessTime(path); - [Test] - public async Task MockFile_GetLastAccessTimeOfNonExistentFile_ShouldReturnDefaultValue() + // Assert + await That(result).IsEqualTo(lastAccessTime); + } + + [Test] + public async Task MockFile_SetLastAccessTimeUtc_ShouldAffectLastAccessTime() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - await ExecuteDefaultValueTest((f, p) => f.GetLastAccessTime(p)); - } + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); - [Test] - public async Task MockFile_GetAttributeOfNonExistentFileButParentDirectoryExists_ShouldThrowOneFileNotFoundException() + // Act + var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); + var result = file.GetLastAccessTime(path); + + // Assert + await That(result).IsEqualTo(lastAccessTime); + } + + [Test] + public async Task MockFile_SetLastAccessTime_ShouldAffectLastAccessTimeUtc() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); - // Act - Action action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + // Act + var lastAccessTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastAccessTime(path, lastAccessTime); + var result = file.GetLastAccessTimeUtc(path); - // Assert - await That(action).Throws(); - } + // Assert + await That(result).IsEqualTo(lastAccessTime.ToUniversalTime()); + } - [Test] - public async Task MockFile_GetAttributeOfNonExistentFile_ShouldThrowOneDirectoryNotFoundException() + [Test] + public async Task MockFile_GetSetLastWriteTime_ShouldPersist() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastWriteTime(path, lastWriteTime); + var result = file.GetLastWriteTime(path); + + // Assert + await That(result).IsEqualTo(lastWriteTime); + } + + static async Task ExecuteDefaultValueTest(Func getDateValue) + { + var expected = new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc); + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var file = new MockFile(fileSystem); + + var actual = getDateValue(file, path); - // Act - Action action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + await That(actual.ToUniversalTime()).IsEqualTo(expected); + } - // Assert - await That(action).Throws(); - } + [Test] + public async Task MockFile_GetLastWriteTimeOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastWriteTime(p)); + } - [Test] - public async Task MockFile_GetAttributeOfExistingFile_ShouldReturnCorrectValue() + [Test] + public async Task MockFile_GetLastWriteTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastWriteTimeUtc(p)); + } + + [Test] + public async Task MockFile_GetLastAccessTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastAccessTimeUtc(p)); + } + + [Test] + public async Task MockFile_GetLastAccessTimeOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetLastAccessTime(p)); + } + + [Test] + public async Task MockFile_GetAttributeOfNonExistentFileButParentDirectoryExists_ShouldThrowOneFileNotFoundException() + { + // Arrange + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + Action action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetAttributeOfNonExistentFile_ShouldThrowOneDirectoryNotFoundException() + { + // Arrange + var fileSystem = new MockFileSystem(); + + // Act + Action action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetAttributeOfExistingFile_ShouldReturnCorrectValue() + { + var filedata = new MockFileData("test") { - var filedata = new MockFileData("test") - { - Attributes = FileAttributes.Hidden - }; - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), filedata } - }); - - var attributes = fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); - await That(attributes).IsEqualTo(FileAttributes.Hidden); - } - - [Test] - [WindowsOnly(WindowsSpecifics.UNCPaths)] - public async Task MockFile_GetAttributeOfExistingUncDirectory_ShouldReturnCorrectValue() + Attributes = FileAttributes.Hidden + }; + var fileSystem = new MockFileSystem(new Dictionary { - var filedata = new MockFileData("test"); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"\\share\folder\demo.txt"), filedata } - }); - - var attributes = fileSystem.File.GetAttributes(XFS.Path(@"\\share\folder")); - await That(attributes).IsEqualTo(FileAttributes.Directory); - } - - [Test] - public async Task MockFile_GetAttributeWithEmptyParameter_ShouldThrowOneArgumentException() + { XFS.Path(@"c:\something\demo.txt"), filedata } + }); + + var attributes = fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt")); + await That(attributes).IsEqualTo(FileAttributes.Hidden); + } + + [Test] + [WindowsOnly(WindowsSpecifics.UNCPaths)] + public async Task MockFile_GetAttributeOfExistingUncDirectory_ShouldReturnCorrectValue() + { + var filedata = new MockFileData("test"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { XFS.Path(@"\\share\folder\demo.txt"), filedata } + }); - // Act - Action action = () => fileSystem.File.GetAttributes(string.Empty); + var attributes = fileSystem.File.GetAttributes(XFS.Path(@"\\share\folder")); + await That(attributes).IsEqualTo(FileAttributes.Directory); + } - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("The path is not of a legal form."); - } + [Test] + public async Task MockFile_GetAttributeWithEmptyParameter_ShouldThrowOneArgumentException() + { + // Arrange + var fileSystem = new MockFileSystem(); - [Test] - public async Task MockFile_GetAttributeWithIllegalParameter_ShouldThrowOneArgumentException() - { - // Arrange - var fileSystem = new MockFileSystem(); + // Act + Action action = () => fileSystem.File.GetAttributes(string.Empty); - // Act - Action action = () => fileSystem.File.GetAttributes(string.Empty); + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("The path is not of a legal form."); + } - // Assert - // Note: The actual type of the exception differs from the documentation. - // According to the documentation it should be of type NotSupportedException. - await That(action).Throws(); - } + [Test] + public async Task MockFile_GetAttributeWithIllegalParameter_ShouldThrowOneArgumentException() + { + // Arrange + var fileSystem = new MockFileSystem(); - [Test] - public async Task MockFile_GetCreationTimeOfNonExistentFile_ShouldReturnDefaultValue() - { - await ExecuteDefaultValueTest((f, p) => f.GetCreationTime(p)); - } + // Act + Action action = () => fileSystem.File.GetAttributes(string.Empty); - [Test] - public async Task MockFile_GetCreationTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() - { - await ExecuteDefaultValueTest((f, p) => f.GetCreationTimeUtc(p)); - } + // Assert + // Note: The actual type of the exception differs from the documentation. + // According to the documentation it should be of type NotSupportedException. + await That(action).Throws(); + } + + [Test] + public async Task MockFile_GetCreationTimeOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetCreationTime(p)); + } - [Test] - public async Task MockFile_SetLastWriteTimeUtc_ShouldAffectLastWriteTime() + [Test] + public async Task MockFile_GetCreationTimeUtcOfNonExistentFile_ShouldReturnDefaultValue() + { + await ExecuteDefaultValueTest((f, p) => f.GetCreationTimeUtc(p)); + } + + [Test] + public async Task MockFile_SetLastWriteTimeUtc_ShouldAffectLastWriteTime() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); - var result = file.GetLastWriteTime(path); - - // Assert - await That(result).IsEqualTo(lastWriteTime); - } - - [Test] - public async Task MockFile_SetLastWriteTime_ShouldAffectLastWriteTimeUtc() + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); + var result = file.GetLastWriteTime(path); + + // Assert + await That(result).IsEqualTo(lastWriteTime); + } + + [Test] + public async Task MockFile_SetLastWriteTime_ShouldAffectLastWriteTimeUtc() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("Demo text content") } - }); - var file = new MockFile(fileSystem); - - // Act - var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); - file.SetLastWriteTime(path, lastWriteTime); - var result = file.GetLastWriteTimeUtc(path); - - // Assert - await That(result).IsEqualTo(lastWriteTime.ToUniversalTime()); - } - - [Test] - public async Task MockFile_ReadAllText_ShouldReturnOriginalTextData() + { path, new MockFileData("Demo text content") } + }); + var file = new MockFile(fileSystem); + + // Act + var lastWriteTime = new DateTime(2010, 6, 4, 13, 26, 42); + file.SetLastWriteTime(path, lastWriteTime); + var result = file.GetLastWriteTimeUtc(path); + + // Assert + await That(result).IsEqualTo(lastWriteTime.ToUniversalTime()); + } + + [Test] + public async Task MockFile_ReadAllText_ShouldReturnOriginalTextData() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, - { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData("Demo text content") }, + { XFS.Path(@"c:\something\other.gif"), new MockFileData(new byte[] { 0x21, 0x58, 0x3f, 0xa9 }) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt")); + // Act + var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt")); - // Assert - await That(result).IsEqualTo("Demo text content"); - } + // Assert + await That(result).IsEqualTo("Demo text content"); + } - [Test] - public async Task MockFile_ReadAllText_ShouldReturnOriginalDataWithCustomEncoding() + [Test] + public async Task MockFile_ReadAllText_ShouldReturnOriginalDataWithCustomEncoding() + { + // Arrange + string text = "Hello there!"; + var encodedText = Encoding.BigEndianUnicode.GetBytes(text); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - string text = "Hello there!"; - var encodedText = Encoding.BigEndianUnicode.GetBytes(text); - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } - }); + { XFS.Path(@"c:\something\demo.txt"), new MockFileData(encodedText) } + }); - var file = new MockFile(fileSystem); + var file = new MockFile(fileSystem); - // Act - var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); + // Act + var result = file.ReadAllText(XFS.Path(@"c:\something\demo.txt"), Encoding.BigEndianUnicode); - // Assert - await That(result).IsEqualTo(text); - } + // Assert + await That(result).IsEqualTo(text); + } - public static IEnumerable GetEncodingsForReadAllText() - { - // little endian - yield return new UTF32Encoding(false, true, true); + public static IEnumerable GetEncodingsForReadAllText() + { + // little endian + yield return new UTF32Encoding(false, true, true); - // big endian - yield return new UTF32Encoding(true, true, true); - yield return new UTF8Encoding(true, true); + // big endian + yield return new UTF32Encoding(true, true, true); + yield return new UTF8Encoding(true, true); - yield return new ASCIIEncoding(); - } + yield return new ASCIIEncoding(); + } - [TestCaseSource(typeof(MockFileTests), nameof(GetEncodingsForReadAllText))] - public async Task MockFile_ReadAllText_ShouldReturnTheOriginalContentWhenTheFileContainsDifferentEncodings(Encoding encoding) - { - // Arrange - string text = "Hello there!"; - var encodedText = encoding.GetPreamble().Concat(encoding.GetBytes(text)).ToArray(); - var path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData(encodedText) } - }); - - // Act - var actualText = fileSystem.File.ReadAllText(path); - - // Assert - await That(actualText).IsEqualTo(text); - } - - [Test] - public async Task MockFile_OpenWrite_ShouldCreateNewFiles() - { - string filePath = XFS.Path(@"c:\something\demo.txt"); - string fileContent = "this is some content"; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - - var bytes = new UTF8Encoding(true).GetBytes(fileContent); - var stream = fileSystem.File.OpenWrite(filePath); - stream.Write(bytes, 0, bytes.Length); - stream.Dispose(); - - await That(fileSystem.FileExists(filePath)).IsTrue(); - await That(fileSystem.GetFile(filePath).TextContents).IsEqualTo(fileContent); - } - - [Test] - public async Task MockFile_OpenWrite_ShouldNotCreateFolders() + [TestCaseSource(typeof(MockFileTests), nameof(GetEncodingsForReadAllText))] + public async Task MockFile_ReadAllText_ShouldReturnTheOriginalContentWhenTheFileContainsDifferentEncodings(Encoding encoding) + { + // Arrange + string text = "Hello there!"; + var encodedText = encoding.GetPreamble().Concat(encoding.GetBytes(text)).ToArray(); + var path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string filePath = XFS.Path(@"c:\something\demo.txt"); // c:\something does not exist: OpenWrite should fail - var fileSystem = new MockFileSystem(); + { path, new MockFileData(encodedText) } + }); + + // Act + var actualText = fileSystem.File.ReadAllText(path); - await That(() => fileSystem.File.OpenWrite(filePath)).Throws(); - } + // Assert + await That(actualText).IsEqualTo(text); + } + + [Test] + public async Task MockFile_OpenWrite_ShouldCreateNewFiles() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "this is some content"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + var bytes = new UTF8Encoding(true).GetBytes(fileContent); + var stream = fileSystem.File.OpenWrite(filePath); + stream.Write(bytes, 0, bytes.Length); + stream.Dispose(); + + await That(fileSystem.FileExists(filePath)).IsTrue(); + await That(fileSystem.GetFile(filePath).TextContents).IsEqualTo(fileContent); + } + + [Test] + public async Task MockFile_OpenWrite_ShouldNotCreateFolders() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); // c:\something does not exist: OpenWrite should fail + var fileSystem = new MockFileSystem(); + + await That(() => fileSystem.File.OpenWrite(filePath)).Throws(); + } - [Test] - public async Task MockFile_OpenWrite_ShouldOverwriteExistingFiles() + [Test] + public async Task MockFile_OpenWrite_ShouldOverwriteExistingFiles() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); + string startFileContent = "this is some content"; + string endFileContent = "this is some other content"; + var fileSystem = new MockFileSystem(new Dictionary { - string filePath = XFS.Path(@"c:\something\demo.txt"); - string startFileContent = "this is some content"; - string endFileContent = "this is some other content"; - var fileSystem = new MockFileSystem(new Dictionary - { - {filePath, new MockFileData(startFileContent)} - }); - - var bytes = new UTF8Encoding(true).GetBytes(endFileContent); - var stream = fileSystem.File.OpenWrite(filePath); - stream.Write(bytes, 0, bytes.Length); - stream.Dispose(); - - await That(fileSystem.FileExists(filePath)).IsTrue(); - await That(fileSystem.GetFile(filePath).TextContents).IsEqualTo(endFileContent); - } - - [Test] - public async Task MockFile_Delete_ShouldRemoveFileFromFileSystem() + {filePath, new MockFileData(startFileContent)} + }); + + var bytes = new UTF8Encoding(true).GetBytes(endFileContent); + var stream = fileSystem.File.OpenWrite(filePath); + stream.Write(bytes, 0, bytes.Length); + stream.Dispose(); + + await That(fileSystem.FileExists(filePath)).IsTrue(); + await That(fileSystem.GetFile(filePath).TextContents).IsEqualTo(endFileContent); + } + + [Test] + public async Task MockFile_Delete_ShouldRemoveFileFromFileSystem() + { + string fullPath = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string fullPath = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { fullPath, new MockFileData("Demo text content") } - }); + { fullPath, new MockFileData("Demo text content") } + }); + + var file = new MockFile(fileSystem); - var file = new MockFile(fileSystem); + file.Delete(fullPath); - file.Delete(fullPath); + await That(fileSystem.FileExists(fullPath)).IsFalse(); + } - await That(fileSystem.FileExists(fullPath)).IsFalse(); - } + [Test] + public async Task MockFile_Delete_Should_RemoveFiles() + { + string filePath = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "this is some content"; + var fileSystem = new MockFileSystem(new Dictionary { { filePath, new MockFileData(fileContent) } }); + await That(fileSystem.AllFiles.Count()).IsEqualTo(1); + fileSystem.File.Delete(filePath); + await That(fileSystem.AllFiles.Count()).IsEqualTo(0); + } - [Test] - public async Task MockFile_Delete_Should_RemoveFiles() - { - string filePath = XFS.Path(@"c:\something\demo.txt"); - string fileContent = "this is some content"; - var fileSystem = new MockFileSystem(new Dictionary { { filePath, new MockFileData(fileContent) } }); - await That(fileSystem.AllFiles.Count()).IsEqualTo(1); - fileSystem.File.Delete(filePath); - await That(fileSystem.AllFiles.Count()).IsEqualTo(0); - } - - [Test] - public async Task MockFile_Delete_No_File_Does_Nothing() + [Test] + public async Task MockFile_Delete_No_File_Does_Nothing() + { + var fileSystem = new MockFileSystem(new Dictionary() { - var fileSystem = new MockFileSystem(new Dictionary() - { - { XFS.Path(@"c:\something\exist.txt"), new MockFileData("Demo text content") }, - }); + { XFS.Path(@"c:\something\exist.txt"), new MockFileData("Demo text content") }, + }); - string filePath = XFS.Path(@"c:\something\not_exist.txt"); + string filePath = XFS.Path(@"c:\something\not_exist.txt"); - await That(() => fileSystem.File.Delete(filePath)).DoesNotThrow(); - } + await That(() => fileSystem.File.Delete(filePath)).DoesNotThrow(); + } - [Test] - public async Task MockFile_Delete_ShouldThrowUnauthorizedAccessException_WhenPathIsADirectory() + [Test] + public async Task MockFile_Delete_ShouldThrowUnauthorizedAccessException_WhenPathIsADirectory() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { XFS.Path(@"c:\bar"), new MockDirectoryData() }, - }); + { XFS.Path(@"c:\bar"), new MockDirectoryData() }, + }); - // Act - Action action = () => fileSystem.File.Delete(XFS.Path(@"c:\bar")); + // Act + Action action = () => fileSystem.File.Delete(XFS.Path(@"c:\bar")); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_AppendText_AppendTextToAnExistingFile() + [Test] + public async Task MockFile_AppendText_AppendTextToAnExistingFile() + { + string filepath = XFS.Path(@"c:\something\does\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary { - string filepath = XFS.Path(@"c:\something\does\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary - { - { filepath, new MockFileData("I'm here. ") } - }); + { filepath, new MockFileData("I'm here. ") } + }); - var stream = filesystem.File.AppendText(filepath); + var stream = filesystem.File.AppendText(filepath); - stream.Write("Me too!"); - stream.Flush(); - stream.Dispose(); + stream.Write("Me too!"); + stream.Flush(); + stream.Dispose(); - var file = filesystem.GetFile(filepath); - await That(file.TextContents).IsEqualTo("I'm here. Me too!"); - } + var file = filesystem.GetFile(filepath); + await That(file.TextContents).IsEqualTo("I'm here. Me too!"); + } - [Test] - public async Task MockFile_AppendText_CreatesNewFileForAppendToNonExistingFile() - { - string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); - var filesystem = new MockFileSystem(new Dictionary()); - filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); + [Test] + public async Task MockFile_AppendText_CreatesNewFileForAppendToNonExistingFile() + { + string filepath = XFS.Path(@"c:\something\doesnt\exist.txt"); + var filesystem = new MockFileSystem(new Dictionary()); + filesystem.AddDirectory(XFS.Path(@"c:\something\doesnt")); - var stream = filesystem.File.AppendText(filepath); + var stream = filesystem.File.AppendText(filepath); - stream.Write("New too!"); - stream.Flush(); - stream.Dispose(); + stream.Write("New too!"); + stream.Flush(); + stream.Dispose(); - var file = filesystem.GetFile(filepath); - await That(file.TextContents).IsEqualTo("New too!"); - await That(filesystem.FileExists(filepath)).IsTrue(); - } + var file = filesystem.GetFile(filepath); + await That(file.TextContents).IsEqualTo("New too!"); + await That(filesystem.FileExists(filepath)).IsTrue(); + } #if !NET9_0_OR_GREATER - [Test] - public void Serializable_works() - { - //Arrange - MockFileData data = new MockFileData("Text Contents"); + [Test] + public void Serializable_works() + { + //Arrange + MockFileData data = new MockFileData("Text Contents"); - //Act + //Act #pragma warning disable SYSLIB0011 - IFormatter formatter = new BinaryFormatter(); - Stream stream = new MemoryStream(); + IFormatter formatter = new BinaryFormatter(); + Stream stream = new MemoryStream(); - formatter.Serialize(stream, data); + formatter.Serialize(stream, data); #pragma warning restore SYSLIB0011 - //Assert - Assert.Pass(); - } + //Assert + Assert.Pass(); + } #endif #if !NET9_0_OR_GREATER - [Test] - public async Task Serializable_can_deserialize() - { - //Arrange - string textContentStr = "Text Contents"; + [Test] + public async Task Serializable_can_deserialize() + { + //Arrange + string textContentStr = "Text Contents"; - //Act - MockFileData data = new MockFileData(textContentStr); + //Act + MockFileData data = new MockFileData(textContentStr); #pragma warning disable SYSLIB0011 - IFormatter formatter = new BinaryFormatter(); - Stream stream = new MemoryStream(); - formatter.Serialize(stream, data); + IFormatter formatter = new BinaryFormatter(); + Stream stream = new MemoryStream(); + formatter.Serialize(stream, data); - stream.Seek(0, SeekOrigin.Begin); + stream.Seek(0, SeekOrigin.Begin); - MockFileData deserialized = (MockFileData)formatter.Deserialize(stream); + MockFileData deserialized = (MockFileData)formatter.Deserialize(stream); #pragma warning restore SYSLIB0011 - //Assert - await That(deserialized.TextContents).IsEqualTo(textContentStr); - } + //Assert + await That(deserialized.TextContents).IsEqualTo(textContentStr); + } #endif - [Test] - public async Task MockFile_Encrypt_ShouldSetEncryptedAttribute() + [Test] + public async Task MockFile_Encrypt_ShouldSetEncryptedAttribute() + { + // Arrange + var fileData = new MockFileData("Demo text content"); + var filePath = XFS.Path(@"c:\a.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileData = new MockFileData("Demo text content"); - var filePath = XFS.Path(@"c:\a.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {filePath, fileData } - }); - - // Act + {filePath, fileData } + }); + + // Act #pragma warning disable CA1416 - fileSystem.File.Encrypt(filePath); + fileSystem.File.Encrypt(filePath); #pragma warning restore CA1416 - var attributes = fileSystem.File.GetAttributes(filePath); + var attributes = fileSystem.File.GetAttributes(filePath); - // Assert - await That(attributes & FileAttributes.Encrypted).IsEqualTo(FileAttributes.Encrypted); - } + // Assert + await That(attributes & FileAttributes.Encrypted).IsEqualTo(FileAttributes.Encrypted); + } - [Test] - public async Task MockFile_Decrypt_ShouldRemoveEncryptedAttribute() - { - // Arrange - const string Content = "Demo text content"; - var fileData = new MockFileData(Content); - var filePath = XFS.Path(@"c:\a.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - {filePath, fileData } - }); + [Test] + public async Task MockFile_Decrypt_ShouldRemoveEncryptedAttribute() + { + // Arrange + const string Content = "Demo text content"; + var fileData = new MockFileData(Content); + var filePath = XFS.Path(@"c:\a.txt"); + var fileSystem = new MockFileSystem(new Dictionary + { + {filePath, fileData } + }); #pragma warning disable CA1416 - fileSystem.File.Encrypt(filePath); + fileSystem.File.Encrypt(filePath); #pragma warning restore CA1416 - // Act + // Act #pragma warning disable CA1416 - fileSystem.File.Decrypt(filePath); + fileSystem.File.Decrypt(filePath); #pragma warning restore CA1416 - var attributes = fileSystem.File.GetAttributes(filePath); + var attributes = fileSystem.File.GetAttributes(filePath); - // Assert - await That(attributes & FileAttributes.Encrypted).IsNotEqualTo(FileAttributes.Encrypted); - } + // Assert + await That(attributes & FileAttributes.Encrypted).IsNotEqualTo(FileAttributes.Encrypted); + } - [Test] - public async Task MockFile_Replace_ShouldReplaceFileContents() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - fileSystem.AddFile(path2, new MockFileData("2")); + [Test] + public async Task MockFile_Replace_ShouldReplaceFileContents() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); - // Act - fileSystem.File.Replace(path1, path2, null); + // Act + fileSystem.File.Replace(path1, path2, null); - await That(fileSystem.File.ReadAllText(path2)).IsEqualTo("1"); - } + await That(fileSystem.File.ReadAllText(path2)).IsEqualTo("1"); + } - [Test] - public async Task MockFile_Replace_ShouldCreateBackup() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - var path3 = XFS.Path(@"c:\temp\file3.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - fileSystem.AddFile(path2, new MockFileData("2")); - - // Act - fileSystem.File.Replace(path1, path2, path3); - - await That(fileSystem.File.ReadAllText(path3)).IsEqualTo("2"); - } - - [Test] - public async Task MockFile_Replace_ShouldThrowIfDirectoryOfBackupPathDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - var path3 = XFS.Path(@"c:\temp\subdirectory\file3.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); - fileSystem.AddFile(path2, new MockFileData("2")); - - // Act - await That(() => fileSystem.File.Replace(path1, path2, path3)).Throws(); - } - - [Test] - public async Task MockFile_Replace_ShouldThrowIfSourceFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - fileSystem.AddFile(path2, new MockFileData("2")); + [Test] + public async Task MockFile_Replace_ShouldCreateBackup() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + + // Act + fileSystem.File.Replace(path1, path2, path3); + + await That(fileSystem.File.ReadAllText(path3)).IsEqualTo("2"); + } + + [Test] + public async Task MockFile_Replace_ShouldThrowIfDirectoryOfBackupPathDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + var path3 = XFS.Path(@"c:\temp\subdirectory\file3.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + fileSystem.AddFile(path2, new MockFileData("2")); + + // Act + await That(() => fileSystem.File.Replace(path1, path2, path3)).Throws(); + } - await That(() => fileSystem.File.Replace(path1, path2, null)).Throws(); - } + [Test] + public async Task MockFile_Replace_ShouldThrowIfSourceFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path2, new MockFileData("2")); - [Test] - public async Task MockFile_Replace_ShouldThrowIfDestinationFileDoesNotExist() - { - // Arrange - var fileSystem = new MockFileSystem(); - var path1 = XFS.Path(@"c:\temp\file1.txt"); - var path2 = XFS.Path(@"c:\temp\file2.txt"); - fileSystem.AddFile(path1, new MockFileData("1")); + await That(() => fileSystem.File.Replace(path1, path2, null)).Throws(); + } - await That(() => fileSystem.File.Replace(path1, path2, null)).Throws(); - } + [Test] + public async Task MockFile_Replace_ShouldThrowIfDestinationFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(); + var path1 = XFS.Path(@"c:\temp\file1.txt"); + var path2 = XFS.Path(@"c:\temp\file2.txt"); + fileSystem.AddFile(path1, new MockFileData("1")); + + await That(() => fileSystem.File.Replace(path1, path2, null)).Throws(); + } - [Test] - public async Task MockFile_OpenRead_ShouldReturnReadOnlyStream() + [Test] + public async Task MockFile_OpenRead_ShouldReturnReadOnlyStream() + { + // Tests issue #230 + // Arrange + string filePath = XFS.Path(@"c:\something\demo.txt"); + string startContent = "hi there"; + var fileSystem = new MockFileSystem(new Dictionary { - // Tests issue #230 - // Arrange - string filePath = XFS.Path(@"c:\something\demo.txt"); - string startContent = "hi there"; - var fileSystem = new MockFileSystem(new Dictionary - { - { filePath, new MockFileData(startContent) } - }); - - // Act - var stream = fileSystem.File.OpenRead(filePath); - - // Assert - await That(stream.CanWrite).IsFalse(); - await That(() => stream.WriteByte(0)).Throws(); - } - } -} + { filePath, new MockFileData(startContent) } + }); + + // Act + var stream = fileSystem.File.OpenRead(filePath); + + // Assert + await That(stream.CanWrite).IsFalse(); + await That(() => stream.WriteByte(0)).Throws(); + } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoFactoryTests.cs index 407492bb9..e4573f0d1 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoFactoryTests.cs @@ -1,43 +1,42 @@ using NUnit.Framework; using System.Collections.Generic; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileVersionInfoFactoryTests { - [TestFixture] - public class MockFileVersionInfoFactoryTests + [Test] + public async Task MockFileVersionInfoFactory_GetVersionInfo_ShouldReturnTheFileVersionInfoOfTheMockFileData() { - [Test] - public async Task MockFileVersionInfoFactory_GetVersionInfo_ShouldReturnTheFileVersionInfoOfTheMockFileData() + // Arrange + var fileVersionInfo = new MockFileVersionInfo(@"c:\a.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileVersionInfo = new MockFileVersionInfo(@"c:\a.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\a.txt", new MockFileData("Demo text content") { FileVersionInfo = fileVersionInfo } } - }); + { @"c:\a.txt", new MockFileData("Demo text content") { FileVersionInfo = fileVersionInfo } } + }); - // Act - var result = fileSystem.FileVersionInfo.GetVersionInfo(@"c:\a.txt"); + // Act + var result = fileSystem.FileVersionInfo.GetVersionInfo(@"c:\a.txt"); - // Assert - await That(result).IsEqualTo(fileVersionInfo); - } + // Assert + await That(result).IsEqualTo(fileVersionInfo); + } - [Test] - public async Task MockFileVersionInfoFactory_GetVersionInfo_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() + [Test] + public async Task MockFileVersionInfoFactory_GetVersionInfo_ShouldThrowFileNotFoundExceptionIfFileDoesNotExist() + { + // Arrange + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(new Dictionary - { - { @"c:\a.txt", new MockFileData("Demo text content") }, - { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, - }); + { @"c:\a.txt", new MockFileData("Demo text content") }, + { @"c:\a\b\c.txt", new MockFileData("Demo text content") }, + }); - // Act - Action code = () => fileSystem.FileVersionInfo.GetVersionInfo(@"c:\foo.txt"); + // Act + Action code = () => fileSystem.FileVersionInfo.GetVersionInfo(@"c:\foo.txt"); - // Assert - await That(code).Throws(); - } + // Assert + await That(code).Throws(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoTests.cs index 789add5e4..1a269df36 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileVersionInfoTests.cs @@ -1,36 +1,36 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class MockFileVersionInfoTests { - [TestFixture] - public class MockFileVersionInfoTests + [Test] + public async Task MockFileVersionInfo_ToString_ShouldReturnTheDefaultFormat() { - [Test] - public async Task MockFileVersionInfo_ToString_ShouldReturnTheDefaultFormat() - { - // Arrange - var mockFileVersionInfo = new MockFileVersionInfo( - fileName: @"c:\b.txt", - fileVersion: "1.0.0.0", - productVersion: "1.0.0.0", - fileDescription: "b", - productName: "b", - companyName: null, - comments: null, - internalName: "b.txt", - isDebug: true, - isPatched: true, - isPrivateBuild: true, - isPreRelease: true, - isSpecialBuild: true, - language: "English", - legalCopyright: null, - legalTrademarks: null, - originalFilename: "b.txt", - privateBuild: null, - specialBuild: null); + // Arrange + var mockFileVersionInfo = new MockFileVersionInfo( + fileName: @"c:\b.txt", + fileVersion: "1.0.0.0", + productVersion: "1.0.0.0", + fileDescription: "b", + productName: "b", + companyName: null, + comments: null, + internalName: "b.txt", + isDebug: true, + isPatched: true, + isPrivateBuild: true, + isPreRelease: true, + isSpecialBuild: true, + language: "English", + legalCopyright: null, + legalTrademarks: null, + originalFilename: "b.txt", + privateBuild: null, + specialBuild: null); - string expected = @"File: c:\b.txt + string expected = @"File: c:\b.txt InternalName: b.txt OriginalFilename: b.txt FileVersion: 1.0.0.0 @@ -45,42 +45,41 @@ public async Task MockFileVersionInfo_ToString_ShouldReturnTheDefaultFormat() Language: English "; - // Act & Assert - await That(mockFileVersionInfo.ToString()).IsEqualTo(expected); - } + // Act & Assert + await That(mockFileVersionInfo.ToString()).IsEqualTo(expected); + } - [Test] - public async Task MockFileVersionInfo_Constructor_ShouldSetFileAndProductVersionNumbersIfFileAndProductVersionAreNotNull() - { - // Arrange - var mockFileVersionInfo = new MockFileVersionInfo(@"c:\file.txt", fileVersion: "1.2.3.4", productVersion: "5.6.7.8"); + [Test] + public async Task MockFileVersionInfo_Constructor_ShouldSetFileAndProductVersionNumbersIfFileAndProductVersionAreNotNull() + { + // Arrange + var mockFileVersionInfo = new MockFileVersionInfo(@"c:\file.txt", fileVersion: "1.2.3.4", productVersion: "5.6.7.8"); - // Assert - await That(mockFileVersionInfo.FileMajorPart).IsEqualTo(1); - await That(mockFileVersionInfo.FileMinorPart).IsEqualTo(2); - await That(mockFileVersionInfo.FileBuildPart).IsEqualTo(3); - await That(mockFileVersionInfo.FilePrivatePart).IsEqualTo(4); - await That(mockFileVersionInfo.ProductMajorPart).IsEqualTo(5); - await That(mockFileVersionInfo.ProductMinorPart).IsEqualTo(6); - await That(mockFileVersionInfo.ProductBuildPart).IsEqualTo(7); - await That(mockFileVersionInfo.ProductPrivatePart).IsEqualTo(8); - } + // Assert + await That(mockFileVersionInfo.FileMajorPart).IsEqualTo(1); + await That(mockFileVersionInfo.FileMinorPart).IsEqualTo(2); + await That(mockFileVersionInfo.FileBuildPart).IsEqualTo(3); + await That(mockFileVersionInfo.FilePrivatePart).IsEqualTo(4); + await That(mockFileVersionInfo.ProductMajorPart).IsEqualTo(5); + await That(mockFileVersionInfo.ProductMinorPart).IsEqualTo(6); + await That(mockFileVersionInfo.ProductBuildPart).IsEqualTo(7); + await That(mockFileVersionInfo.ProductPrivatePart).IsEqualTo(8); + } - [Test] - public async Task MockFileVersionInfo_Constructor_ShouldNotSetFileAndProductVersionNumbersIfFileAndProductVersionAreNull() - { - // Act - var mockFileVersionInfo = new MockFileVersionInfo(@"c:\a.txt"); + [Test] + public async Task MockFileVersionInfo_Constructor_ShouldNotSetFileAndProductVersionNumbersIfFileAndProductVersionAreNull() + { + // Act + var mockFileVersionInfo = new MockFileVersionInfo(@"c:\a.txt"); - // Assert - await That(mockFileVersionInfo.FileMajorPart).IsEqualTo(0); - await That(mockFileVersionInfo.FileMinorPart).IsEqualTo(0); - await That(mockFileVersionInfo.FileBuildPart).IsEqualTo(0); - await That(mockFileVersionInfo.FilePrivatePart).IsEqualTo(0); - await That(mockFileVersionInfo.ProductMajorPart).IsEqualTo(0); - await That(mockFileVersionInfo.ProductMinorPart).IsEqualTo(0); - await That(mockFileVersionInfo.ProductBuildPart).IsEqualTo(0); - await That(mockFileVersionInfo.ProductPrivatePart).IsEqualTo(0); - } + // Assert + await That(mockFileVersionInfo.FileMajorPart).IsEqualTo(0); + await That(mockFileVersionInfo.FileMinorPart).IsEqualTo(0); + await That(mockFileVersionInfo.FileBuildPart).IsEqualTo(0); + await That(mockFileVersionInfo.FilePrivatePart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductMajorPart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductMinorPart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductBuildPart).IsEqualTo(0); + await That(mockFileVersionInfo.ProductPrivatePart).IsEqualTo(0); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllBytesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllBytesTests.cs index a79199ffe..76d9d6875 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllBytesTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllBytesTests.cs @@ -4,105 +4,105 @@ using System.Threading.Tasks; using System.Threading; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileWriteAllBytesTests { - public class MockFileWriteAllBytesTests + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() { - [Test] - public async Task MockFile_WriteAllBytes_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() - { - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"c:\something\file.txt"); - var fileContent = new byte[] { 1, 2, 3, 4 }; + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.txt"); + var fileContent = new byte[] { 1, 2, 3, 4 }; - Action action = () => fileSystem.File.WriteAllBytes(path, fileContent); + Action action = () => fileSystem.File.WriteAllBytes(path, fileContent); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_WriteAllBytes_ShouldWriteDataToMemoryFileSystem() - { - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - var fileContent = new byte[] { 1, 2, 3, 4 }; - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + [Test] + public async Task MockFile_WriteAllBytes_ShouldWriteDataToMemoryFileSystem() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + var fileContent = new byte[] { 1, 2, 3, 4 }; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - fileSystem.File.WriteAllBytes(path, fileContent); + fileSystem.File.WriteAllBytes(path, fileContent); - await That(fileSystem.GetFile(path).Contents).IsEqualTo(fileContent); - } + await That(fileSystem.GetFile(path).Contents).IsEqualTo(fileContent); + } - [Test] - public async Task MockFile_WriteAllBytes_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + { + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("this is hidden") }, - }); - fileSystem.File.SetAttributes(path, FileAttributes.Hidden); + { path, new MockFileData("this is hidden") }, + }); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - Action action = () => fileSystem.File.WriteAllBytes(path, new byte[] { 123 }); + Action action = () => fileSystem.File.WriteAllBytes(path, new byte[] { 123 }); - await That(action).Throws() - .Because($"Access to the path '{path}' is denied."); - } + await That(action).Throws() + .Because($"Access to the path '{path}' is denied."); + } - [Test] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentExceptionIfContainsIllegalCharacters() - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"C:")); + [Test] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentExceptionIfContainsIllegalCharacters() + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"C:")); - Action action = () => fileSystem.File.WriteAllBytes(XFS.Path(@"C:\a fileSystem.File.WriteAllBytes(XFS.Path(@"C:\a(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfPathIsNull() - { - var fileSystem = new MockFileSystem(); + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfPathIsNull() + { + var fileSystem = new MockFileSystem(); - Action action = () => fileSystem.File.WriteAllBytes(null, new byte[] { 123 }); + Action action = () => fileSystem.File.WriteAllBytes(null, new byte[] { 123 }); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfBytesAreNull() - { - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"c:\something\demo.txt"); + [Test] + public async Task MockFile_WriteAllBytes_ShouldThrowAnArgumentNullExceptionIfBytesAreNull() + { + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\demo.txt"); - Action action = () => fileSystem.File.WriteAllBytes(path, null); + Action action = () => fileSystem.File.WriteAllBytes(path, null); - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - await That(exception.ParamName).IsEqualTo("bytes"); - } + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).IsEqualTo("bytes"); + } - [Test] - public async Task 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 }; + [Test] + public async Task 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); + fileSystem.File.WriteAllBytes(path, fileContent); - for(int i = 0; i < fileContent.Length; i++) - { - fileContent[i] += 1; - } + for(int i = 0; i < fileContent.Length; i++) + { + fileContent[i] += 1; + } - var readAgain = fileSystem.File.ReadAllBytes(path); + var readAgain = fileSystem.File.ReadAllBytes(path); - await That(fileContent).IsNotEqualTo(readAgain); - } + await That(fileContent).IsNotEqualTo(readAgain); + } #if FEATURE_ASYNC_FILE @@ -201,5 +201,4 @@ public async Task MockFile_WriteAllBytesAsync_ShouldThrowAnArgumentNullException await That(exception.ParamName).IsEqualTo("bytes"); } #endif - } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllLinesTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllLinesTests.cs index 1def83bf6..1ff9eef6d 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllLinesTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllLinesTests.cs @@ -6,64 +6,111 @@ using NUnit.Framework; using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +public class MockFileWriteAllLinesTests { - public class MockFileWriteAllLinesTests + private class TestDataForWriteAllLines { - private class TestDataForWriteAllLines + public static readonly string Path = XFS.Path(@"c:\something\demo.txt"); + + public static IEnumerable ForDifferentEncoding { - public static readonly string Path = XFS.Path(@"c:\something\demo.txt"); + get + { + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var fileContentEnumerable = new List { "first line", "second line", "third line", "fourth and last line" }; + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerable = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(Path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentArray, Encoding.UTF32); + var expectedContent = string.Format(CultureInfo.InvariantCulture, + "first line{0}second line{0}third line{0}fourth and last line{0}", Environment.NewLine); + + // IEnumerable + yield return new TestCaseData(fileSystem, writeEnumerable, expectedContent) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(fileSystem, writeEnumerableUtf32, expectedContent) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - public static IEnumerable ForDifferentEncoding + // string[] + yield return new TestCaseData(fileSystem, writeArray, expectedContent) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(fileSystem, writeArrayUtf32, expectedContent) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); + } + } + + public static IEnumerable ForIllegalPath + { + get { - get - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - var fileContentEnumerable = new List { "first line", "second line", "third line", "fourth and last line" }; - var fileContentArray = fileContentEnumerable.ToArray(); - Action writeEnumerable = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable); - Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, Encoding.UTF32); - Action writeArray = () => fileSystem.File.WriteAllLines(Path, fileContentArray); - Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(Path, fileContentArray, Encoding.UTF32); - var expectedContent = string.Format(CultureInfo.InvariantCulture, - "first line{0}second line{0}third line{0}fourth and last line{0}", Environment.NewLine); - - // IEnumerable - yield return new TestCaseData(fileSystem, writeEnumerable, expectedContent) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(fileSystem, writeEnumerableUtf32, expectedContent) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(fileSystem, writeArray, expectedContent) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(fileSystem, writeArrayUtf32, expectedContent) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } + const string illegalPath = "<<<"; + return GetCasesForArgumentChecking(illegalPath); } + } - public static IEnumerable ForIllegalPath + public static IEnumerable ForNullPath + { + get { - get - { - const string illegalPath = "<<<"; - return GetCasesForArgumentChecking(illegalPath); - } + const string illegalPath = null; + return GetCasesForArgumentChecking(illegalPath); } + } - public static IEnumerable ForNullPath + private static IEnumerable GetCasesForArgumentChecking(string path) + { + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumerable) + .SetName("WriteAllLines(string, IEnumerable) input: " + path); + yield return new TestCaseData(writeEnumerableUtf32) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32) input: " + path); + + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLines(string, string[]) input: " + path); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLines(string, string[], Encoding.UTF32) input: " + path); + } + + private static IEnumerable ForNullEncoding + { + get { - get - { - const string illegalPath = null; - return GetCasesForArgumentChecking(illegalPath); - } + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerableNull = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, null); + Action writeArrayNull = () => fileSystem.File.WriteAllLines(Path, fileContentArray, null); + + // IEnumerable + yield return new TestCaseData(writeEnumerableNull) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArrayNull) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); } + } - private static IEnumerable GetCasesForArgumentChecking(string path) + public static IEnumerable ForPathIsDirectory + { + get { var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something"); + fileSystem.Directory.CreateDirectory(path); var fileContentEnumerable = new List(); var fileContentArray = fileContentEnumerable.ToArray(); Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); @@ -72,181 +119,181 @@ private static IEnumerable GetCasesForArgumentChecking(string path) Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); // IEnumerable - yield return new TestCaseData(writeEnumerable) - .SetName("WriteAllLines(string, IEnumerable) input: " + path); - yield return new TestCaseData(writeEnumerableUtf32) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32) input: " + path); + yield return new TestCaseData(writeEnumerable, path) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(writeEnumerableUtf32, path) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); // string[] - yield return new TestCaseData(writeArray) - .SetName("WriteAllLines(string, string[]) input: " + path); - yield return new TestCaseData(writeArrayUtf32) - .SetName("WriteAllLines(string, string[], Encoding.UTF32) input: " + path); + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); } + } - private static IEnumerable ForNullEncoding + public static IEnumerable ForFileIsReadOnly + { + get { - get - { - var fileSystem = new MockFileSystem(); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - Action writeEnumerableNull = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable, null); - Action writeArrayNull = () => fileSystem.File.WriteAllLines(Path, fileContentArray, null); - - // IEnumerable - yield return new TestCaseData(writeEnumerableNull) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArrayNull) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } - } + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(path, mockFileData); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - public static IEnumerable ForPathIsDirectory - { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something"); - fileSystem.Directory.CreateDirectory(path); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); - Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); - Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); - Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - - // IEnumerable - yield return new TestCaseData(writeEnumerable, path) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(writeEnumerableUtf32, path) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray, path) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(writeArrayUtf32, path) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } + // IEnumerable + yield return new TestCaseData(writeEnumerable, path) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(writeEnumerableUtf32, path) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); } + } - public static IEnumerable ForFileIsReadOnly + public static IEnumerable ForContentsIsNull + { + get { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something\file.txt"); - var mockFileData = new MockFileData(string.Empty); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddFile(path, mockFileData); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); - Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); - Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); - Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - - // IEnumerable - yield return new TestCaseData(writeEnumerable, path) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(writeEnumerableUtf32, path) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray, path) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(writeArrayUtf32, path) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + fileSystem.AddFile(path, mockFileData); + List fileContentEnumerable = null; + string[] fileContentArray = null; + + // ReSharper disable ExpressionIsAlwaysNull + Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); + Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); + // ReSharper restore ExpressionIsAlwaysNull + + // IEnumerable + yield return new TestCaseData(writeEnumerable) + .SetName("WriteAllLines(string, IEnumerable)"); + yield return new TestCaseData(writeEnumerableUtf32) + .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLines(string, string[])"); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); } + } - public static IEnumerable ForContentsIsNull +#if FEATURE_ASYNC_FILE + public static IEnumerable ForDifferentEncodingAsync + { + get { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something\file.txt"); - var mockFileData = new MockFileData(string.Empty); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - fileSystem.AddFile(path, mockFileData); - List fileContentEnumerable = null; - string[] fileContentArray = null; - - // ReSharper disable ExpressionIsAlwaysNull - Action writeEnumerable = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable); - Action writeEnumerableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32); - Action writeArray = () => fileSystem.File.WriteAllLines(path, fileContentArray); - Action writeArrayUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32); - // ReSharper restore ExpressionIsAlwaysNull - - // IEnumerable - yield return new TestCaseData(writeEnumerable) - .SetName("WriteAllLines(string, IEnumerable)"); - yield return new TestCaseData(writeEnumerableUtf32) - .SetName("WriteAllLines(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray) - .SetName("WriteAllLines(string, string[])"); - yield return new TestCaseData(writeArrayUtf32) - .SetName("WriteAllLines(string, string[], Encoding.UTF32)"); - } + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var fileContentEnumerable = new List { "first line", "second line", "third line", "fourth and last line" }; + var fileContentArray = fileContentEnumerable.ToArray(); + Action writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable); + Action writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable, Encoding.UTF32); + Action writeArray = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray); + Action writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray, Encoding.UTF32); + var expectedContent = string.Format(CultureInfo.InvariantCulture, + "first line{0}second line{0}third line{0}fourth and last line{0}", Environment.NewLine); + + // IEnumerable + yield return new TestCaseData(fileSystem, writeEnumberable, expectedContent) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(fileSystem, writeEnumberableUtf32, expectedContent) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(fileSystem, writeArray, expectedContent) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(fileSystem, writeArrayUtf32, expectedContent) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); } + } -#if FEATURE_ASYNC_FILE - public static IEnumerable ForDifferentEncodingAsync + public static IEnumerable ForIllegalPathAsync + { + get { - get - { - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - var fileContentEnumerable = new List { "first line", "second line", "third line", "fourth and last line" }; - var fileContentArray = fileContentEnumerable.ToArray(); - Action writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable); - Action writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable, Encoding.UTF32); - Action writeArray = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray); - Action writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray, Encoding.UTF32); - var expectedContent = string.Format(CultureInfo.InvariantCulture, - "first line{0}second line{0}third line{0}fourth and last line{0}", Environment.NewLine); - - // IEnumerable - yield return new TestCaseData(fileSystem, writeEnumberable, expectedContent) - .SetName("WriteAllLinesAsync(string, IEnumerable)"); - yield return new TestCaseData(fileSystem, writeEnumberableUtf32, expectedContent) - .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(fileSystem, writeArray, expectedContent) - .SetName("WriteAllLinesAsync(string, string[])"); - yield return new TestCaseData(fileSystem, writeArrayUtf32, expectedContent) - .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); - } + const string illegalPath = "<<<"; + return GetCasesForArgumentCheckingAsync(illegalPath); } + } - public static IEnumerable ForIllegalPathAsync + public static IEnumerable ForNullPathAsync + { + get { - get - { - const string illegalPath = "<<<"; - return GetCasesForArgumentCheckingAsync(illegalPath); - } + const string illegalPath = null; + return GetCasesForArgumentCheckingAsync(illegalPath); } + } + + private static IEnumerable GetCasesForArgumentCheckingAsync(string path) + { + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); + Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); + Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); + Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); + + // IEnumerable + yield return new TestCaseData(writeEnumberable) + .SetName("WriteAllLinesAsync(string, IEnumerable) input: " + path); + yield return new TestCaseData(writeEnumberableUtf32) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32) input: " + path); + + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLinesAsync(string, string[]) input: " + path); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32) input: " + path); + } - public static IEnumerable ForNullPathAsync + private static IEnumerable ForNullEncodingAsync + { + get { - get - { - const string illegalPath = null; - return GetCasesForArgumentCheckingAsync(illegalPath); - } + var fileSystem = new MockFileSystem(); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Func writeEnumberableNull = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable, null); + Func writeArrayNull = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray, null); + + // IEnumerable + yield return new TestCaseData(writeEnumberableNull) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); + + // string[] + yield return new TestCaseData(writeArrayNull) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); } + } - private static IEnumerable GetCasesForArgumentCheckingAsync(string path) + public static IEnumerable ForPathIsDirectoryAsync + { + get { var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something"); + fileSystem.Directory.CreateDirectory(path); var fileContentEnumerable = new List(); var fileContentArray = fileContentEnumerable.ToArray(); Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); @@ -255,360 +302,312 @@ private static IEnumerable GetCasesForArgumentCheckingAsync(string path) Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); // IEnumerable - yield return new TestCaseData(writeEnumberable) - .SetName("WriteAllLinesAsync(string, IEnumerable) input: " + path); - yield return new TestCaseData(writeEnumberableUtf32) - .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32) input: " + path); + yield return new TestCaseData(writeEnumberable, path) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(writeEnumberableUtf32, path) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); // string[] - yield return new TestCaseData(writeArray) - .SetName("WriteAllLinesAsync(string, string[]) input: " + path); - yield return new TestCaseData(writeArrayUtf32) - .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32) input: " + path); - } - - private static IEnumerable ForNullEncodingAsync - { - get - { - var fileSystem = new MockFileSystem(); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - Func writeEnumberableNull = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentEnumerable, null); - Func writeArrayNull = () => fileSystem.File.WriteAllLinesAsync(Path, fileContentArray, null); - - // IEnumerable - yield return new TestCaseData(writeEnumberableNull) - .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArrayNull) - .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); - } + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); } + } - public static IEnumerable ForPathIsDirectoryAsync + public static IEnumerable ForFileIsReadOnlyAsync + { + get { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something"); - fileSystem.Directory.CreateDirectory(path); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); - Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); - Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); - Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); - - // IEnumerable - yield return new TestCaseData(writeEnumberable, path) - .SetName("WriteAllLinesAsync(string, IEnumerable)"); - yield return new TestCaseData(writeEnumberableUtf32, path) - .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray, path) - .SetName("WriteAllLinesAsync(string, string[])"); - yield return new TestCaseData(writeArrayUtf32, path) - .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); - } - } + var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(path, mockFileData); + var fileContentEnumerable = new List(); + var fileContentArray = fileContentEnumerable.ToArray(); + Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); + Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); + Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); + Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); - public static IEnumerable ForFileIsReadOnlyAsync - { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something\file.txt"); - var mockFileData = new MockFileData(string.Empty); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddFile(path, mockFileData); - var fileContentEnumerable = new List(); - var fileContentArray = fileContentEnumerable.ToArray(); - Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); - Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); - Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); - Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); - - // IEnumerable - yield return new TestCaseData(writeEnumberable, path) - .SetName("WriteAllLinesAsync(string, IEnumerable)"); - yield return new TestCaseData(writeEnumberableUtf32, path) - .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray, path) - .SetName("WriteAllLinesAsync(string, string[])"); - yield return new TestCaseData(writeArrayUtf32, path) - .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); - } - } + // IEnumerable + yield return new TestCaseData(writeEnumberable, path) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(writeEnumberableUtf32, path) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); - public static IEnumerable ForContentsIsNullAsync - { - get - { - var fileSystem = new MockFileSystem(); - var path = XFS.Path(@"c:\something\file.txt"); - var mockFileData = new MockFileData(string.Empty); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - fileSystem.AddFile(path, mockFileData); - List fileContentEnumerable = null; - string[] fileContentArray = null; - - // ReSharper disable ExpressionIsAlwaysNull - Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); - Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); - Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); - Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); - // ReSharper restore ExpressionIsAlwaysNull - - // IEnumerable - yield return new TestCaseData(writeEnumberable) - .SetName("WriteAllLinesAsync(string, IEnumerable)"); - yield return new TestCaseData(writeEnumberableUtf32) - .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); - - // string[] - yield return new TestCaseData(writeArray) - .SetName("WriteAllLinesAsync(string, string[])"); - yield return new TestCaseData(writeArrayUtf32) - .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); - } + // string[] + yield return new TestCaseData(writeArray, path) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(writeArrayUtf32, path) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); } + } - [Test] - public async Task MockFile_WriteAllLinesAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + public static IEnumerable ForContentsIsNullAsync + { + get { - // Arrange - const string path = "test.txt"; var fileSystem = new MockFileSystem(); + var path = XFS.Path(@"c:\something\file.txt"); + var mockFileData = new MockFileData(string.Empty); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + fileSystem.AddFile(path, mockFileData); + List fileContentEnumerable = null; + string[] fileContentArray = null; + + // ReSharper disable ExpressionIsAlwaysNull + Func writeEnumberable = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable); + Func writeEnumberableUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentEnumerable, Encoding.UTF32); + Func writeArray = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray); + Func writeArrayUtf32 = () => fileSystem.File.WriteAllLinesAsync(path, fileContentArray, Encoding.UTF32); + // ReSharper restore ExpressionIsAlwaysNull - // Act - async Task Act() => - await fileSystem.File.WriteAllLinesAsync( - path, - new[] { "line 1", "line 2" }, - new CancellationToken(canceled: true)); - await That(Act).Throws(); + // IEnumerable + yield return new TestCaseData(writeEnumberable) + .SetName("WriteAllLinesAsync(string, IEnumerable)"); + yield return new TestCaseData(writeEnumberableUtf32) + .SetName("WriteAllLinesAsync(string, IEnumerable, Encoding.UTF32)"); - // Assert - await That(fileSystem.File.Exists(path)).IsFalse(); + // string[] + yield return new TestCaseData(writeArray) + .SetName("WriteAllLinesAsync(string, string[])"); + yield return new TestCaseData(writeArrayUtf32) + .SetName("WriteAllLinesAsync(string, string[], Encoding.UTF32)"); } -#endif - } - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForDifferentEncoding))] - public async Task MockFile_WriteAllLinesGeneric_ShouldWriteTheCorrectContent(IMockFileDataAccessor fileSystem, Action action, string expectedContent) + [Test] + public async Task MockFile_WriteAllLinesAsync_ShouldThrowOperationCanceledExceptionIfCancelled() { // Arrange - // is done in the test case source + const string path = "test.txt"; + var fileSystem = new MockFileSystem(); // Act - action(); + async Task Act() => + await fileSystem.File.WriteAllLinesAsync( + path, + new[] { "line 1", "line 2" }, + new CancellationToken(canceled: true)); + await That(Act).Throws(); // Assert - var actualContent = fileSystem.GetFile(TestDataForWriteAllLines.Path).TextContents; - await That(actualContent).IsEqualTo(expectedContent); + await That(fileSystem.File.Exists(path)).IsFalse(); } +#endif - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForNullPath))] - public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfPathIsNull(Action action) - { - // Arrange - // is done in the test case source + } - // Act - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForDifferentEncoding))] + public async Task MockFile_WriteAllLinesGeneric_ShouldWriteTheCorrectContent(IMockFileDataAccessor fileSystem, Action action, string expectedContent) + { + // Arrange + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - await That(exception.ParamName).StartsWith("path"); - } + // Act + action(); - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullEncoding")] - public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfEncodingIsNull(Action action) - { - // Arrange - // is done in the test case source + // Assert + var actualContent = fileSystem.GetFile(TestDataForWriteAllLines.Path).TextContents; + await That(actualContent).IsEqualTo(expectedContent); + } - // Act - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForNullPath))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfPathIsNull(Action action) + { + // Arrange + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - await That(exception.ParamName).StartsWith("encoding"); - } + // Act + // is done in the test case source - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForIllegalPath))] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentExceptionIfPathContainsIllegalCharacters(Action action) - { - // Arrange - // is done in the test case source + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("path"); + } - // Act - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullEncoding")] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfEncodingIsNull(Action action) + { + // Arrange + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path."); - } + // Act + // is done in the test case source - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForPathIsDirectory))] - public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnUnauthorizedAccessExceptionIfPathIsOneDirectory(Action action, string path) - { - // Arrange - // is done in the test case source + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("encoding"); + } - // Act - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForIllegalPath))] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentExceptionIfPathContainsIllegalCharacters(Action action) + { + // Arrange + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); - await That(exception.Message).IsEqualTo(expectedMessage); - } + // Act + // is done in the test case source - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForFileIsReadOnly))] - public async Task MockFile_WriteAllLinesGeneric_ShouldThrowOneUnauthorizedAccessExceptionIfFileIsReadOnly(Action action, string path) - { - // Arrange - // is done in the test case source + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).IsEqualTo("Illegal characters in path."); + } - // Act - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForPathIsDirectory))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnUnauthorizedAccessExceptionIfPathIsOneDirectory(Action action, string path) + { + // Arrange + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); - await That(exception.Message).IsEqualTo(expectedMessage); - } + // Act + // is done in the test case source - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForContentsIsNull))] - public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfContentsIsNull(Action action) - { - // Arrange - // is done in the test case source + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } - // Act - // is done in the test case sourceForContentsIsNull + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForFileIsReadOnly))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowOneUnauthorizedAccessExceptionIfFileIsReadOnly(Action action, string path) + { + // Arrange + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - await That(exception.ParamName).IsEqualTo("contents"); - } + // Act + // is done in the test case source + + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } + + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForContentsIsNull))] + public async Task MockFile_WriteAllLinesGeneric_ShouldThrowAnArgumentNullExceptionIfContentsIsNull(Action action) + { + // Arrange + // is done in the test case source + + // Act + // is done in the test case sourceForContentsIsNull + + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).IsEqualTo("contents"); + } #if FEATURE_ASYNC_FILE - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForDifferentEncodingAsync))] - public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldWriteTheCorrectContent(IMockFileDataAccessor fileSystem, Action action, string expectedContent) - { - // Arrange - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForDifferentEncodingAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldWriteTheCorrectContent(IMockFileDataAccessor fileSystem, Action action, string expectedContent) + { + // Arrange + // is done in the test case source - // Act - action(); + // Act + action(); - // Assert - var actualContent = fileSystem.GetFile(TestDataForWriteAllLines.Path).TextContents; - await That(actualContent).IsEqualTo(expectedContent); - } + // Assert + var actualContent = fileSystem.GetFile(TestDataForWriteAllLines.Path).TextContents; + await That(actualContent).IsEqualTo(expectedContent); + } - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForNullPathAsync))] - public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfPathIsNull(Func action) - { - // Arrange - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForNullPathAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfPathIsNull(Func action) + { + // Arrange + // is done in the test case source - // Act - // is done in the test case source + // Act + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - await That(exception.ParamName).StartsWith("path"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("path"); + } - [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullEncodingAsync")] - public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfEncodingIsNull(Func action) - { - // Arrange - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), "ForNullEncodingAsync")] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfEncodingIsNull(Func action) + { + // Arrange + // is done in the test case source - // Act - // is done in the test case source + // Act + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - await That(exception.ParamName).StartsWith("encoding"); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).StartsWith("encoding"); + } - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForIllegalPathAsync))] - [WindowsOnly(WindowsSpecifics.StrictPathRules)] - public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentExceptionIfPathContainsIllegalCharacters(Func action) - { - // Arrange - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForIllegalPathAsync))] + [WindowsOnly(WindowsSpecifics.StrictPathRules)] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentExceptionIfPathContainsIllegalCharacters(Func action) + { + // Arrange + // is done in the test case source - // Act - // is done in the test case source + // Act + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).IsEqualTo("Illegal characters in path."); - } + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).IsEqualTo("Illegal characters in path."); + } - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForPathIsDirectoryAsync))] - public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnUnauthorizedAccessExceptionIfPathIsOneDirectory(Func action, string path) - { - // Arrange - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForPathIsDirectoryAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnUnauthorizedAccessExceptionIfPathIsOneDirectory(Func action, string path) + { + // Arrange + // is done in the test case source - // Act - // is done in the test case source + // Act + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); - await That(exception.Message).IsEqualTo(expectedMessage); - } + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForFileIsReadOnlyAsync))] - public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowOneUnauthorizedAccessExceptionIfFileIsReadOnly(Func action, string path) - { - // Arrange - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForFileIsReadOnlyAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowOneUnauthorizedAccessExceptionIfFileIsReadOnly(Func action, string path) + { + // Arrange + // is done in the test case source - // Act - // is done in the test case source + // Act + // is done in the test case source - // Assert - var exception = await That(action).Throws(); - var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); - await That(exception.Message).IsEqualTo(expectedMessage); - } + // Assert + var exception = await That(action).Throws(); + var expectedMessage = string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path); + await That(exception.Message).IsEqualTo(expectedMessage); + } - [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForContentsIsNullAsync))] - public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfContentsIsNull(Func action) - { - // Arrange - // is done in the test case source + [TestCaseSource(typeof(TestDataForWriteAllLines), nameof(TestDataForWriteAllLines.ForContentsIsNullAsync))] + public async Task MockFile_WriteAllLinesAsyncGeneric_ShouldThrowAnArgumentNullExceptionIfContentsIsNull(Func action) + { + // Arrange + // is done in the test case source - // Act - // is done in the test case sourceForContentsIsNull + // Act + // is done in the test case sourceForContentsIsNull - // Assert - var exception = await That(action).Throws(); - await That(exception.Message).StartsWith("Value cannot be null."); - await That(exception.ParamName).IsEqualTo("contents"); - } -#endif + // Assert + var exception = await That(action).Throws(); + await That(exception.Message).StartsWith("Value cannot be null."); + await That(exception.ParamName).IsEqualTo("contents"); } -} +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllTextTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllTextTests.cs index 88942d461..5cd2cd64c 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllTextTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileWriteAllTextTests.cs @@ -1,413 +1,412 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using Collections.Generic; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using Collections.Generic; - using NUnit.Framework; +using NUnit.Framework; - using Text; +using Text; - using XFS = MockUnixSupport; +using XFS = MockUnixSupport; - using System.Threading.Tasks; - using System.Threading; +using System.Threading.Tasks; +using System.Threading; - public class MockFileWriteAllTextTests +public class MockFileWriteAllTextTests +{ + [Test] + public async Task MockFile_WriteAllText_ShouldWriteTextFileToMemoryFileSystem() { - [Test] - public async Task MockFile_WriteAllText_ShouldWriteTextFileToMemoryFileSystem() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - string fileContent = "Hello there!"; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "Hello there!"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - // Act - fileSystem.File.WriteAllText(path, fileContent); + // Act + fileSystem.File.WriteAllText(path, fileContent); - // Assert - await That(fileSystem.GetFile(path).TextContents).IsEqualTo(fileContent); - } + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(fileContent); + } - [Test] - public async Task MockFile_WriteAllText_ShouldOverwriteAnExistingFile() - { - // http://msdn.microsoft.com/en-us/library/ms143375.aspx + [Test] + public async Task MockFile_WriteAllText_ShouldOverwriteAnExistingFile() + { + // http://msdn.microsoft.com/en-us/library/ms143375.aspx - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - // Act - fileSystem.File.WriteAllText(path, "foo"); - fileSystem.File.WriteAllText(path, "bar"); + // Act + fileSystem.File.WriteAllText(path, "foo"); + fileSystem.File.WriteAllText(path, "bar"); - // Assert - await That(fileSystem.GetFile(path).TextContents).IsEqualTo("bar"); - } + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo("bar"); + } - [Test] - public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("this is hidden") }, - }); - fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - - // Act - Action action = () => fileSystem.File.WriteAllText(path, "hello world"); - - // Assert - await That(action).Throws() - .Because($"Access to the path '{path}' is denied."); - } - - [Test] - public async Task MockFile_WriteAllText_ShouldThrowAnArgumentExceptionIfThePathIsEmpty() + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { path, new MockFileData("this is hidden") }, + }); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - // Act - Action action = () => fileSystem.File.WriteAllText(string.Empty, "hello world"); + // Act + Action action = () => fileSystem.File.WriteAllText(path, "hello world"); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws() + .Because($"Access to the path '{path}' is denied."); + } - [Test] - public async Task MockFile_WriteAllText_ShouldNotThrowAnArgumentNullExceptionIfTheContentIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - string directoryPath = XFS.Path(@"c:\something"); - string filePath = XFS.Path(@"c:\something\demo.txt"); - fileSystem.AddDirectory(directoryPath); - - // Act - fileSystem.File.WriteAllText(filePath, null); - - // Assert - // no exception should be thrown, also the documentation says so - var data = fileSystem.GetFile(filePath); - await That(data.Contents).IsEmpty(); - } - - [Test] - public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfTheFileIsReadOnly() - { - // Arrange - var fileSystem = new MockFileSystem(); - string filePath = XFS.Path(@"c:\something\demo.txt"); - var mockFileData = new MockFileData(new byte[0]); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddFile(filePath, mockFileData); - - // Act - Action action = () => fileSystem.File.WriteAllText(filePath, null); - - // Assert - await That(action).Throws(); - } - - [Test] - public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory() - { - // Arrange - var fileSystem = new MockFileSystem(); - string directoryPath = XFS.Path(@"c:\something"); - fileSystem.AddDirectory(directoryPath); + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnArgumentExceptionIfThePathIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Action action = () => fileSystem.File.WriteAllText(directoryPath, null); + // Act + Action action = () => fileSystem.File.WriteAllText(string.Empty, "hello world"); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_WriteAllText_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"c:\something\file.txt"); + [Test] + public async Task MockFile_WriteAllText_ShouldNotThrowAnArgumentNullExceptionIfTheContentIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + string filePath = XFS.Path(@"c:\something\demo.txt"); + fileSystem.AddDirectory(directoryPath); + + // Act + fileSystem.File.WriteAllText(filePath, null); + + // Assert + // no exception should be thrown, also the documentation says so + var data = fileSystem.GetFile(filePath); + await That(data.Contents).IsEmpty(); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfTheFileIsReadOnly() + { + // Arrange + var fileSystem = new MockFileSystem(); + string filePath = XFS.Path(@"c:\something\demo.txt"); + var mockFileData = new MockFileData(new byte[0]); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(filePath, mockFileData); + + // Act + Action action = () => fileSystem.File.WriteAllText(filePath, null); + + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + fileSystem.AddDirectory(directoryPath); + + // Act + Action action = () => fileSystem.File.WriteAllText(directoryPath, null); - // Act - Action action = () => fileSystem.File.WriteAllText(path, string.Empty); + // Assert + await That(action).Throws(); + } + + [Test] + public async Task MockFile_WriteAllText_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.txt"); - // Assert - await That(action).Throws(); - } + // Act + Action action = () => fileSystem.File.WriteAllText(path, string.Empty); + + // Assert + await That(action).Throws(); + } - public static IEnumerable> GetEncodingsWithExpectedBytes() + public static IEnumerable> GetEncodingsWithExpectedBytes() + { + Encoding utf8WithoutBom = new UTF8Encoding(false, true); + return new Dictionary { - Encoding utf8WithoutBom = new UTF8Encoding(false, true); - return new Dictionary - { - // ASCII does not need a BOM - { Encoding.ASCII, new byte[] { 72, 101, 108, 108, 111, 32, 116, - 104, 101, 114, 101, 33, 32, 68, 122, 105, 63, 107, 105, 46 } }, - - // BigEndianUnicode needs a BOM, the BOM is the first two bytes - { Encoding.BigEndianUnicode, new byte [] { 254, 255, 0, 72, 0, 101, - 0, 108, 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, - 0, 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 1, 25, 0, 107, 0, 105, 0, 46 } }, - - // UTF-32 needs a BOM, the BOM is the first four bytes - { Encoding.UTF32, new byte [] {255, 254, 0, 0, 72, 0, 0, 0, 101, - 0, 0, 0, 108, 0, 0, 0, 108, 0, 0, 0, 111, 0, 0, 0, 32, 0, 0, - 0, 116, 0, 0, 0, 104, 0, 0, 0, 101, 0, 0, 0, 114, 0, 0, 0, - 101, 0, 0, 0, 33, 0, 0, 0, 32, 0, 0, 0, 68, 0, 0, 0, 122, 0, - 0, 0, 105, 0, 0, 0, 25, 1, 0, 0, 107, 0, 0, 0, 105, 0, 0, 0, 46, 0, 0, 0 } }, + // ASCII does not need a BOM + { Encoding.ASCII, new byte[] { 72, 101, 108, 108, 111, 32, 116, + 104, 101, 114, 101, 33, 32, 68, 122, 105, 63, 107, 105, 46 } }, + + // BigEndianUnicode needs a BOM, the BOM is the first two bytes + { Encoding.BigEndianUnicode, new byte [] { 254, 255, 0, 72, 0, 101, + 0, 108, 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, + 0, 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 1, 25, 0, 107, 0, 105, 0, 46 } }, + + // UTF-32 needs a BOM, the BOM is the first four bytes + { Encoding.UTF32, new byte [] {255, 254, 0, 0, 72, 0, 0, 0, 101, + 0, 0, 0, 108, 0, 0, 0, 108, 0, 0, 0, 111, 0, 0, 0, 32, 0, 0, + 0, 116, 0, 0, 0, 104, 0, 0, 0, 101, 0, 0, 0, 114, 0, 0, 0, + 101, 0, 0, 0, 33, 0, 0, 0, 32, 0, 0, 0, 68, 0, 0, 0, 122, 0, + 0, 0, 105, 0, 0, 0, 25, 1, 0, 0, 107, 0, 0, 0, 105, 0, 0, 0, 46, 0, 0, 0 } }, #pragma warning disable SYSLIB0001 - // UTF-7 does not need a BOM - { Encoding.UTF7, new byte [] {72, 101, 108, 108, 111, 32, 116, - 104, 101, 114, 101, 43, 65, 67, 69, 45, 32, 68, 122, 105, - 43, 65, 82, 107, 45, 107, 105, 46 } }, + // UTF-7 does not need a BOM + { Encoding.UTF7, new byte [] {72, 101, 108, 108, 111, 32, 116, + 104, 101, 114, 101, 43, 65, 67, 69, 45, 32, 68, 122, 105, + 43, 65, 82, 107, 45, 107, 105, 46 } }, #pragma warning restore SYSLIB0001 - // The default encoding does not need a BOM - { utf8WithoutBom, new byte [] { 72, 101, 108, 108, 111, 32, 116, - 104, 101, 114, 101, 33, 32, 68, 122, 105, 196, 153, 107, 105, 46 } }, + // The default encoding does not need a BOM + { utf8WithoutBom, new byte [] { 72, 101, 108, 108, 111, 32, 116, + 104, 101, 114, 101, 33, 32, 68, 122, 105, 196, 153, 107, 105, 46 } }, - // Unicode needs a BOM, the BOM is the first two bytes - { Encoding.Unicode, new byte [] { 255, 254, 72, 0, 101, 0, 108, - 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, 0, - 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 0, 25, 1, 107, 0, - 105, 0, 46, 0 } } - }; - } + // Unicode needs a BOM, the BOM is the first two bytes + { Encoding.Unicode, new byte [] { 255, 254, 72, 0, 101, 0, 108, + 0, 108, 0, 111, 0, 32, 0, 116, 0, 104, 0, 101, 0, 114, 0, + 101, 0, 33, 0, 32, 0, 68, 0, 122, 0, 105, 0, 25, 1, 107, 0, + 105, 0, 46, 0 } } + }; + } - [TestCaseSource(typeof(MockFileWriteAllTextTests), nameof(GetEncodingsWithExpectedBytes))] - public async Task MockFile_WriteAllText_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair encodingsWithContents) - { - // Arrange - const string FileContent = "Hello there! Dzięki."; - string path = XFS.Path(@"c:\something\demo.txt"); - byte[] expectedBytes = encodingsWithContents.Value; - Encoding encoding = encodingsWithContents.Key; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - - // Act - fileSystem.File.WriteAllText(path, FileContent, encoding); - - // Assert - var actualBytes = fileSystem.GetFile(path).Contents; - await That(actualBytes).IsEqualTo(expectedBytes); - } - - [Test] - public async Task MockFile_WriteAllTextMultipleLines_ShouldWriteTextFileToMemoryFileSystem() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); + [TestCaseSource(typeof(MockFileWriteAllTextTests), nameof(GetEncodingsWithExpectedBytes))] + public async Task MockFile_WriteAllText_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair encodingsWithContents) + { + // Arrange + const string FileContent = "Hello there! Dzięki."; + string path = XFS.Path(@"c:\something\demo.txt"); + byte[] expectedBytes = encodingsWithContents.Value; + Encoding encoding = encodingsWithContents.Key; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + fileSystem.File.WriteAllText(path, FileContent, encoding); + + // Assert + var actualBytes = fileSystem.GetFile(path).Contents; + await That(actualBytes).IsEqualTo(expectedBytes); + } - var fileContent = new List { "Hello there!", "Second line!" }; - var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; + [Test] + public async Task MockFile_WriteAllTextMultipleLines_ShouldWriteTextFileToMemoryFileSystem() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + var fileContent = new List { "Hello there!", "Second line!" }; + var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; - // Act - fileSystem.File.WriteAllLines(path, fileContent); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - // Assert - await That(fileSystem.GetFile(path).TextContents).IsEqualTo(expected); - } + // Act + fileSystem.File.WriteAllLines(path, fileContent); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(expected); + } #if FEATURE_ASYNC_FILE - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldWriteTextFileToMemoryFileSystem() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - string fileContent = "Hello there!"; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldWriteTextFileToMemoryFileSystem() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + string fileContent = "Hello there!"; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - // Act - await fileSystem.File.WriteAllTextAsync(path, fileContent); + // Act + await fileSystem.File.WriteAllTextAsync(path, fileContent); - // Assert - await That(fileSystem.GetFile(path).TextContents).IsEqualTo(fileContent); - } + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(fileContent); + } - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldThrowOperationCanceledExceptionIfCancelled() - { - // Arrange - const string path = "test.txt"; - var fileSystem = new MockFileSystem(); - - // Act - async Task Act() => - await fileSystem.File.WriteAllTextAsync( - path, - "line", - new CancellationToken(canceled: true)); - await That(Act).Throws(); - - // Assert - await That(fileSystem.File.Exists(path)).IsFalse(); - } - - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldOverriteAnExistingFile() - { - // http://msdn.microsoft.com/en-us/library/ms143375.aspx + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowOperationCanceledExceptionIfCancelled() + { + // Arrange + const string path = "test.txt"; + var fileSystem = new MockFileSystem(); + + // Act + async Task Act() => + await fileSystem.File.WriteAllTextAsync( + path, + "line", + new CancellationToken(canceled: true)); + await That(Act).Throws(); + + // Assert + await That(fileSystem.File.Exists(path)).IsFalse(); + } - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldOverriteAnExistingFile() + { + // http://msdn.microsoft.com/en-us/library/ms143375.aspx - // Act - await fileSystem.File.WriteAllTextAsync(path, "foo"); - await fileSystem.File.WriteAllTextAsync(path, "bar"); + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); - // Assert - await That(fileSystem.GetFile(path).TextContents).IsEqualTo("bar"); - } + // Act + await fileSystem.File.WriteAllTextAsync(path, "foo"); + await fileSystem.File.WriteAllTextAsync(path, "bar"); - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); - var fileSystem = new MockFileSystem(new Dictionary - { - { path, new MockFileData("this is hidden") }, - }); - fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - - // Act - Func action = () => fileSystem.File.WriteAllTextAsync(path, "hello world"); - - // Assert - await That(action).Throws() - .Because($"Access to the path '{path}' is denied."); - } - - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldThrowAnArgumentExceptionIfThePathIsEmpty() + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo("bar"); + } + + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfFileIsHidden() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + var fileSystem = new MockFileSystem(new Dictionary { - // Arrange - var fileSystem = new MockFileSystem(); + { path, new MockFileData("this is hidden") }, + }); + fileSystem.File.SetAttributes(path, FileAttributes.Hidden); - // Act - Func action = () => fileSystem.File.WriteAllTextAsync(string.Empty, "hello world"); + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(path, "hello world"); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws() + .Because($"Access to the path '{path}' is denied."); + } - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldNotThrowAnArgumentNullExceptionIfTheContentIsNull() - { - // Arrange - var fileSystem = new MockFileSystem(); - string directoryPath = XFS.Path(@"c:\something"); - string filePath = XFS.Path(@"c:\something\demo.txt"); - fileSystem.AddDirectory(directoryPath); - - // Act - await fileSystem.File.WriteAllTextAsync(filePath, ""); - - // Assert - // no exception should be thrown, also the documentation says so - var data = fileSystem.GetFile(filePath); - await That(data.Contents).IsEmpty(); - } - - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfTheFileIsReadOnly() - { - // Arrange - var fileSystem = new MockFileSystem(); - string filePath = XFS.Path(@"c:\something\demo.txt"); - var mockFileData = new MockFileData(new byte[0]); - mockFileData.Attributes = FileAttributes.ReadOnly; - fileSystem.AddFile(filePath, mockFileData); - - // Act - Func action = () => fileSystem.File.WriteAllTextAsync(filePath, ""); - - // Assert - await That(action).Throws(); - } - - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory() - { - // Arrange - var fileSystem = new MockFileSystem(); - string directoryPath = XFS.Path(@"c:\something"); - fileSystem.AddDirectory(directoryPath); + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnArgumentExceptionIfThePathIsEmpty() + { + // Arrange + var fileSystem = new MockFileSystem(); - // Act - Func action = () => fileSystem.File.WriteAllTextAsync(directoryPath, ""); + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(string.Empty, "hello world"); - // Assert - await That(action).Throws(); - } + // Assert + await That(action).Throws(); + } - [Test] - public async Task MockFile_WriteAllTextAsync_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() - { - // Arrange - var fileSystem = new MockFileSystem(); - string path = XFS.Path(@"c:\something\file.txt"); + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldNotThrowAnArgumentNullExceptionIfTheContentIsNull() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + string filePath = XFS.Path(@"c:\something\demo.txt"); + fileSystem.AddDirectory(directoryPath); + + // Act + await fileSystem.File.WriteAllTextAsync(filePath, ""); + + // Assert + // no exception should be thrown, also the documentation says so + var data = fileSystem.GetFile(filePath); + await That(data.Contents).IsEmpty(); + } - // Act - Func action = () => fileSystem.File.WriteAllTextAsync(path, string.Empty); + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfTheFileIsReadOnly() + { + // Arrange + var fileSystem = new MockFileSystem(); + string filePath = XFS.Path(@"c:\something\demo.txt"); + var mockFileData = new MockFileData(new byte[0]); + mockFileData.Attributes = FileAttributes.ReadOnly; + fileSystem.AddFile(filePath, mockFileData); + + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(filePath, ""); + + // Assert + await That(action).Throws(); + } - // Assert - await That(action).Throws(); - } + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory() + { + // Arrange + var fileSystem = new MockFileSystem(); + string directoryPath = XFS.Path(@"c:\something"); + fileSystem.AddDirectory(directoryPath); - [TestCaseSource(typeof(MockFileWriteAllTextTests), nameof(GetEncodingsWithExpectedBytes))] - public async Task MockFile_WriteAllTextAsync_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair encodingsWithContents) - { - // Arrange - const string FileContent = "Hello there! Dzięki."; - string path = XFS.Path(@"c:\something\demo.txt"); - byte[] expectedBytes = encodingsWithContents.Value; - Encoding encoding = encodingsWithContents.Key; - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); - - // Act - await fileSystem.File.WriteAllTextAsync(path, FileContent, encoding); - - // Assert - var actualBytes = fileSystem.GetFile(path).Contents; - await That(actualBytes).IsEqualTo(expectedBytes); - } - - [Test] - public async Task MockFile_WriteAllTextAsyncMultipleLines_ShouldWriteTextFileToMemoryFileSystem() - { - // Arrange - string path = XFS.Path(@"c:\something\demo.txt"); + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(directoryPath, ""); - var fileContent = new List { "Hello there!", "Second line!" }; - var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; + // Assert + await That(action).Throws(); + } - var fileSystem = new MockFileSystem(); - fileSystem.AddDirectory(XFS.Path(@"c:\something")); + [Test] + public async Task MockFile_WriteAllTextAsync_ShouldThrowDirectoryNotFoundExceptionIfPathDoesNotExists() + { + // Arrange + var fileSystem = new MockFileSystem(); + string path = XFS.Path(@"c:\something\file.txt"); - // Act - await fileSystem.File.WriteAllLinesAsync(path, fileContent); + // Act + Func action = () => fileSystem.File.WriteAllTextAsync(path, string.Empty); - // Assert - await That(fileSystem.GetFile(path).TextContents).IsEqualTo(expected); - } -#endif + // Assert + await That(action).Throws(); } -} + + [TestCaseSource(typeof(MockFileWriteAllTextTests), nameof(GetEncodingsWithExpectedBytes))] + public async Task MockFile_WriteAllTextAsync_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair encodingsWithContents) + { + // Arrange + const string FileContent = "Hello there! Dzięki."; + string path = XFS.Path(@"c:\something\demo.txt"); + byte[] expectedBytes = encodingsWithContents.Value; + Encoding encoding = encodingsWithContents.Key; + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + await fileSystem.File.WriteAllTextAsync(path, FileContent, encoding); + + // Assert + var actualBytes = fileSystem.GetFile(path).Contents; + await That(actualBytes).IsEqualTo(expectedBytes); + } + + [Test] + public async Task MockFile_WriteAllTextAsyncMultipleLines_ShouldWriteTextFileToMemoryFileSystem() + { + // Arrange + string path = XFS.Path(@"c:\something\demo.txt"); + + var fileContent = new List { "Hello there!", "Second line!" }; + var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine; + + var fileSystem = new MockFileSystem(); + fileSystem.AddDirectory(XFS.Path(@"c:\something")); + + // Act + await fileSystem.File.WriteAllLinesAsync(path, fileContent); + + // Assert + await That(fileSystem.GetFile(path).TextContents).IsEqualTo(expected); + } +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs index 0d01f031e..e614de495 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockPathTests.cs @@ -1,577 +1,577 @@ using NUnit.Framework; using System.Collections.Generic; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; + +public class MockPathTests { - using XFS = MockUnixSupport; + static readonly string TestPath = XFS.Path("C:\\test\\test.bmp"); - public class MockPathTests + [Test] + public async Task ChangeExtension_ExtensionNoPeriod_PeriodAdded() { - static readonly string TestPath = XFS.Path("C:\\test\\test.bmp"); + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - [Test] - public async Task ChangeExtension_ExtensionNoPeriod_PeriodAdded() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + //Act + var result = mockPath.ChangeExtension(TestPath, "doc"); - //Act - var result = mockPath.ChangeExtension(TestPath, "doc"); - - //Assert - await That(result).IsEqualTo(XFS.Path("C:\\test\\test.doc")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\test.doc")); + } - [Test] - public async Task Combine_SentTwoPaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task Combine_SentTwoPaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "test.bmp"); + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "test.bmp"); - //Assert - await That(result).IsEqualTo(XFS.Path("C:\\test\\test.bmp")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\test.bmp")); + } - [Test] - public async Task Combine_SentThreePaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task Combine_SentThreePaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "test.bmp"); + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "test.bmp"); - //Assert - await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\test.bmp")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\test.bmp")); + } - [Test] - public async Task Combine_SentFourPaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task Combine_SentFourPaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "test.bmp"); + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "test.bmp"); - //Assert - await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\subdir2\\test.bmp")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\subdir2\\test.bmp")); + } - [Test] - public async Task Combine_SentFivePaths_Combines() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task Combine_SentFivePaths_Combines() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "subdir3", "test.bmp"); + //Act + var result = mockPath.Combine(XFS.Path("C:\\test"), "subdir1", "subdir2", "subdir3", "test.bmp"); - //Assert - await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\subdir2\\subdir3\\test.bmp")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test\\subdir1\\subdir2\\subdir3\\test.bmp")); + } - [Test] - public async Task GetDirectoryName_SentPath_ReturnsDirectory() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetDirectoryName_SentPath_ReturnsDirectory() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetDirectoryName(TestPath); + //Act + var result = mockPath.GetDirectoryName(TestPath); - //Assert - await That(result).IsEqualTo(XFS.Path("C:\\test")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\test")); + } - [Test] - public async Task GetExtension_SendInPath_ReturnsExtension() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetExtension_SendInPath_ReturnsExtension() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetExtension(TestPath); + //Act + var result = mockPath.GetExtension(TestPath); - //Assert - await That(result).IsEqualTo(".bmp"); - } + //Assert + await That(result).IsEqualTo(".bmp"); + } - [Test] - public async Task GetFileName_SendInPath_ReturnsFilename() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetFileName_SendInPath_ReturnsFilename() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetFileName(TestPath); + //Act + var result = mockPath.GetFileName(TestPath); - //Assert - await That(result).IsEqualTo("test.bmp"); - } + //Assert + await That(result).IsEqualTo("test.bmp"); + } - [Test] - public async Task GetFileNameWithoutExtension_SendInPath_ReturnsFileNameNoExt() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetFileNameWithoutExtension_SendInPath_ReturnsFileNameNoExt() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetFileNameWithoutExtension(TestPath); + //Act + var result = mockPath.GetFileNameWithoutExtension(TestPath); - //Assert - await That(result).IsEqualTo("test"); - } + //Assert + await That(result).IsEqualTo("test"); + } - [Test] - public async Task GetFullPath_SendInPath_ReturnsFullPath() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetFullPath_SendInPath_ReturnsFullPath() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetFullPath(TestPath); + //Act + var result = mockPath.GetFullPath(TestPath); - //Assert - await That(result).IsEqualTo(TestPath); - } + //Assert + await That(result).IsEqualTo(TestPath); + } - public static IEnumerable GetFullPath_RelativePaths_Cases + public static IEnumerable GetFullPath_RelativePaths_Cases + { + get { - get - { - yield return new[] { XFS.Path(@"c:\a"), "b", XFS.Path(@"c:\a\b") }; - yield return new[] { XFS.Path(@"c:\a\b"), "c", XFS.Path(@"c:\a\b\c") }; - yield return new[] { XFS.Path(@"c:\a\b"), XFS.Path(@"c\"), XFS.Path(@"c:\a\b\c\") }; - yield return new[] { XFS.Path(@"c:\a\b"), XFS.Path(@"..\c"), XFS.Path(@"c:\a\c") }; - yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\c\..\"), XFS.Path(@"c:\a\b\") }; - yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d"), XFS.Path(@"c:\d") }; - yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d\"), XFS.Path(@"c:\d\") }; - } + yield return new[] { XFS.Path(@"c:\a"), "b", XFS.Path(@"c:\a\b") }; + yield return new[] { XFS.Path(@"c:\a\b"), "c", XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\b"), XFS.Path(@"c\"), XFS.Path(@"c:\a\b\c\") }; + yield return new[] { XFS.Path(@"c:\a\b"), XFS.Path(@"..\c"), XFS.Path(@"c:\a\c") }; + yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\c\..\"), XFS.Path(@"c:\a\b\") }; + yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d"), XFS.Path(@"c:\d") }; + yield return new[] { XFS.Path(@"c:\a\b\c"), XFS.Path(@"..\..\..\..\..\d\"), XFS.Path(@"c:\d\") }; } + } - [TestCaseSource(nameof(GetFullPath_RelativePaths_Cases))] - public async Task GetFullPath_RelativePaths_ShouldReturnTheAbsolutePathWithCurrentDirectory(string currentDir, string relativePath, string expectedResult) - { - //Arrange - var mockFileSystem = new MockFileSystem(); - mockFileSystem.Directory.SetCurrentDirectory(currentDir); - var mockPath = new MockPath(mockFileSystem); + [TestCaseSource(nameof(GetFullPath_RelativePaths_Cases))] + public async Task GetFullPath_RelativePaths_ShouldReturnTheAbsolutePathWithCurrentDirectory(string currentDir, string relativePath, string expectedResult) + { + //Arrange + var mockFileSystem = new MockFileSystem(); + mockFileSystem.Directory.SetCurrentDirectory(currentDir); + var mockPath = new MockPath(mockFileSystem); - //Act - var actualResult = mockPath.GetFullPath(relativePath); + //Act + var actualResult = mockPath.GetFullPath(relativePath); - //Assert - await That(actualResult).IsEqualTo(expectedResult); - } + //Assert + await That(actualResult).IsEqualTo(expectedResult); + } - public static IEnumerable GetFullPath_RootedPathWithRelativeSegments_Cases + public static IEnumerable GetFullPath_RootedPathWithRelativeSegments_Cases + { + get { - get - { - yield return new[] { XFS.Path(@"c:\a\b\..\c"), XFS.Path(@"c:\a\c") }; - yield return new[] { XFS.Path(@"c:\a\b\.\.\..\.\c"), XFS.Path(@"c:\a\c") }; - yield return new[] { XFS.Path(@"c:\a\b\.\c"), XFS.Path(@"c:\a\b\c") }; - yield return new[] { XFS.Path(@"c:\a\b\.\.\.\.\c"), XFS.Path(@"c:\a\b\c") }; - yield return new[] { XFS.Path(@"c:\a\..\..\c"), XFS.Path(@"c:\c") }; - } + yield return new[] { XFS.Path(@"c:\a\b\..\c"), XFS.Path(@"c:\a\c") }; + yield return new[] { XFS.Path(@"c:\a\b\.\.\..\.\c"), XFS.Path(@"c:\a\c") }; + yield return new[] { XFS.Path(@"c:\a\b\.\c"), XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\b\.\.\.\.\c"), XFS.Path(@"c:\a\b\c") }; + yield return new[] { XFS.Path(@"c:\a\..\..\c"), XFS.Path(@"c:\c") }; } + } - [TestCaseSource(nameof(GetFullPath_RootedPathWithRelativeSegments_Cases))] - public async Task GetFullPath_RootedPathWithRelativeSegments_ShouldReturnAnRootedAbsolutePath(string rootedPath, string expectedResult) - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); + [TestCaseSource(nameof(GetFullPath_RootedPathWithRelativeSegments_Cases))] + public async Task GetFullPath_RootedPathWithRelativeSegments_ShouldReturnAnRootedAbsolutePath(string rootedPath, string expectedResult) + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); - //Act - var actualResult = mockPath.GetFullPath(rootedPath); + //Act + var actualResult = mockPath.GetFullPath(rootedPath); - //Assert - await That(actualResult).IsEqualTo(expectedResult); - } + //Assert + await That(actualResult).IsEqualTo(expectedResult); + } - public static IEnumerable GetFullPath_AbsolutePaths_Cases + public static IEnumerable GetFullPath_AbsolutePaths_Cases + { + get { - get - { - yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"/b"), XFS.Path(@"c:\b") }; - yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"/b\"), XFS.Path(@"c:\b\") }; - yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"\b"), XFS.Path(@"c:\b") }; - yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"c:\c") }; - yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"z:\c") }; - yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c"), XFS.Path(@"\\computer\share\c") }; - yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\d"), XFS.Path(@"\\computer\share\d") }; - yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\..\d"), XFS.Path(@"\\computer\share\d") }; - } + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"/b"), XFS.Path(@"c:\b") }; + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"/b\"), XFS.Path(@"c:\b\") }; + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"\b"), XFS.Path(@"c:\b") }; + yield return new[] { XFS.Path(@"c:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"c:\c") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\b\..\c"), XFS.Path(@"z:\c") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c"), XFS.Path(@"\\computer\share\c") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\d"), XFS.Path(@"\\computer\share\d") }; + yield return new[] { XFS.Path(@"z:\a"), XFS.Path(@"\\computer\share\c\..\..\d"), XFS.Path(@"\\computer\share\d") }; } + } - [TestCaseSource(nameof(GetFullPath_AbsolutePaths_Cases))] - public async Task GetFullPath_AbsolutePaths_ShouldReturnThePathWithTheRoot_Or_Unc(string currentDir, string absolutePath, string expectedResult) - { - //Arrange - var mockFileSystem = new MockFileSystem(); - mockFileSystem.Directory.SetCurrentDirectory(currentDir); - var mockPath = new MockPath(mockFileSystem); + [TestCaseSource(nameof(GetFullPath_AbsolutePaths_Cases))] + public async Task GetFullPath_AbsolutePaths_ShouldReturnThePathWithTheRoot_Or_Unc(string currentDir, string absolutePath, string expectedResult) + { + //Arrange + var mockFileSystem = new MockFileSystem(); + mockFileSystem.Directory.SetCurrentDirectory(currentDir); + var mockPath = new MockPath(mockFileSystem); - //Act - var actualResult = mockPath.GetFullPath(absolutePath); + //Act + var actualResult = mockPath.GetFullPath(absolutePath); - //Assert - await That(actualResult).IsEqualTo(expectedResult); - } + //Assert + await That(actualResult).IsEqualTo(expectedResult); + } - [Test] - public async Task GetFullPath_InvalidUNCPaths_ShouldThrowArgumentException() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); + [Test] + public async Task GetFullPath_InvalidUNCPaths_ShouldThrowArgumentException() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); - //Act - Action action = () => mockPath.GetFullPath(XFS.Path(@"\\shareZ")); + //Act + Action action = () => mockPath.GetFullPath(XFS.Path(@"\\shareZ")); - //Assert - await That(action).Throws(); - } + //Assert + await That(action).Throws(); + } - [Test] - public async Task GetFullPath_NullValue_ShouldThrowArgumentNullException() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); + [Test] + public async Task GetFullPath_NullValue_ShouldThrowArgumentNullException() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); - //Act - Action action = () => mockPath.GetFullPath(null); + //Act + Action action = () => mockPath.GetFullPath(null); - //Assert - await That(action).Throws(); - } + //Assert + await That(action).Throws(); + } - [Test] - public async Task GetFullPath_EmptyValue_ShouldThrowArgumentException() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); + [Test] + public async Task GetFullPath_EmptyValue_ShouldThrowArgumentException() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); - //Act - Action action = () => mockPath.GetFullPath(string.Empty); + //Act + Action action = () => mockPath.GetFullPath(string.Empty); - //Assert - await That(action).Throws(); - } + //Assert + await That(action).Throws(); + } - [Test] - public async Task GetFullPath_WithWhiteSpace_ShouldThrowArgumentException() - { - var mockFileSystem = new MockFileSystem(); + [Test] + public async Task GetFullPath_WithWhiteSpace_ShouldThrowArgumentException() + { + var mockFileSystem = new MockFileSystem(); - Action action = () => mockFileSystem.Path.GetFullPath(" "); + Action action = () => mockFileSystem.Path.GetFullPath(" "); - await That(action).Throws(); - } + await That(action).Throws(); + } - [Test] - public async Task GetFullPath_WithMultipleDirectorySeparators_ShouldReturnTheNormalizedForm() - { - //Arrange - var mockFileSystem = new MockFileSystem(); - var mockPath = new MockPath(mockFileSystem); + [Test] + public async Task GetFullPath_WithMultipleDirectorySeparators_ShouldReturnTheNormalizedForm() + { + //Arrange + var mockFileSystem = new MockFileSystem(); + var mockPath = new MockPath(mockFileSystem); - //Act - var actualFullPath = mockPath.GetFullPath(XFS.Path(@"c:\foo\\//bar\file.dat")); + //Act + var actualFullPath = mockPath.GetFullPath(XFS.Path(@"c:\foo\\//bar\file.dat")); - //Assert - await That(actualFullPath).IsEqualTo(XFS.Path(@"c:\foo\bar\file.dat")); - } + //Assert + await That(actualFullPath).IsEqualTo(XFS.Path(@"c:\foo\bar\file.dat")); + } - [Test] - public async Task GetInvalidFileNameChars_Called_ReturnsChars() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetInvalidFileNameChars_Called_ReturnsChars() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetInvalidFileNameChars(); + //Act + var result = mockPath.GetInvalidFileNameChars(); - //Assert - await That(result.Length > 0).IsTrue(); - } + //Assert + await That(result.Length > 0).IsTrue(); + } - [Test] - public async Task GetInvalidPathChars_Called_ReturnsChars() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetInvalidPathChars_Called_ReturnsChars() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetInvalidPathChars(); + //Act + var result = mockPath.GetInvalidPathChars(); - //Assert - await That(result.Length > 0).IsTrue(); - } + //Assert + await That(result.Length > 0).IsTrue(); + } - [Test] - public async Task GetPathRoot_SendInPath_ReturnsRoot() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetPathRoot_SendInPath_ReturnsRoot() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetPathRoot(TestPath); + //Act + var result = mockPath.GetPathRoot(TestPath); - //Assert - await That(result).IsEqualTo(XFS.Path("C:\\")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("C:\\")); + } - [Test] - public async Task GetRandomFileName_Called_ReturnsStringLengthGreaterThanZero() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetRandomFileName_Called_ReturnsStringLengthGreaterThanZero() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetRandomFileName(); + //Act + var result = mockPath.GetRandomFileName(); - //Assert - await That(result.Length > 0).IsTrue(); - } + //Assert + await That(result.Length > 0).IsTrue(); + } - [Test] - public async Task GetTempFileName_Called_ReturnsStringLengthGreaterThanZero() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetTempFileName_Called_ReturnsStringLengthGreaterThanZero() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetTempFileName(); + //Act + var result = mockPath.GetTempFileName(); - //Assert - await That(result.Length > 0).IsTrue(); - } + //Assert + await That(result.Length > 0).IsTrue(); + } - [Test] - public async Task GetTempFileName_Called_CreatesEmptyFileInTempDirectory() - { - //Arrange - var fileSystem = new MockFileSystem(); - var mockPath = new MockPath(fileSystem); + [Test] + public async Task GetTempFileName_Called_CreatesEmptyFileInTempDirectory() + { + //Arrange + var fileSystem = new MockFileSystem(); + var mockPath = new MockPath(fileSystem); - //Act - var result = mockPath.GetTempFileName(); + //Act + var result = mockPath.GetTempFileName(); - await That(fileSystem.FileExists(result)).IsTrue(); - await That(fileSystem.FileInfo.New(result).Length).IsEqualTo(0); - } + await That(fileSystem.FileExists(result)).IsTrue(); + await That(fileSystem.FileInfo.New(result).Length).IsEqualTo(0); + } - [Test] - public async Task GetTempPath_Called_ReturnsStringLengthGreaterThanZero() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetTempPath_Called_ReturnsStringLengthGreaterThanZero() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetTempPath(); + //Act + var result = mockPath.GetTempPath(); - //Assert - await That(result.Length > 0).IsTrue(); - } + //Assert + await That(result.Length > 0).IsTrue(); + } - [Test] - public async Task GetTempPath_ShouldEndWithDirectorySeparator() - { - //Arrange - var mockPath = new MockFileSystem().Path; - var directorySeparator = mockPath.DirectorySeparatorChar.ToString(); + [Test] + public async Task GetTempPath_ShouldEndWithDirectorySeparator() + { + //Arrange + var mockPath = new MockFileSystem().Path; + var directorySeparator = mockPath.DirectorySeparatorChar.ToString(); - //Act - var result = mockPath.GetTempPath(); + //Act + var result = mockPath.GetTempPath(); - //Assert - await That(result).EndsWith(directorySeparator); - } + //Assert + await That(result).EndsWith(directorySeparator); + } - [Test] - [TestCase(null)] - [TestCase("")] - [TestCase(@"C:\temp")] - public async Task GetTempPath_Called_ReturnsStringLengthGreaterThanZero(string tempDirectory) - { - //Arrange - var mockPath = new MockPath(new MockFileSystem(), string.IsNullOrEmpty(tempDirectory) ? tempDirectory : XFS.Path(tempDirectory)); + [Test] + [TestCase(null)] + [TestCase("")] + [TestCase(@"C:\temp")] + public async Task GetTempPath_Called_ReturnsStringLengthGreaterThanZero(string tempDirectory) + { + //Arrange + var mockPath = new MockPath(new MockFileSystem(), string.IsNullOrEmpty(tempDirectory) ? tempDirectory : XFS.Path(tempDirectory)); - //Act - var result = mockPath.GetTempPath(); + //Act + var result = mockPath.GetTempPath(); - //Assert - await That(result.Length > 0).IsTrue(); - } + //Assert + await That(result.Length > 0).IsTrue(); + } - [Test] - public async Task GetTempPath_Called_WithNonNullVirtualTempDirectory_ReturnsVirtualTempDirectory() - { - //Arrange - var tempDirectory = XFS.Path(@"C:\temp"); + [Test] + public async Task GetTempPath_Called_WithNonNullVirtualTempDirectory_ReturnsVirtualTempDirectory() + { + //Arrange + var tempDirectory = XFS.Path(@"C:\temp"); - var mockPath = new MockPath(new MockFileSystem(), tempDirectory); + var mockPath = new MockPath(new MockFileSystem(), tempDirectory); - //Act - var result = mockPath.GetTempPath(); + //Act + var result = mockPath.GetTempPath(); - //Assert - await That(result).IsEqualTo(tempDirectory); - } + //Assert + await That(result).IsEqualTo(tempDirectory); + } - [Test] - [TestCase(null)] - [TestCase("")] - public async Task GetTempPath_Called_WithNullOrEmptyVirtualTempDirectory_ReturnsFallbackTempDirectory(string tempDirectory) - { - //Arrange - var mockPath = new MockPath(new MockFileSystem(), tempDirectory); + [Test] + [TestCase(null)] + [TestCase("")] + public async Task GetTempPath_Called_WithNullOrEmptyVirtualTempDirectory_ReturnsFallbackTempDirectory(string tempDirectory) + { + //Arrange + var mockPath = new MockPath(new MockFileSystem(), tempDirectory); - //Act - var result = mockPath.GetTempPath(); + //Act + var result = mockPath.GetTempPath(); - //Assert - await That(result.Length > 0).IsTrue(); - } + //Assert + await That(result.Length > 0).IsTrue(); + } - [Test] - public async Task HasExtension_PathSentIn_DeterminesExtension() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task HasExtension_PathSentIn_DeterminesExtension() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.HasExtension(TestPath); + //Act + var result = mockPath.HasExtension(TestPath); - //Assert - await That(result).IsTrue(); - } + //Assert + await That(result).IsTrue(); + } - [Test] - public async Task IsPathRooted_PathSentIn_DeterminesPathExists() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task IsPathRooted_PathSentIn_DeterminesPathExists() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.IsPathRooted(TestPath); + //Act + var result = mockPath.IsPathRooted(TestPath); - //Assert - await That(result).IsTrue(); - } + //Assert + await That(result).IsTrue(); + } #if FEATURE_ADVANCED_PATH_OPERATIONS - [Test] - public async Task IsPathFullyQualified_WithAbsolutePath_ReturnsTrue() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task IsPathFullyQualified_WithAbsolutePath_ReturnsTrue() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.IsPathFullyQualified(XFS.Path("C:\\directory\\file.txt")); + //Act + var result = mockPath.IsPathFullyQualified(XFS.Path("C:\\directory\\file.txt")); - //Assert - await That(result).IsTrue(); - } + //Assert + await That(result).IsTrue(); + } - [Test] - public async Task IsPathFullyQualified_WithRelativePath_ReturnsFalse() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task IsPathFullyQualified_WithRelativePath_ReturnsFalse() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.IsPathRooted(XFS.Path("directory\\file.txt")); + //Act + var result = mockPath.IsPathRooted(XFS.Path("directory\\file.txt")); - //Assert - await That(result).IsFalse(); - } + //Assert + await That(result).IsFalse(); + } - [Test] - public async Task IsPathFullyQualified_WithRelativePathParts_ReturnsFalse() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task IsPathFullyQualified_WithRelativePathParts_ReturnsFalse() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.IsPathRooted(XFS.Path("directory\\..\\file.txt")); + //Act + var result = mockPath.IsPathRooted(XFS.Path("directory\\..\\file.txt")); - //Assert - await That(result).IsFalse(); - } + //Assert + await That(result).IsFalse(); + } - [Test] - public async Task GetRelativePath_Works() - { - //Arrange - var mockPath = new MockPath(new MockFileSystem()); + [Test] + public async Task GetRelativePath_Works() + { + //Arrange + var mockPath = new MockPath(new MockFileSystem()); - //Act - var result = mockPath.GetRelativePath(XFS.Path("c:\\d"), XFS.Path("c:\\d\\e\\f.txt")); + //Act + var result = mockPath.GetRelativePath(XFS.Path("c:\\d"), XFS.Path("c:\\d\\e\\f.txt")); - //Assert - await That(result).IsEqualTo(XFS.Path("e\\f.txt")); - } + //Assert + await That(result).IsEqualTo(XFS.Path("e\\f.txt")); + } - [Test] - public async Task GetRelativePath_WhenPathIsNull_ShouldThrowArgumentNullException() + [Test] + public async Task GetRelativePath_WhenPathIsNull_ShouldThrowArgumentNullException() + { + var mockPath = new MockFileSystem().Path; + + var exception = await That(() => { - var mockPath = new MockFileSystem().Path; + mockPath.GetRelativePath("foo", null); + }).Throws(); - var exception = await That(() => - { - mockPath.GetRelativePath("foo", null); - }).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } - await That(exception.ParamName).IsEqualTo("path"); - } + [Test] + public async Task GetRelativePath_WhenPathIsWhitespace_ShouldThrowArgumentException() + { + var mockPath = new MockFileSystem().Path; - [Test] - public async Task GetRelativePath_WhenPathIsWhitespace_ShouldThrowArgumentException() + var exception = await That(() => { - var mockPath = new MockFileSystem().Path; + mockPath.GetRelativePath("foo", " "); + }).Throws(); - var exception = await That(() => - { - mockPath.GetRelativePath("foo", " "); - }).Throws(); + await That(exception.ParamName).IsEqualTo("path"); + } - await That(exception.ParamName).IsEqualTo("path"); - } + [Test] + public async Task GetRelativePath_WhenRelativeToNull_ShouldThrowArgumentNullException() + { + var mockPath = new MockFileSystem().Path; - [Test] - public async Task GetRelativePath_WhenRelativeToNull_ShouldThrowArgumentNullException() + var exception = await That(() => { - var mockPath = new MockFileSystem().Path; + mockPath.GetRelativePath(null, "foo"); + }).Throws(); - var exception = await That(() => - { - mockPath.GetRelativePath(null, "foo"); - }).Throws(); + await That(exception.ParamName).IsEqualTo("relativeTo"); + } - await That(exception.ParamName).IsEqualTo("relativeTo"); - } + [Test] + public async Task GetRelativePath_WhenRelativeToIsWhitespace_ShouldThrowArgumentException() + { + var mockPath = new MockFileSystem().Path; - [Test] - public async Task GetRelativePath_WhenRelativeToIsWhitespace_ShouldThrowArgumentException() + var exception = await That(() => { - var mockPath = new MockFileSystem().Path; + mockPath.GetRelativePath(" ", "foo"); + }).Throws(); - var exception = await That(() => - { - mockPath.GetRelativePath(" ", "foo"); - }).Throws(); - - await That(exception.ParamName).IsEqualTo("relativeTo"); - } + await That(exception.ParamName).IsEqualTo("relativeTo"); + } #endif #if FEATURE_PATH_EXISTS @@ -633,21 +633,20 @@ public async Task Exists_ExistingFileOrDirectory_ShouldReturnTrue() #endif #if FEATURE_ADVANCED_PATH_OPERATIONS - [Test] - public async Task GetRelativePath_ShouldUseCurrentDirectoryFromMockFileSystem() - { - var fs = new MockFileSystem(); + [Test] + public async Task GetRelativePath_ShouldUseCurrentDirectoryFromMockFileSystem() + { + var fs = new MockFileSystem(); - fs.AddDirectory("input"); - fs.AddDirectory("output"); - fs.Directory.SetCurrentDirectory("input"); + fs.AddDirectory("input"); + fs.AddDirectory("output"); + fs.Directory.SetCurrentDirectory("input"); - fs.AddFile("input/a.txt", "foo"); + fs.AddFile("input/a.txt", "foo"); - var result = fs.Path.GetRelativePath("/input", "a.txt"); + var result = fs.Path.GetRelativePath("/input", "a.txt"); - await That(result).IsEqualTo("a.txt"); - } -#endif + await That(result).IsEqualTo("a.txt"); } -} +#endif +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockUnixSupportTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockUnixSupportTests.cs index 97b5551ad..9f17d8567 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockUnixSupportTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockUnixSupportTests.cs @@ -1,24 +1,23 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests -{ - using XFS = MockUnixSupport; +namespace System.IO.Abstractions.TestingHelpers.Tests; + +using XFS = MockUnixSupport; - [TestFixture] - public class MockUnixSupportTests +[TestFixture] +public class MockUnixSupportTests +{ + [Test] + [UnixOnly(UnixSpecifics.SlashRoot)] + public async Task Should_Convert_Backslashes_To_Slashes_On_Unix() { - [Test] - [UnixOnly(UnixSpecifics.SlashRoot)] - public async Task Should_Convert_Backslashes_To_Slashes_On_Unix() - { - await That(XFS.Path(@"\test\")).IsEqualTo("/test/"); - } + await That(XFS.Path(@"\test\")).IsEqualTo("/test/"); + } - [Test] - [UnixOnly(UnixSpecifics.SlashRoot)] - public async Task Should_Remove_Drive_Letter_On_Unix() - { - await That(XFS.Path(@"c:\test\")).IsEqualTo("/test/"); - } + [Test] + [UnixOnly(UnixSpecifics.SlashRoot)] + public async Task Should_Remove_Drive_Letter_On_Unix() + { + await That(XFS.Path(@"c:\test\")).IsEqualTo("/test/"); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/ProductVersionParserTests.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/ProductVersionParserTests.cs index 4aeeab3c6..967c08498 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/ProductVersionParserTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/ProductVersionParserTests.cs @@ -1,104 +1,103 @@ using NUnit.Framework; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +[TestFixture] +public class ProductVersionParserTests { - [TestFixture] - public class ProductVersionParserTests + [Test] + public async Task ProductVersionParser_Parse_ShouldIgnoreTheSegmentsWhenThereAreMoreThanFiveOfThem() { - [Test] - public async Task ProductVersionParser_Parse_ShouldIgnoreTheSegmentsWhenThereAreMoreThanFiveOfThem() - { - // Arrange - string productVersion = "1.2.3.4.5"; + // Arrange + string productVersion = "1.2.3.4.5"; - // Act - var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); - // Assert - await ThatAll( - That(versionInfo.ProductMajorPart).IsEqualTo(0), - That(versionInfo.ProductMinorPart).IsEqualTo(0), - That(versionInfo.ProductBuildPart).IsEqualTo(0), - That(versionInfo.ProductPrivatePart).IsEqualTo(0) - ); - } + // Assert + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(0), + That(versionInfo.ProductMinorPart).IsEqualTo(0), + That(versionInfo.ProductBuildPart).IsEqualTo(0), + That(versionInfo.ProductPrivatePart).IsEqualTo(0) + ); + } - [Test] - [TestCase("test.2.3.4", 0, 0, 0, 0)] - [TestCase("1.test.3.4", 1, 0, 0, 0)] - [TestCase("1.2.test.4", 1, 2, 0, 0)] - [TestCase("1.2.3.test", 1, 2, 3, 0)] - public async Task ProductVersionParser_Parse_ShouldSkipTheRestOfTheSegmentsWhenOneIsNotValidNumber( - string productVersion, - int expectedMajor, - int expectedMinor, - int expectedBuild, - int expectedRevision) - { - // Act - var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + [Test] + [TestCase("test.2.3.4", 0, 0, 0, 0)] + [TestCase("1.test.3.4", 1, 0, 0, 0)] + [TestCase("1.2.test.4", 1, 2, 0, 0)] + [TestCase("1.2.3.test", 1, 2, 3, 0)] + public async Task ProductVersionParser_Parse_ShouldSkipTheRestOfTheSegmentsWhenOneIsNotValidNumber( + string productVersion, + int expectedMajor, + int expectedMinor, + int expectedBuild, + int expectedRevision) + { + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); - // Assert - await ThatAll( - That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), - That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), - That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), - That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) - ); - } + // Assert + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), + That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), + That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), + That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) + ); + } - [Test] - [TestCase("1-test.2.3.4", 1, 0, 0, 0)] - [TestCase("1-test5.2.3.4", 1, 0, 0, 0)] - [TestCase("1.2-test.3.4", 1, 2, 0, 0)] - [TestCase("1.2-test5.3.4", 1, 2, 0, 0)] - [TestCase("1.2.3-test.4", 1, 2, 3, 0)] - [TestCase("1.2.3-test5.4", 1, 2, 3, 0)] - [TestCase("1.2.3.4-test", 1, 2, 3, 4)] - [TestCase("1.2.3.4-test5", 1, 2, 3, 4)] - public async Task ProductVersionParser_Parse_ShouldSkipTheRestOfTheSegmentsWhenOneContainsMoreThanJustOneNumber( - string productVersion, - int expectedMajor, - int expectedMinor, - int expectedBuild, - int expectedRevision) - { - // Act - var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + [Test] + [TestCase("1-test.2.3.4", 1, 0, 0, 0)] + [TestCase("1-test5.2.3.4", 1, 0, 0, 0)] + [TestCase("1.2-test.3.4", 1, 2, 0, 0)] + [TestCase("1.2-test5.3.4", 1, 2, 0, 0)] + [TestCase("1.2.3-test.4", 1, 2, 3, 0)] + [TestCase("1.2.3-test5.4", 1, 2, 3, 0)] + [TestCase("1.2.3.4-test", 1, 2, 3, 4)] + [TestCase("1.2.3.4-test5", 1, 2, 3, 4)] + public async Task ProductVersionParser_Parse_ShouldSkipTheRestOfTheSegmentsWhenOneContainsMoreThanJustOneNumber( + string productVersion, + int expectedMajor, + int expectedMinor, + int expectedBuild, + int expectedRevision) + { + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); - // Assert + // Assert - await ThatAll( - That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), - That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), - That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), - That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) - ); - } + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), + That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), + That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), + That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) + ); + } - [Test] - [TestCase("", 0, 0, 0, 0)] - [TestCase("1", 1, 0, 0, 0)] - [TestCase("1.2", 1, 2, 0, 0)] - [TestCase("1.2.3", 1, 2, 3, 0)] - [TestCase("1.2.3.4", 1, 2, 3, 4)] - public async Task ProductVersionParser_Parse_ShouldParseEachProvidedSegment( - string productVersion, - int expectedMajor, - int expectedMinor, - int expectedBuild, - int expectedRevision) - { - // Act - var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); + [Test] + [TestCase("", 0, 0, 0, 0)] + [TestCase("1", 1, 0, 0, 0)] + [TestCase("1.2", 1, 2, 0, 0)] + [TestCase("1.2.3", 1, 2, 3, 0)] + [TestCase("1.2.3.4", 1, 2, 3, 4)] + public async Task ProductVersionParser_Parse_ShouldParseEachProvidedSegment( + string productVersion, + int expectedMajor, + int expectedMinor, + int expectedBuild, + int expectedRevision) + { + // Act + var versionInfo = new MockFileVersionInfo("foo", productVersion: productVersion); - // Assert - await ThatAll( - That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), - That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), - That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), - That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) - ); - } + // Assert + await ThatAll( + That(versionInfo.ProductMajorPart).IsEqualTo(expectedMajor), + That(versionInfo.ProductMinorPart).IsEqualTo(expectedMinor), + That(versionInfo.ProductBuildPart).IsEqualTo(expectedBuild), + That(versionInfo.ProductPrivatePart).IsEqualTo(expectedRevision) + ); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Shared.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Shared.cs index 8cadfea01..78b5ce51f 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Shared.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/Shared.cs @@ -1,21 +1,20 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal static class Shared { - internal static class Shared + /// + /// These chars are not valid path chars but do not cause the same + /// errors that other Path.GetInvalidFileNameChars() will. + /// + public static char[] SpecialInvalidPathChars(IFileSystem fileSystem) => new[] { - /// - /// These chars are not valid path chars but do not cause the same - /// errors that other Path.GetInvalidFileNameChars() will. - /// - public static char[] SpecialInvalidPathChars(IFileSystem fileSystem) => new[] - { - // These are not allowed in a file name, but - // inserting them a path does not make it invalid - fileSystem.Path.DirectorySeparatorChar, - fileSystem.Path.AltDirectorySeparatorChar, + // These are not allowed in a file name, but + // inserting them a path does not make it invalid + fileSystem.Path.DirectorySeparatorChar, + fileSystem.Path.AltDirectorySeparatorChar, - // Raises a different type of exception from other - // invalid chars and is covered by other tests - fileSystem.Path.VolumeSeparatorChar - }; - } -} + // Raises a different type of exception from other + // invalid chars and is covered by other tests + fileSystem.Path.VolumeSeparatorChar + }; +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixOnlyAttribute.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixOnlyAttribute.cs index ffe5c2a8c..8b26fc8e7 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixOnlyAttribute.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixOnlyAttribute.cs @@ -1,27 +1,26 @@ using NUnit.Framework; using NUnit.Framework.Interfaces; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal sealed class UnixOnlyAttribute : Attribute, ITestAction { - internal sealed class UnixOnlyAttribute : Attribute, ITestAction - { - private readonly string reason; + private readonly string reason; - public UnixOnlyAttribute(string reason) - { - this.reason = reason; - } + public UnixOnlyAttribute(string reason) + { + this.reason = reason; + } - public ActionTargets Targets => ActionTargets.Test; + public ActionTargets Targets => ActionTargets.Test; - public void BeforeTest(ITest test) + public void BeforeTest(ITest test) + { + if (!MockUnixSupport.IsUnixPlatform()) { - if (!MockUnixSupport.IsUnixPlatform()) - { - Assert.Inconclusive(reason); - } + Assert.Inconclusive(reason); } - - public void AfterTest(ITest test) { } } -} + + public void AfterTest(ITest test) { } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs index bf7cd4f52..24dcf0f59 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/UnixSpecifics.cs @@ -1,9 +1,8 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal static class UnixSpecifics { - internal static class UnixSpecifics - { - public const string SlashRoot = "Filesystem root is just '/' on Unix"; + public const string SlashRoot = "Filesystem root is just '/' on Unix"; - public const string CaseSensitivity = "Paths are case-sensitive on Unix"; - } -} + public const string CaseSensitivity = "Paths are case-sensitive on Unix"; +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsOnlyAttribute.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsOnlyAttribute.cs index 49be416ed..ae7c30b1d 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsOnlyAttribute.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsOnlyAttribute.cs @@ -1,27 +1,26 @@ using NUnit.Framework; using NUnit.Framework.Interfaces; -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal sealed class WindowsOnlyAttribute : Attribute, ITestAction { - internal sealed class WindowsOnlyAttribute : Attribute, ITestAction - { - private readonly string reason; + private readonly string reason; - public WindowsOnlyAttribute(string reason) - { - this.reason = reason; - } + public WindowsOnlyAttribute(string reason) + { + this.reason = reason; + } - public ActionTargets Targets => ActionTargets.Test; + public ActionTargets Targets => ActionTargets.Test; - public void BeforeTest(ITest test) + public void BeforeTest(ITest test) + { + if (!MockUnixSupport.IsWindowsPlatform()) { - if (!MockUnixSupport.IsWindowsPlatform()) - { - Assert.Inconclusive(reason); - } + Assert.Inconclusive(reason); } - - public void AfterTest(ITest test) { } } -} + + public void AfterTest(ITest test) { } +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs index 754d934a8..1dcf4bf59 100644 --- a/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs +++ b/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/WindowsSpecifics.cs @@ -1,15 +1,14 @@ -namespace System.IO.Abstractions.TestingHelpers.Tests +namespace System.IO.Abstractions.TestingHelpers.Tests; + +internal static class WindowsSpecifics { - internal static class WindowsSpecifics - { - public const string Drives = "Drives are a Windows-only concept"; + public const string Drives = "Drives are a Windows-only concept"; - public const string AccessControlLists = "ACLs are a Windows-only concept"; + public const string AccessControlLists = "ACLs are a Windows-only concept"; - public const string UNCPaths = "UNC paths are a Windows-only concept"; + public const string UNCPaths = "UNC paths are a Windows-only concept"; - public const string StrictPathRules = "Windows has stricter path rules than other platforms"; + public const string StrictPathRules = "Windows has stricter path rules than other platforms"; - public const string CaseInsensitivity = "Paths are case-insensitive on Windows"; - } -} + public const string CaseInsensitivity = "Paths are case-insensitive on Windows"; +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoFactoryTests.cs index 6b1b9a7b1..49032ae83 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoFactoryTests.cs @@ -1,16 +1,15 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DirectoryInfoFactoryTests { - [TestFixture] - public class DirectoryInfoFactoryTests + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() { - [Test] - public async Task Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new FileSystem(); + var fileSystem = new FileSystem(); - var result = fileSystem.DirectoryInfo.Wrap(null); + var result = fileSystem.DirectoryInfo.Wrap(null); - await That(result).IsNull(); - } + await That(result).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoTests.cs index ddb90f547..2b7da0833 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryInfoTests.cs @@ -1,18 +1,17 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DirectoryInfoTests { - [TestFixture] - public class DirectoryInfoTests + [Test] + public async Task Parent_ForRootDirectory_ShouldReturnNull() { - [Test] - public async Task Parent_ForRootDirectory_ShouldReturnNull() - { - var wrapperFilesystem = new FileSystem(); + var wrapperFilesystem = new FileSystem(); - var current = wrapperFilesystem.Directory.GetCurrentDirectory(); - var root = wrapperFilesystem.DirectoryInfo.New(current).Root; - var rootsParent = root.Parent; + var current = wrapperFilesystem.Directory.GetCurrentDirectory(); + var root = wrapperFilesystem.DirectoryInfo.New(current).Root; + var rootsParent = root.Parent; - await That(rootsParent).IsNull(); - } + await That(rootsParent).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryWrapperTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryWrapperTests.cs index 2cff9e386..75547515e 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryWrapperTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DirectoryWrapperTests.cs @@ -1,51 +1,50 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DirectoryWrapperTests { - [TestFixture] - public class DirectoryWrapperTests + [Test] + public async Task GetParent_ForRootDirectory_ShouldReturnNull() { - [Test] - public async Task GetParent_ForRootDirectory_ShouldReturnNull() - { - // Arrange - var wrapperFilesystem = new FileSystem(); - var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); - - // Act - var result = wrapperFilesystem.Directory.GetParent(root); - - // Assert - await That(result).IsNull(); - } - - [Test] - public async Task GetParent_ForSimpleSubfolderPath_ShouldReturnRoot() - { - // Arrange - var wrapperFilesystem = new FileSystem(); - var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); - var subfolder = wrapperFilesystem.Path.Combine(root, "some-folder"); - - // Act - var result = wrapperFilesystem.Directory.GetParent(subfolder); - - // Assert - await That(result.FullName).IsEqualTo(root); - } - - [Test] - public async Task GetParent_ForSimpleFilePath_ShouldReturnSubfolder() - { - // Arrange - var wrapperFilesystem = new FileSystem(); - var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); - var subfolder = wrapperFilesystem.Path.Combine(root, "some-folder"); - var file = wrapperFilesystem.Path.Combine(subfolder, "some-file.txt"); - - // Act - var result = wrapperFilesystem.Directory.GetParent(file); - - // Assert - await That(result.FullName).IsEqualTo(subfolder); - } + // Arrange + var wrapperFilesystem = new FileSystem(); + var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); + + // Act + var result = wrapperFilesystem.Directory.GetParent(root); + + // Assert + await That(result).IsNull(); + } + + [Test] + public async Task GetParent_ForSimpleSubfolderPath_ShouldReturnRoot() + { + // Arrange + var wrapperFilesystem = new FileSystem(); + var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); + var subfolder = wrapperFilesystem.Path.Combine(root, "some-folder"); + + // Act + var result = wrapperFilesystem.Directory.GetParent(subfolder); + + // Assert + await That(result.FullName).IsEqualTo(root); + } + + [Test] + public async Task GetParent_ForSimpleFilePath_ShouldReturnSubfolder() + { + // Arrange + var wrapperFilesystem = new FileSystem(); + var root = wrapperFilesystem.Directory.GetDirectoryRoot("."); + var subfolder = wrapperFilesystem.Path.Combine(root, "some-folder"); + var file = wrapperFilesystem.Path.Combine(subfolder, "some-file.txt"); + + // Act + var result = wrapperFilesystem.Directory.GetParent(file); + + // Assert + await That(result.FullName).IsEqualTo(subfolder); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DriveInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DriveInfoFactoryTests.cs index f96f183ab..23819e141 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DriveInfoFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/DriveInfoFactoryTests.cs @@ -1,16 +1,15 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class DriveInfoFactoryTests { - [TestFixture] - public class DriveInfoFactoryTests + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() { - [Test] - public async Task Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new FileSystem(); + var fileSystem = new FileSystem(); - var result = fileSystem.DriveInfo.Wrap(null); + var result = fileSystem.DriveInfo.Wrap(null); - await That(result).IsNull(); - } + await That(result).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoBaseConversionTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoBaseConversionTests.cs index 6a9da572a..ad00fda81 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoBaseConversionTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoBaseConversionTests.cs @@ -1,24 +1,23 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +/// +/// Unit tests for the conversion operators of the class. +/// +public class FileInfoBaseConversionTests { /// - /// Unit tests for the conversion operators of the class. + /// Tests that a null is correctly converted to a null without exception. /// - public class FileInfoBaseConversionTests + [Test] + public async Task FileInfoBase_FromFileInfo_ShouldReturnNullIfFileInfoIsNull() { - /// - /// Tests that a null is correctly converted to a null without exception. - /// - [Test] - public async Task FileInfoBase_FromFileInfo_ShouldReturnNullIfFileInfoIsNull() - { - // Arrange - FileInfo fileInfo = null; + // Arrange + FileInfo fileInfo = null; - // Act - FileInfoBase actual = fileInfo; + // Act + FileInfoBase actual = fileInfo; - // Assert - await That(actual).IsNull(); - } + // Assert + await That(actual).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoFactoryTests.cs index a6d41e4a2..26c849685 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileInfoFactoryTests.cs @@ -1,16 +1,15 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class FileInfoFactoryTests { - [TestFixture] - public class FileInfoFactoryTests + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() { - [Test] - public async Task Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new FileSystem(); + var fileSystem = new FileSystem(); - var result = fileSystem.FileInfo.Wrap(null); + var result = fileSystem.FileInfo.Wrap(null); - await That(result).IsNull(); - } + await That(result).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemTests.cs index 88fe586fc..c862af110 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemTests.cs @@ -1,104 +1,103 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class FileSystemTests { - [TestFixture] - public class FileSystemTests - { #if !NET9_0_OR_GREATER - [Test] - public async Task Is_Serializable() - { - var fileSystem = new FileSystem(); - var memoryStream = new MemoryStream(); + [Test] + public async Task Is_Serializable() + { + var fileSystem = new FileSystem(); + var memoryStream = new MemoryStream(); #pragma warning disable SYSLIB0011 - var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); - serializer.Serialize(memoryStream, fileSystem); + serializer.Serialize(memoryStream, fileSystem); #pragma warning restore SYSLIB0011 - await That(memoryStream).HasLength().GreaterThan(0) - .Because("Length didn't increase after serialization task."); - } + await That(memoryStream).HasLength().GreaterThan(0) + .Because("Length didn't increase after serialization task."); + } #endif - [Test] - public async Task Mock_File_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.File.ToString()).Returns("") - ).DoesNotThrow(); - } - - [Test] - public async Task Mock_Directory_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.Directory.ToString()).Returns("") - ).DoesNotThrow(); - } - - [Test] - public async Task Mock_FileInfo_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.FileInfo.ToString()).Returns("") - ).DoesNotThrow(); - } - - [Test] - public async Task Mock_FileStream_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.FileStream.ToString()).Returns("") - ).DoesNotThrow(); - } - - [Test] - public async Task Mock_Path_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.Path.ToString()).Returns("") - ).DoesNotThrow(); - } - - [Test] - public async Task Mock_DirectoryInfo_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.DirectoryInfo.ToString()).Returns("") - ).DoesNotThrow(); - } - - [Test] - public async Task Mock_DriveInfo_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.DirectoryInfo.ToString()).Returns("") - ).DoesNotThrow(); - } - - [Test] - public async Task Mock_FileSystemWatcher_Succeeds() - { - var fileSystemMock = new Moq.Mock(); - - await That(() => - fileSystemMock.Setup(x => x.FileSystemWatcher.ToString()).Returns("") - ).DoesNotThrow(); - } + [Test] + public async Task Mock_File_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.File.ToString()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_Directory_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.Directory.ToString()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_FileInfo_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.FileInfo.ToString()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_FileStream_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.FileStream.ToString()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_Path_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.Path.ToString()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_DirectoryInfo_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.DirectoryInfo.ToString()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_DriveInfo_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.DirectoryInfo.ToString()).Returns("") + ).DoesNotThrow(); + } + + [Test] + public async Task Mock_FileSystemWatcher_Succeeds() + { + var fileSystemMock = new Moq.Mock(); + + await That(() => + fileSystemMock.Setup(x => x.FileSystemWatcher.ToString()).Returns("") + ).DoesNotThrow(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemWatcherFactoryTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemWatcherFactoryTests.cs index bf697dd85..4762aa35d 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemWatcherFactoryTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileSystemWatcherFactoryTests.cs @@ -1,16 +1,15 @@ -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +[TestFixture] +public class FileSystemWatcherFactoryTests { - [TestFixture] - public class FileSystemWatcherFactoryTests + [Test] + public async Task Wrap_WithNull_ShouldReturnNull() { - [Test] - public async Task Wrap_WithNull_ShouldReturnNull() - { - var fileSystem = new FileSystem(); + var fileSystem = new FileSystem(); - var result = fileSystem.FileSystemWatcher.Wrap(null); + var result = fileSystem.FileSystemWatcher.Wrap(null); - await That(result).IsNull(); - } + await That(result).IsNull(); } -} +} \ No newline at end of file diff --git a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileVersionInfoBaseConversionTests.cs b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileVersionInfoBaseConversionTests.cs index 77f6429ea..f1d436e1b 100644 --- a/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileVersionInfoBaseConversionTests.cs +++ b/tests/TestableIO.System.IO.Abstractions.Wrappers.Tests/FileVersionInfoBaseConversionTests.cs @@ -1,26 +1,25 @@ using System.Diagnostics; -namespace System.IO.Abstractions.Tests +namespace System.IO.Abstractions.Tests; + +/// +/// Unit tests for the conversion operators of the class. +/// +public class FileVersionInfoBaseConversionTests { /// - /// Unit tests for the conversion operators of the class. + /// Tests that a null is correctly converted to a null without exception. /// - public class FileVersionInfoBaseConversionTests + [Test] + public async Task FileVersionInfoBase_FromFileVersionInfo_ShouldReturnNullIfFileVersionInfoIsNull() { - /// - /// Tests that a null is correctly converted to a null without exception. - /// - [Test] - public async Task FileVersionInfoBase_FromFileVersionInfo_ShouldReturnNullIfFileVersionInfoIsNull() - { - // Arrange - FileVersionInfo fileVersionInfo = null; + // Arrange + FileVersionInfo fileVersionInfo = null; - // Act - FileVersionInfoBase actual = fileVersionInfo; + // Act + FileVersionInfoBase actual = fileVersionInfo; - // Assert - await That(actual).IsNull(); - } + // Assert + await That(actual).IsNull(); } -} +} \ No newline at end of file