public static string TrimSlashes(this string path) { if (string.IsNullOrEmpty(path)) { return(path); } var trimmed = path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); if (XFS.IsUnixPlatform() && (path[0] == Path.DirectorySeparatorChar || path[0] == Path.AltDirectorySeparatorChar) && trimmed == "") { return(Path.DirectorySeparatorChar.ToString()); } if (XFS.IsWindowsPlatform() && trimmed.Length == 2 && char.IsLetter(trimmed[0]) && trimmed[1] == ':') { return(trimmed + Path.DirectorySeparatorChar); } return(trimmed); }
public MockFileSystem(IDictionary <string, MockFileData> files, string currentDirectory = "") { if (string.IsNullOrEmpty(currentDirectory)) { currentDirectory = XFS.Path(DEFAULT_CURRENT_DIRECTORY); } StringOperations = new StringOperations(XFS.IsUnixPlatform()); pathVerifier = new PathVerifier(this); this.files = new Dictionary <string, MockFileData>(StringOperations.Comparer); Path = new MockPath(this); File = new MockFile(this); Directory = new MockDirectory(this, currentDirectory); FileInfo = new MockFileInfoFactory(this); FileStream = new MockFileStreamFactory(this); DirectoryInfo = new MockDirectoryInfoFactory(this); DriveInfo = new MockDriveInfoFactory(this); FileSystemWatcher = new MockFileSystemWatcherFactory(); if (files != null) { foreach (var entry in files) { AddFile(entry.Key, entry.Value); } } if (!FileExists(currentDirectory)) { AddDirectory(currentDirectory); } }
private string[] GetFilesInternal(IEnumerable <string> files, string path, string searchPattern, SearchOption searchOption) { path = EnsurePathEndsWithDirectorySeparator(path); path = mockFileDataAccessor.Path.GetFullPath(path); bool isUnix = XFS.IsUnixPlatform(); string allDirectoriesPattern = isUnix ? @"([^<>:""/|?*]*/)*" : @"([^<>:""/\\|?*]*\\)*"; var fileNamePattern = searchPattern == "*" ? isUnix ? @"[^/]*?/?" : @"[^\\]*?\\?" : Regex.Escape(searchPattern) .Replace(@"\*", isUnix ? @"[^<>:""/|?*]*?" : @"[^<>:""/\\|?*]*?") .Replace(@"\?", isUnix ? @"[^<>:""/|?*]?" : @"[^<>:""/\\|?*]?"); 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); return(files .Where(p => Regex.IsMatch(p, pathPattern)) .ToArray()); }
private string[] GetFilesInternal(IEnumerable <string> files, string path, string searchPattern, SearchOption searchOption) { CheckSearchPattern(searchPattern); path = EnsurePathEndsWithDirectorySeparator(path); path = _mockFileDataAccessor.Path.GetFullPath(path); bool isUnix = XFS.IsUnixPlatform(); string allDirectoriesPattern = isUnix ? @"([^<>:""/|?*]*/)*" : @"([^<>:""/\\|?*]*\\)*"; string fileNamePattern; string pathPatternSpecial = null; if (searchPattern == "*") { fileNamePattern = isUnix ? @"[^/]*?/?" : @"[^\\]*?\\?"; } else { fileNamePattern = Regex.Escape(searchPattern) .Replace(@"\*", isUnix ? @"[^<>:""/|?*]*?" : @"[^<>:""/\\|?*]*?") .Replace(@"\?", isUnix ? @"[^<>:""/|?*]?" : @"[^<>:""/\\|?*]?"); string extension = Path.GetExtension(searchPattern); bool hasExtensionLengthOfThree = extension.Length == 4 && !extension.Contains("*") && !extension.Contains("?"); if (hasExtensionLengthOfThree) { string fileNamePatternSpecial = $"{fileNamePattern}[^.]"; pathPatternSpecial = isUnix ? $@"(?i:^{Regex.Escape(path)}{(searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty)}{fileNamePatternSpecial}(?:/?)$)" : $@"(?i:^{Regex.Escape(path)}{(searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty)}{fileNamePatternSpecial}(?:\\?)$)"; } } string pathPattern = isUnix ? $@"(?i:^{Regex.Escape(path)}{(searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty)}{fileNamePattern}(?:/?)$)" : $@"(?i:^{Regex.Escape(path)}{(searchOption == SearchOption.AllDirectories ? allDirectoriesPattern : string.Empty)}{fileNamePattern}(?:\\?)$)"; return(files .Where(p => { if (Regex.IsMatch(p, pathPattern)) { return true; } if (pathPatternSpecial != null && Regex.IsMatch(p, pathPatternSpecial)) { return true; } return false; }) .ToArray()); }
public override IDirectoryInfo GetParent(string path) { if (path == null) { 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 (mockFileDataAccessor.PathVerifier.HasIllegalCharacters(path, false)) { throw new ArgumentException("Path contains invalid path characters.", "path"); } var absolutePath = mockFileDataAccessor.Path.GetFullPath(path); var sepAsString = mockFileDataAccessor.Path.DirectorySeparatorChar.ToString(); var lastIndex = 0; if (absolutePath != sepAsString) { var startIndex = mockFileDataAccessor.StringOperations.EndsWith(absolutePath, sepAsString) ? absolutePath.Length - 1 : absolutePath.Length; lastIndex = absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar, startIndex - 1); if (lastIndex < 0) { return(null); } } 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(); if (absolutePath.Length > 1 && absolutePath.LastIndexOf(mockFileDataAccessor.Path.DirectorySeparatorChar) == 0) { return(new MockDirectoryInfo(mockFileDataAccessor, mockFileDataAccessor.Path.DirectorySeparatorChar.ToString())); } } return(null); } return(new MockDirectoryInfo(mockFileDataAccessor, parentPath)); }
public void MockDirectory_GetParent_ShouldThrowArgumentExceptionIfPathHasIllegalCharacters() { if (XFS.IsUnixPlatform()) { Assert.True(true, "Path.GetInvalidChars() does not return anything on Mono"); } // Arrange MockFileSystem fileSystem = new MockFileSystem(); // Act Action act = () => fileSystem.Directory.GetParent(XFS.Path("c:\\director\ty\\has\\illegal\\character")); // Assert Assert.Throws <ArgumentException>(act); }
public override bool Exists(string path) { if (path == "/" && XFS.IsUnixPlatform()) { return(true); } try { path = path.TrimSlashes(); path = mockFileDataAccessor.Path.GetFullPath(path); return(mockFileDataAccessor.AllDirectories.Any(p => p.Equals(path, StringComparison.OrdinalIgnoreCase))); } catch (Exception) { return(false); } }
public void MockDriveInfo_Constructor_ShouldInitializeLocalWindowsDrives_SpecialForWindows() { if (XFS.IsUnixPlatform()) { Assert.Inconclusive("Using XFS.Path transform c into c:."); } // Arrange var fileSystem = new MockFileSystem(); fileSystem.AddDirectory(XFS.Path(@"c:\Test")); // Act var driveInfo = new MockDriveInfo(fileSystem, "c"); // Assert Assert.AreEqual(@"C:\", driveInfo.Name); }
public override bool Exists(string path) { if (path == "/" && XFS.IsUnixPlatform()) { return(true); } try { path = path.TrimSlashes(); path = mockFileDataAccessor.Path.GetFullPath(path); return(mockFileDataAccessor.AllDirectories.Any(p => mockFileDataAccessor.StringOperations.Equals(p, path))); } catch (Exception) { return(false); } }
public MockFileSystem(IDictionary <string, MockFileData> files, string 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)); } var defaultTempDirectory = XFS.Path(TEMP_DIRECTORY); StringOperations = new StringOperations(XFS.IsUnixPlatform()); pathVerifier = new PathVerifier(this); this.files = new Dictionary <string, MockFileData>(StringOperations.Comparer); Path = new MockPath(this, defaultTempDirectory); File = new MockFile(this); Directory = new MockDirectory(this, currentDirectory); FileInfo = new MockFileInfoFactory(this); FileStream = new MockFileStreamFactory(this); DirectoryInfo = new MockDirectoryInfoFactory(this); DriveInfo = new MockDriveInfoFactory(this); FileSystemWatcher = new MockFileSystemWatcherFactory(); if (files != null) { foreach (var entry in files) { AddFile(entry.Key, entry.Value); } } if (!FileExists(currentDirectory)) { AddDirectory(currentDirectory); } if (!FileExists(defaultTempDirectory)) { AddDirectory(defaultTempDirectory); } }
public void MockFile_Copy_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidChars_Message() { if (XFS.IsUnixPlatform()) { Assert.True(true, "Path.GetInvalidChars() does not return anything on Mono"); } var destFilePath = XFS.Path(@"c:\something\demo.txt"); var fileSystem = new MockFileSystem(); foreach (var invalidChar in fileSystem.Path.GetInvalidPathChars()) { var sourceFilePath = XFS.Path(@"c:\some" + invalidChar + @"thing\demo.txt"); var exception = Assert.Throws <ArgumentException>(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); exception.Message.Should().Be("Illegal characters in path.", string.Format("Testing char: [{0:c}] \\{1:X4}", invalidChar, (int)invalidChar)); } }
public void MockFile_Copy_ShouldThrowNotSupportedExceptionWhenTargetFileNameContainsInvalidChars_Message() { if (XFS.IsUnixPlatform()) { Assert.True(true, "Path.GetInvalidChars() does not return anything on Mono"); } string sourceFilePath = XFS.Path(@"c:\something\demo.txt"); MockFileSystem fileSystem = new MockFileSystem(); foreach (char invalidChar in fileSystem.Path.GetInvalidFileNameChars().Where(x => x != fileSystem.Path.DirectorySeparatorChar)) { string destFilePath = XFS.Path(@"c:\something\demo.txt") + invalidChar; ArgumentException exception = Assert.Throws <ArgumentException>(() => fileSystem.File.Copy(sourceFilePath, destFilePath)); Assert.Equal(exception.Message, "Illegal characters in path."); } }
public void MockFile_Move_ShouldThrowNotSupportedExceptionWhenSourcePathContainsInvalidChars_Message() { if (XFS.IsUnixPlatform()) { Assert.True(true, "Path.GetInvalidChars() does not return anything on Mono"); } string destFilePath = XFS.Path(@"c:\something\demo.txt"); MockFileSystem fileSystem = new MockFileSystem(); foreach (char invalidChar in fileSystem.Path.GetInvalidPathChars()) { string sourceFilePath = XFS.Path(@"c:\some" + invalidChar + @"thing\demo.txt"); ArgumentException exception = Assert.Throws <ArgumentException>(() => fileSystem.File.Move(sourceFilePath, destFilePath)); Assert.Equal(exception.Message, "Illegal characters in path."); } }
public void MockDirectory_GetLogicalDrives_Returns_LogicalDrives() { var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { XFS.Path(@"c:\foo\bar\"), new MockDirectoryData() }, { XFS.Path(@"c:\foo\baz\"), new MockDirectoryData() }, { XFS.Path(@"d:\bash\"), new MockDirectoryData() }, }); var drives = fileSystem.Directory.GetLogicalDrives(); if (XFS.IsUnixPlatform()) { Assert.AreEqual(1, drives.Length); Assert.IsTrue(drives.Contains("/")); } else { Assert.AreEqual(2, drives.Length); Assert.IsTrue(drives.Contains("c:\\")); Assert.IsTrue(drives.Contains("d:\\")); } }
public void MockFile_AppendAllText_ShouldPersistNewTextWithCustomEncoding() { // Arrange string path = XFS.Path(@"c:\something\demo.txt"); MockFileSystem fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { path, new MockFileData("Demo text content") } }); MockFile file = new MockFile(fileSystem); // Act file.AppendAllText(path, "+ some text", Encoding.BigEndianUnicode); // Assert byte[] 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 }; if (XFS.IsUnixPlatform()) { // Remove EOF on mono expected = new byte[] { 68, 101, 109, 111, 32, 116, 101, 120, 116, 32, 99, 111, 110, 116, 101, 110, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101, 0, 32, 0, 116, 0, 101, 0, 120, 0, 116 }; } Assert.Equal( expected, file.ReadAllBytes(path)); }
private string[] GetFilesInternal(IEnumerable <string> files, string path, string searchPattern, SearchOption searchOption) { CheckSearchPattern(searchPattern); path = EnsurePathEndsWithDirectorySeparator(path); bool isUnix = XFS.IsUnixPlatform(); string allDirectoriesPattern = isUnix ? @"([^<>:""/|?*]*/)*" : @"([^<>:""/\\|?*]*\\)*"; string fileNamePattern; string pathPatternSpecial = null; 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); } } 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); return(files .Where(p => { if (Regex.IsMatch(p, pathPattern)) { return true; } if (pathPatternSpecial != null && Regex.IsMatch(p, pathPatternSpecial)) { return true; } return false; }) .ToArray()); }
private string[] GetFilesInternal( IEnumerable <string> files, string path, string searchPattern, SearchOption searchOption) { 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)); } CheckSearchPattern(searchPattern); path = path.TrimSlashes(); path = path.NormalizeSlashes(); if (!Exists(path)) { throw CommonExceptions.CouldNotFindPartOfPath(path); } path = EnsureAbsolutePath(path); if (!path.EndsWith(Path.DirectorySeparatorChar.ToString())) { path += Path.DirectorySeparatorChar; } var isUnix = XFS.IsUnixPlatform(); var allDirectoriesPattern = isUnix ? @"([^<>:""/|?*]*/)*" : @"([^<>:""/\\|?*]*\\)*"; string fileNamePattern; string pathPatternSpecial = null; 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); } } 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); return(files .Where(p => Regex.IsMatch(p, pathPattern) || (pathPatternSpecial != null && Regex.IsMatch(p, pathPatternSpecial))) .ToArray()); }