Exemple #1
0
        public void SetUp()
        {
            fileSystem = new MockFileSystem();
            var rnd      = new Random();
            var rndBytes = new byte[2048];

            rnd.NextBytes(rndBytes);
            var rndBytesFile = new MockFileData(rndBytes);

            fileSystem.AddDirectory(@"C:\Archive");
            fileSystem.AddFile(@"C:\source1\file.bin", rndBytesFile);
            fileSystem.AddFile(@"C:\source1\1\file2.bin", rndBytesFile);
            fileSystem.AddFile(@"C:\source1\2\file3.bin", rndBytesFile);
            fileSystem.AddFile(@"C:\source2\1\1\file4.bin", rndBytesFile);
            fileSystem.AddDirectory(@"C:\source3");
        }
        public void ItCanLoadLocalRepositoryWithTemplates()
        {
            var logger     = NullLogger <RepositoryLoader> .Instance;
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory("/opt/stamp/repos/.local/templates/TestTemplate@1");

            var stampConfig = Mock.Of <IStampConfig>(config =>
                                                     config.GetLocalRepositoryPath() == PurePath.Create("/opt/stamp/repos/.local")
                                                     );

            var expectedTemplateName    = "TestTemplate";
            var expectedTemplateVersion = SemVersion.Parse("1.0.0");
            var templateLoader          = Mock.Of <ITemplateLoader>(loader =>
                                                                    loader.LoadFromTemplateDirectory(It.IsAny <IPurePath>()) == Mock.Of <ITemplate>(template =>
                                                                                                                                                    template.Name == expectedTemplateName &&
                                                                                                                                                    template.Version == expectedTemplateVersion
                                                                                                                                                    )
                                                                    );

            var repositoryLoader = new RepositoryLoader(fileSystem, templateLoader, stampConfig, logger);
            var repository       = repositoryLoader.LoadLocalRepository();

            repository.Should().NotBeNull();
            repository.Name.Should().Be(".local");
            repository.Description.Should().Be("Local repository");
            repository.Templates.Count.Should().Be(1);
            repository.Templates[0].Name.Should().Be(expectedTemplateName);
            repository.Templates[0].Version.Should().Be(expectedTemplateVersion);
        }
            public static IEnumerable ForDifferentEncoding()
            {
                var fileSystem = new MockFileSystem();

                fileSystem.AddDirectory(@"c:\something");
                var fileContentEnumerable = new List <string> {
                    "first line", "second line", "third line", "fourth and last line"
                };
                var    fileContentArray      = fileContentEnumerable.ToArray();
                Action writeEnumberable      = () => fileSystem.File.WriteAllLines(Path, fileContentEnumerable);
                Action writeEnumberableUtf32 = () => 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 object[] { fileSystem, writeEnumberable, expectedContent, "WriteAllLines(string, IEnumerable<string>)" });

                yield return
                    (new object[]
                {
                    fileSystem, writeEnumberableUtf32, expectedContent,
                    "WriteAllLines(string, IEnumerable<string>, Encoding.UTF32)"
                });

                // string[]
                yield return(new object[] { fileSystem, writeArray, expectedContent, "WriteAllLines(string, string[])" });

                yield return
                    (new object[] { fileSystem, writeArrayUtf32, expectedContent, "WriteAllLines(string, string[], Encoding.UTF32)" });
            }
Exemple #4
0
        private static MockFileSystem CreateEmptyMockFileSystem()
        {
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>(), "c:\\Test");

            fileSystem.AddDirectory("Test");
            return(fileSystem);
        }
        public void MakeSecondLineUpperCase()
        {
            // Create a mock input file
            var mockInputFile = new MockFileData("Line 1\nLine 2\nLine 3");

            // Setup mock file system starting state
            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddFile(@"c:\root\in\myfile.txt", mockInputFile);
            mockFileSystem.AddDirectory(@"c:\root\out");

            // Create TextFileProcessor with mock file system
            var sut = new TextFileProcessor(@"c:\root\in\myfile.txt",
                                            @"c:\root\out\myfile.txt",
                                            mockFileSystem);

            // Process test file
            sut.Process();

            // Check mock file system for output file
            Assert.True(mockFileSystem.FileExists(@"c:\root\out\myfile.txt"));

            // Check content of output file in mock file system
            MockFileData processedFile = mockFileSystem.GetFile(@"c:\root\out\myfile.txt");

            string[] lines = processedFile.TextContents.SplitLines();

            Assert.Equal("Line 1", lines[0]);
            Assert.Equal("LINE 2", lines[1]);
            Assert.Equal("Line 3", lines[2]);
        }
            public static IEnumerable ForContentsIsNull()
            {
                var fileSystem   = new MockFileSystem();
                var path         = XFS.Path(@"c:\something\file.txt");
                var mockFileData = new MockFileData(string.Empty);

                mockFileData.Attributes = FileAttributes.ReadOnly;
                fileSystem.AddDirectory(@"c:\something");
                fileSystem.AddFile(path, mockFileData);
                List <string> fileContentEnumerable = null;

                string[] fileContentArray = null;

                // ReSharper disable ExpressionIsAlwaysNull
                Action writeEnumberable      = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable);
                Action writeEnumberableUtf32 = () => 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 object[] { writeEnumberable, "WriteAllLines(string, IEnumerable<string>)" });

                yield return(new object[] { writeEnumberableUtf32, "WriteAllLines(string, IEnumerable<string>, Encoding.UTF32)" });

                // string[]
                yield return(new object[] { writeArray, "WriteAllLines(string, string[])" });

                yield return(new object[] { writeArrayUtf32, "WriteAllLines(string, string[], Encoding.UTF32)" });
            }
        public void WriteBackupFile_WritesBackupFile_EveryoneIsHappy(
            [Frozen] IMainModel model,
            string fileContent)
        {
            var directory     = @"C:\Temp\";
            var fileName      = "temp";
            var fileExtension = ".txt";
            var filePath      = directory + fileName + fileExtension;

            var mockedFileSystem  = new MockFileSystem();
            var mockedFileContent = new MockFileData(fileContent);

            mockedFileSystem.AddDirectory(directory);
            mockedFileSystem.AddFile(filePath, mockedFileContent);

            model.FileName = filePath;

            var sut = new BackupService(model, mockedFileSystem);

            sut.WriteBackupFile();

            var expectedPath = $"{directory}{fileName}_backup_{DateTime.Now:yyyyMMddHHmmss}{fileExtension}";

            mockedFileSystem.FileExists(expectedPath).Should().BeTrue();
        }
Exemple #8
0
        public void CopyFilesWhenIndicated(bool shouldInitialize)
        {
            var initializationDeterminer = new MockLevelInitializationDeterminer(shouldInitialize);

            var copyDir = new MockCopyDir();

            var levelId           = "level";
            var levelToInitialize = new Level(id: levelId, folderFilepath: ".");
            var levelsProvider    = new FakeLevelsProvider(new[] { levelToInitialize });
            var mockFileSystem    = new MockFileSystem();

            mockFileSystem.AddDirectory(levelToInitialize.GetMasterFolder()); //will throw error if no master folder

            var masterFolderLevelInitializer = new MasterFolderLevelInitializer(initializationDeterminer,
                                                                                copyDir,
                                                                                levelsProvider,
                                                                                mockFileSystem.Path);

            var someUser = "******";

            masterFolderLevelInitializer.InitializeIfNecessary(levelId, someUser);

            Assert.Equal(shouldInitialize, copyDir.DidCopy);
            Assert.Equal(shouldInitialize, initializationDeterminer.IsMarkedAsInitialized);
        }
        public void AddLargestNumber()
        {
            //Assert
            var mockInputFile =
                new MockFileData(new byte[] { 0xFF, 0x34, 0x56, 0xD2 });
            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddFile(@"a:\root\in\myfile.data", mockInputFile);
            mockFileSystem.AddDirectory(@"a:\root\out");

            var sut = new BinaryFileProcessor(
                @"a:\root\in\myfile.data",
                @"a:\root\out\myfile.data", mockFileSystem);

            //act
            sut.Process();

            //Assert
            Assert.True(mockFileSystem.FileExists(@"a:\root\out\myfile.data"));

            var processedFile = mockFileSystem.GetFile(@"a:\root\out\myfile.data");
            var data          = processedFile.Contents;

            Assert.Equal(5, data.Length);
            Assert.Equal(0xFF, data[4]);
        }
        public void Mockfile_Create_OverwritesExistingFile()
        {
            string path       = XFS.Path(@"c:\some\file.txt");
            var    fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(XFS.Path(@"c:\some"));

            var mockFile = new MockFile(fileSystem);

            // Create a file
            using (var stream = mockFile.Create(path))
            {
                var contents = new UTF8Encoding(false).GetBytes("Test 1");
                stream.Write(contents, 0, contents.Length);
            }

            // 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);
            }

            var actualContents = fileSystem.GetFile(path).Contents;

            Assert.That(actualContents, Is.EqualTo(expectedContents));
        }
Exemple #11
0
        public void TestNoSettingsFileReloadTouchSaveCycle(string SettingName, string SettingValue, string SettingSerializeAs)
        {
            string referenceConfigFileContent = Helpers.GenerateFileContent(new List <Tuple <string, string, string> > {
                new Tuple <string, string, string>(SettingName, SettingValue, SettingSerializeAs)
            }, typeof(TestSettingsAllValid));
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory("c:\\");
            StaticMockFileSystem.MockFileSystem = fileSystem;
            TestSettingsAllValid.Default.Reload();
            if (SettingName == "StringSetting")
            {
                TestSettingsAllValid.Default.StringSetting = TestSettingsAllValid.Default.StringSetting;
            }
            if (SettingName == "BinarySetting")
            {
                TestSettingsAllValid.Default.BinarySetting = TestSettingsAllValid.Default.BinarySetting;
            }
            if (SettingName == "XmlSetting")
            {
                TestSettingsAllValid.Default.XmlSetting = TestSettingsAllValid.Default.XmlSetting;
            }
            TestSettingsAllValid.Default.Save();
            var result = StaticMockFileSystem.MockFileSystem.File.ReadAllText(Consts.SettingsPath);

            Assert.AreEqual(Helpers.GetCanonicalXml(referenceConfigFileContent), Helpers.GetCanonicalXml(result));
            StaticMockFileSystem.MockFileSystem = null;
        }
        public async Task CanImportPackageWithFiles()
        {
            var          writer       = new MockTextWriter();
            var          settings     = Substitute.For <IChauffeurSettings>();
            const string siteRootPath = "C:\\SiteRoot";

            settings.TryGetSiteRootDirectory(out string dir).Returns(x =>
            {
                x[0] = siteRootPath;
                return(true);
            });
            var fs = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { "C:\\Path\\Text.xml", new MockFileData(filesXml) },
                { "C:\\Path\\foo.txt", new MockFileData("something") }
            });

            fs.AddDirectory(siteRootPath);

            var package = new PackageDeliverable(null, writer, fs, settings, null, null, null);

            await package.Run(null, new[] { "Text", "-f:C:\\Path" });

            Assert.Collection(
                fs.Directory.GetFiles(siteRootPath),
                item => Assert.Equal("foo.txt", fs.Path.GetFileName(item))
                );
        }
Exemple #13
0
        public void InitializeBase()
        {
            FileSystem        = new MockFileSystem();
            TestDirectoryName = @"C:\ProgramFiles";
            TestFileName      = $@"{TestDirectoryName}\text.txt";

            FileSystem.AddDirectory(TestDirectoryName);

            JsonOperations    = new Library.JsonOperations();
            Configuration     = new Library.Configuration(FileSystem);
            LockFinder        = new Library.LockFinder(FileSystem, Configuration);
            LockReader        = new Library.LockReader(FileSystem, LockFinder, JsonOperations);
            LockBuilder       = new Library.LockBuilder(Configuration);
            LockWriter        = new Library.LockWriter(FileSystem, JsonOperations, LockBuilder);
            Communicator      = new ListCommunicator();
            Unlocker          = new Library.Unlocker(FileSystem, LockReader, LockBuilder);
            Launcher          = new Launcher();
            LaunchLockProcess =
                new Library.LaunchLockProcess(
                    Configuration,
                    LockFinder,
                    LockReader,
                    LockBuilder,
                    LockWriter,
                    Communicator,
                    FileSystem,
                    Unlocker,
                    Launcher);

            Intialize();
        }
        public async Task RescanLocationAsync_RemovesScannedFilesNotFoundInDiretory()
        {
            // ARRANGE
            MockFileSystem fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(@"C:\foobar");
            Mock <IFileHashService>      service          = new Mock <IFileHashService>();
            ScannedFileStore             scannedFileStore = new ScannedFileStore(fileSystem, service.Object);
            MockScannedFileStoreProgress progress         = new MockScannedFileStoreProgress();
            List <string> locations = new List <string>()
            {
                @"C:\foobar"
            };

            service.Setup(t => t.ListScannedFilePathsAsync(It.IsAny <List <string> >())).ReturnsAsync((List <string> locs) =>
            {
                return(new List <string>()
                {
                    @"C:\foobar\foo.bar"
                });
            });

            // ACT
            await scannedFileStore.RescanLocationsAsync(locations, progress);

            // ASSERT
            service.Verify(t => t.RemoveScannedFilesByFilePathAsync(It.Is <string>(s => s.Equals(@"C:\foobar\foo.bar"))));
        }
        public void AddLargestNumber()
        {
            const string inputDir      = @"d:\root\in";
            const string inputFileName = @"myfile.csv";
            var          inputFilePath = Path.Combine(inputDir, inputFileName);

            const string outputDir      = @"d:\root\out";
            const string outputFileName = @"myfileout.csv";
            var          outputFilePath = Path.Combine(outputDir, outputFileName);

            var csvLines = new StringBuilder();

            csvLines.AppendLine("OrderNumber,CustomerNumber,Description,Quantity");
            csvLines.AppendLine("42, 100001, Shirt, II");
            csvLines.AppendLine("43, 200002, Shorts, I");
            csvLines.AppendLine("@ This is a comment");
            csvLines.AppendLine("");
            csvLines.AppendLine("44, 300003, Cap, V");

            var mockFileInput  = new MockFileData(csvLines.ToString());
            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddFile(inputFilePath, mockFileInput);
            mockFileSystem.AddDirectory(outputDir);

            var sut = new CsvFileProcessor(inputFilePath, outputFilePath, mockFileSystem);

            sut.Process();

            Assert.True(mockFileSystem.FileExists(outputFilePath));

            MockFileData processedFile = mockFileSystem.GetFile(outputFilePath);

            Approvals.Verify(processedFile.TextContents);
        }
Exemple #16
0
        private static MockFileSystem CreateVirtualFileSystemWithFolder(string folder)
        {
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(folder);
            return(fileSystem);
        }
        public static MockFileSystem CreateMockFileSystem()
        {
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(@"C:\");
            return(fileSystem);
        }
Exemple #18
0
        public IFileSystem GetFileSystem()
        {
            MockFileSystem fs = new MockFileSystem();
            fs.AddFile(@"C:\test\staticsql.json", new MockFileData("{ \"entity_folder\": \"StaticSQL\"}"));

            fs.AddDirectory(@"C:\test\subfolder");


            fs.AddFile(@"C:\test\StaticSQL\entity.json", new MockFileData("{\"attributes\": \"\"}"));
            fs.AddDirectory(@"C:\empty");

            fs.AddFile(@"C:\double\staticsql1.json", new MockFileData("{ \"entity_folder\": \"StaticSQL\"}"));
            fs.AddFile(@"C:\double\staticsql2.json", new MockFileData("{ \"entity_folder\": \"StaticSQL\"}"));

            return fs;
        }
Exemple #19
0
        public void It_should_create_limelight_image_directory_if_it_does_not_exist()
        {
            _fileSystemMock.AddDirectory(Constants.SpotlightImageDirectoryPath);

            _spotlightImageSaver.Save();

            Assert.AreEqual(true, _fileSystemMock.Directory.Exists(Constants.LimelightImageDirectoryPath));
        }
        public void MockDirectory_EnumerateDirectories_WithTopDirectories_ShouldOnlyReturnTopDirectories()
        {
            // Arrange
            MockFileSystem 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
            IEnumerable <string> actualResult = fileSystem.Directory.EnumerateDirectories(XFS.Path(@"c:\Folder\"), "*.foo");

            // Assert
            Assert.Equal(actualResult, new[] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\") });
        }
        public void MockDirectory_GetDirectories_WithAllDirectories_ShouldReturnsAllMatchingSubFolders()
        {
            // Arrange
            MockFileSystem 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
            string[] actualResult = fileSystem.Directory.GetDirectories(XFS.Path(@"c:\Folder\"), "*.foo", SearchOption.AllDirectories);

            // Assert
            Assert.Equal(actualResult, new[] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\"), XFS.Path(@"C:\Folder\.foo\.foo\") });
        }
Exemple #22
0
        public void SetUp()
        {
            _filesystem = new MockFileSystem();
            _filesystem.AddDirectory(SDKUtil.GetUserConfigPath());

            _jsonUtil      = new JsonUtil(_filesystem);
            _configFactory = new SdkConfig.Factory(_jsonUtil);
        }
        public void 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
            Assert.That(actualNames, Is.EquivalentTo(new[] { @"C:\", @"Z:\", @"D:\" }));
        }
        public void MockFile_Delete_No_File_Does_Nothing()
        {
            const string filePath   = @"c:\something\demo.txt";
            var          fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(fileSystem.Path.GetDirectoryName(filePath));
            fileSystem.File.Delete(filePath);
        }
        public void 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
            Assert.That(actualResult, Is.EquivalentTo(new [] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\") }));
        }
        public void 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"));

            Assert.Contains(XFS.Path(@"C:\test\file.txt"), fileSystem.AllFiles.ToList());
            Assert.Contains(XFS.Path(@"C:\LOUD\file.txt"), fileSystem.AllFiles.ToList());
            Assert.Contains(XFS.Path(@"C:\test\SUBDirectory"), fileSystem.AllDirectories.ToList());
            Assert.Contains(XFS.Path(@"C:\LOUD\SUBDirectory"), fileSystem.AllDirectories.ToList());
        }
        public void 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
            Assert.That(actualResult, Is.EquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\"), XFS.Path(@"C:\Folder\.foo\.foo\") }));
        }
        public void 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"));

            Assert.Contains(XFS.Path(@"C:\test\subtest\new\file.txt"), fileSystem.AllFiles.ToList());
            Assert.Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\file.txt"), fileSystem.AllFiles.ToList());
            Assert.Contains(XFS.Path(@"C:\test\subtest\new\SUBDirectory"), fileSystem.AllDirectories.ToList());
            Assert.Contains(XFS.Path(@"C:\LOUD\SUBLOUD\new\SUBDirectory"), fileSystem.AllDirectories.ToList());
        }
        public void MockFileSystem_AddDirectory_ShouldCreateDirectory()
        {
            string baseDirectory = XFS.Path(@"C:\Test");
            var    fileSystem    = new MockFileSystem();

            fileSystem.AddDirectory(baseDirectory);

            Assert.IsTrue(fileSystem.Directory.Exists(baseDirectory));
        }
        public void 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
            actualNames.Should().BeEquivalentTo(new[] { @"C:\", @"Z:\", @"D:\" });
        }
        public void MockFileSystem_AddDirectory_TrailingSlashAllowedButNotRequired(string path)
        {
            var fileSystem = new MockFileSystem();
            var path2      = XFS.Path(path);

            fileSystem.AddDirectory(path2);

            Assert.IsTrue(fileSystem.FileExists(path2));
        }
        public void 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
            Assert.AreEqual(@"C:\", driveInfo.Name);
        }
        public void 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
            Assert.AreEqual(expectedDirectory, actualDirectory.FullName);
        }
        public void MockFile_AppendAllText_ShouldCreateIfNotExistWithBom()
        {
            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>());
            const string path = @"c:\something\demo3.txt";
            fileSystem.AddDirectory(@"c:\something\");

            // Act
            fileSystem.File.AppendAllText(path, "AA", Encoding.UTF32);

            // Assert
            CollectionAssert.AreEqual(
                new byte[] {255, 254, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0},
                fileSystem.GetFile(path).Contents);
        }
        public void MockFile_WriteAllBytes_ShouldWriteDataToMemoryFileSystem()
        {
            // Arrange
            string path = XFS.Path(@"c:\something\demo.txt");
            var fileSystem = new MockFileSystem();
            var fileContent = new byte[] { 1, 2, 3, 4 };
            fileSystem.AddDirectory(@"c:\something");

            // Act
            fileSystem.File.WriteAllBytes(path, fileContent);

            // Assert
            Assert.AreEqual(
                fileContent,
                fileSystem.GetFile(path).Contents);
        }
        public void MockFile_WriteAllText_ShouldWriteTextFileToMemoryFileSystem()
        {
            // Arrange
            string path = XFS.Path(@"c:\something\demo.txt");
            string fileContent = "Hello there!";
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(@"c:\something");

            // Act
            fileSystem.File.WriteAllText(path, fileContent);

            // Assert
            Assert.AreEqual(
                fileContent,
                fileSystem.GetFile(path).TextContents);
        }
        public void MockFile_WriteAllText_ShouldOverriteAnExistingFile()
        {
            // http://msdn.microsoft.com/en-us/library/ms143375.aspx

            // Arrange
            string path = XFS.Path(@"c:\something\demo.txt");
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(@"c:\something");

            // Act
            fileSystem.File.WriteAllText(path, "foo");
            fileSystem.File.WriteAllText(path, "bar");

            // Assert
            Assert.AreEqual("bar", fileSystem.GetFile(path).TextContents);
        }
        public void 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);
            Assert.That(data.Contents, Is.Empty);
        }
        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 void MockFileSystem_AddDirectory_ShouldCreateDirectory()
        {
            // Arrange
            string baseDirectory = MockUnixSupport.Path(@"C:\Test");
            var fileSystem = new MockFileSystem();

            // Act
            fileSystem.AddDirectory(baseDirectory);

            // Assert
            Assert.IsTrue(fileSystem.Directory.Exists(baseDirectory));
        }
        public void MockFileSystem_AddDirectory_ShouldThrowExceptionIfDirectoryIsReadOnly()
        {
            // Arrange
            const string baseDirectory = @"C:\Test";
            var fileSystem = new MockFileSystem();
            fileSystem.AddFile(baseDirectory, new MockFileData(string.Empty));
            fileSystem.File.SetAttributes(baseDirectory, FileAttributes.ReadOnly);

            // Act
            TestDelegate act = () => fileSystem.AddDirectory(baseDirectory);

            // Assert
            Assert.Throws<UnauthorizedAccessException>(act);
        }
        public void MockFile_ReadAllBytes_ShouldReturnDataSavedByWriteAllBytes()
        {
            // Arrange
            string path = XFS.Path(@"c:\something\demo.txt");
            var fileSystem = new MockFileSystem();
            var fileContent = new byte[] { 1, 2, 3, 4 };
            fileSystem.AddDirectory(@"c:\something");

            // Act
            fileSystem.File.WriteAllBytes(path, fileContent);

            // Assert
            Assert.AreEqual(
                fileContent,
                fileSystem.File.ReadAllBytes(path));
        }
        public void 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;

            // Assert
            Assert.AreEqual(XFS.Path(@"c:\a\b"), result.FullName);
        }
        public void Move_DirectoryExistsWithDifferentCase_DirectorySuccessfullyMoved()
        {
            // Arrange
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(@"C:\OLD_LOCATION\Data");
            fileSystem.AddFile(@"C:\old_location\Data\someFile.txt", new MockFileData("abc"));

            // Act
            fileSystem.Directory.Move(@"C:\old_location", @"C:\NewLocation\");

            // Assert
            Assert.IsTrue(fileSystem.File.Exists(@"C:\NewLocation\Data\someFile.txt"));
        }
        public void MockFile_WriteAllTextMultipleLines_ShouldWriteTextFileToMemoryFileSystem()
        {
            // Arrange
            string path = XFS.Path(@"c:\something\demo.txt");

            var fileContent = new List<string> {"Hello there!", "Second line!"};
            var expected = "Hello there!" + Environment.NewLine + "Second line!" + Environment.NewLine;

            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(@"c:\something");

            // Act
            fileSystem.File.WriteAllLines(path, fileContent);

            // Assert
            Assert.AreEqual(
                expected,
                fileSystem.GetFile(path).TextContents);
        }
        public void MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternHasIllegalCharacters(string searchPattern)
        {
            // Arrange
            var directoryPath = XFS.Path(@"c:\Foo");
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(directoryPath);

            // Act
            TestDelegate action = () => fileSystem.Directory.GetFiles(directoryPath, searchPattern);

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockDirectory_GetFiles_ShouldThrowAnArgumentException_IfSearchPatternEndsWithTwoDots()
        {
            // Arrange
            var directoryPath = XFS.Path(@"c:\Foo");
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(directoryPath);

            // Act
            TestDelegate action = () => fileSystem.Directory.GetFiles(directoryPath, "*a..");

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockDirectory_Move_ShouldThrowAnIOExceptionIfDirectoriesAreOnDifferentVolumes()
        {
            // Arrange
            string sourcePath = XFS.Path(@"c:\a");
            string destPath = XFS.Path(@"d:\v");
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(sourcePath);

            // Act
            TestDelegate action = () => fileSystem.Directory.Move(sourcePath, destPath);

            // Assert
            Assert.Throws<IOException>(action, "Source and destination path must have identical roots. Move will not work across volumes.");
        }
        public void MockDirectory_Move_ShouldThrowAnIOExceptionIfBothPathAreIdentical()
        {
            // Arrange
            string path = XFS.Path(@"c:\a");
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(path);

            // Act
            TestDelegate action = () => fileSystem.Directory.Move(path, path);

            // Assert
            Assert.Throws<IOException>(action, "Source and destination path must be different.");
        }
        public void MockDirectory_GetParent_ShouldReturnNullIfPathIsRoot()
        {
            // Arrange
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(XFS.Path(@"c:\"));

            // Act
            var actualResult = fileSystem.Directory.GetParent(XFS.Path(@"c:\"));

            // Assert
            Assert.IsNull(actualResult);
        }
        public void MockFile_WriteAllText_ShouldThrowAnUnauthorizedAccessExceptionIfThePathIsOneDirectory()
        {
            // Arrange
            var fileSystem = new MockFileSystem();
            string directoryPath = XFS.Path(@"c:\something");
            fileSystem.AddDirectory(directoryPath);

            // Act
            TestDelegate action = () => fileSystem.File.WriteAllText(directoryPath, null);

            // Assert
            Assert.Throws<UnauthorizedAccessException>(action);
        }
        public void 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
            Assert.That(actualResult, Is.EquivalentTo(new []{XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\")}));
        }
        public void MockFile_WriteAllText_Encoding_ShouldWriteTextFileToMemoryFileSystem(KeyValuePair<Encoding, byte[]> 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(@"c:\something");

            // Act
            fileSystem.File.WriteAllText(path, FileContent, encoding);

            // Assert
            var actualBytes = fileSystem.GetFile(path).Contents;
            Assert.AreEqual(expectedBytes, actualBytes);
        }
        public void 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
            Assert.That(actualResult, Is.EquivalentTo(new[] { XFS.Path(@"C:\Folder\.foo\"), XFS.Path(@"C:\Folder\foo.foo\"), XFS.Path(@"C:\Folder\.foo\.foo\") }));
        }
        public void MockDirectory_GetParent_ShouldReturnTheParentWithoutTrailingDirectorySeparatorChar(string path, string expectedResult)
        {
            // Arrange
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(path);

            // Act
            var actualResult = fileSystem.Directory.GetParent(path);

            // Assert
            Assert.AreEqual(expectedResult, actualResult.FullName);
        }
        public void MockFile_GetAttributeOfNonExistantFileButParentDirectoryExists_ShouldThrowOneFileNotFoundException()
        {
            // Arrange
            var fileSystem = new MockFileSystem();
            fileSystem.AddDirectory(XFS.Path(@"c:\something"));

            // Act
            TestDelegate action = () => fileSystem.File.GetAttributes(XFS.Path(@"c:\something\demo.txt"));

            // Assert
            Assert.Throws<FileNotFoundException>(action);
        }