public void MockFile_Open_ThrowsOnTruncateWithMissingFile()
        {
            string filepath = XFS.Path(@"c:\something\doesnt\exist.txt");
            var filesystem = new MockFileSystem(new Dictionary<string, MockFileData>());

            Assert.Throws<FileNotFoundException>(() => filesystem.File.Open(filepath, FileMode.Truncate));
        }
 public void Files_On_Different_FileSystems_Are_Not_Equal()
 {
     var fileA = FileSystem.FileDescribing(@"c:\path\to\file.txt");
     var fileB = new MockFileSystem().FileDescribing(@"c:\path\to\file.txt");
     AssertEqualityNotEquals(fileA, fileB);
     AssertOperatorNotEquals(fileA, fileB);
 }
 public void Directories_On_Different_FileSystems_Are_Not_Equal()
 {
     var dirA = FileSystem.DirectoryDescribing(@"c:\path\to");
     var dirB = new MockFileSystem().DirectoryDescribing(@"c:\path\to");
     AssertEqualityNotEquals(dirA, dirB);
     AssertOperatorNotEquals(dirA, dirB);
 }
        public void Mockfile_Create_OverwritesExistingFile()
        {
            string path = XFS.Path(@"c:\some\file.txt");
            var fileSystem = new MockFileSystem();

            var mockFile = new MockFile(fileSystem);

            fileSystem.Directory.CreateDirectory(Path.GetDirectoryName(path));

            // 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));
        }
        public void MockFileInfo_Length_ShouldThrowFileNotFoundExcpetionIfFileDoesNotExistInMemoryFileSystem()
        {
            // Arrange
            const string fileContent = "Demo text content";
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { @"c:\a.txt", new MockFileData(fileContent) },
                { @"c:\a\b\c.txt", new MockFileData(fileContent) },
            });
            var fileInfo = new MockFileInfo(fileSystem, @"c:\foo.txt");

            try
            {
                // Act
                fileInfo.Length.ToString();

                // Assert
                Assert.Fail("Expected exception was not thrown");
            }
            catch (FileNotFoundException ex)
            {
                // Assert
                Assert.AreEqual(@"c:\foo.txt", ex.FileName);
            }
        }
        public void MockDirectory_GetFiles_ShouldReturnFilesDirectlyBelowPathWhenPatternIsWildcardAndSearchOptionIsTopDirectoryOnly()
        {
            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { @"c:\a.txt", new MockFileData("Demo text content") },
                { @"c:\b.txt", new MockFileData("Demo text content") },
                { @"c:\c.txt", new MockFileData("Demo text content") },
                { @"c:\a\a.txt", new MockFileData("Demo text content") },
                { @"c:\a\b.txt", new MockFileData("Demo text content") },
                { @"c:\a\c.txt", new MockFileData("Demo text content") },
                { @"c:\a\a\a.txt", new MockFileData("Demo text content") },
                { @"c:\a\a\b.txt", new MockFileData("Demo text content") },
                { @"c:\a\a\c.txt", new MockFileData("Demo text content") },
            });

            // Act
            var result = fileSystem.Directory.GetFiles(@"c:\a", "*", SearchOption.TopDirectoryOnly);

            // Assert
            CollectionAssert.AreEqual
            (
                new[]
                {
                    @"c:\a\a.txt",
                    @"c:\a\b.txt",
                    @"c:\a\c.txt"
                },
                result
            );
        }
 public void MyTestInitialize()
 {
     _fileSystem = new MockFileSystem();
     var mockExifReader = new MockExifReader(_fileSystem);
     _directoryFactory = new PictureDirectoryFactory(_fileSystem, mockExifReader);
     _fileHandlerFactory = new FileHandlerFactory(_fileSystem);
 }
        public void MockFile_AppendAllText_ShouldPersistNewTextWithCustomEncoding()
        {
            // Arrange
            const string path = @"c:\something\demo.txt";
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { 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, 255, 253, 0, 43, 0, 32, 0, 115, 0, 111, 0, 109, 0, 101,
                0, 32, 0, 116, 0, 101, 0, 120, 0, 116
            };
            CollectionAssert.AreEqual(
                expected,
                file.ReadAllBytes(path));
        }
        public void MockFile_Move_ShouldThrowArgumentNullExceptionWhenSourceIsNull_ParamName() {
            string destFilePath = XFS.Path(@"c:\something\demo.txt");
            var fileSystem = new MockFileSystem();

            var exception = Assert.Throws<ArgumentNullException>(() => fileSystem.File.Move(null, destFilePath));

            Assert.That(exception.ParamName, Is.EqualTo("sourceFileName"));
        }
        public void MockFile_Copy_ShouldThrowArgumentNullExceptionWhenSourceIsNull_Message()
        {
            string destFilePath = XFS.Path(@"c:\something\demo.txt");
            var fileSystem = new MockFileSystem();

            var exception = Assert.Throws<ArgumentNullException>(() => fileSystem.File.Copy(null, destFilePath));

            Assert.That(exception.Message, Is.StringStarting("File name cannot be null."));
        }
示例#11
0
 public void CreateNewDirectoryWithRenameAttemptsDateTest()
 {
     MockFileSystem mockFileSystem = new MockFileSystem();
     FileCreator.CreateNewDirectoryWithRenameAttempts("D:\\tmp\\ayt-export\\iPhone Text History Backup - 03-03-2012", mockFileSystem, 10);
     Assert.AreEqual(1, mockFileSystem.DirectoryCount);
     Assert.IsTrue(mockFileSystem.DirectoryExists("D:\\tmp\\ayt-export\\iPhone Text History Backup - 03-03-2012"));
     FileCreator.CreateNewDirectoryWithRenameAttempts("D:\\tmp\\ayt-export\\iPhone Text History Backup - 03-03-2012", mockFileSystem, 10);
     Assert.AreEqual(2, mockFileSystem.DirectoryCount);
     Assert.IsTrue(mockFileSystem.DirectoryExists("D:\\tmp\\ayt-export\\iPhone Text History Backup - 03-03-2012 (2)"));
 }
        public void MockFile_Open_ThrowsOnCreateNewWithExistingFile()
        {
            string filepath = XFS.Path(@"c:\something\already\exists.txt");
            var filesystem = new MockFileSystem(new Dictionary<string, MockFileData> 
            {
                { filepath, new MockFileData("I'm here") }
            });

            Assert.Throws<IOException>(() => filesystem.File.Open(filepath, FileMode.CreateNew));
        }
        public void MockFile_Delete_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path)
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate action = () => fileSystem.File.Delete(path);

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathContainsInvalidChar(string path)
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate action = () => fileSystem.File.AppendAllLines(path, new[] { "does not matter" });

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockFile_WriteAllBytes_ShouldThrowAnArgumentExceptionIfContainsIllegalCharacters()
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate action = () => fileSystem.File.WriteAllBytes("<<<", new byte[] { 123 });

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockDriveInfo_Constructor_ShouldThrowExceptionIfUncPath(string driveName)
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate action = () => new MockDriveInfo(fileSystem, XFS.Path(driveName));

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockFile_AppendAllLines_ShouldThrowArgumentExceptionIfPathIsZeroLength()
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate action = () => fileSystem.File.AppendAllLines(string.Empty, new[] { "does not matter" });

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockFile_Open_CreatesNewFileFileOnCreateNew()
        {
            string filepath = XFS.Path(@"c:\something\doesnt\exist.txt");
            var filesystem = new MockFileSystem(new Dictionary<string, MockFileData>());

            var stream = filesystem.File.Open(filepath, FileMode.CreateNew);

            Assert.That(filesystem.File.Exists(filepath), Is.True);
            Assert.That(stream.Position, Is.EqualTo(0));
            Assert.That(stream.Length, Is.EqualTo(0));
        }
        public void MockFile_WriteAllText_ShouldThrowAnArgumentExceptionIfThePathIsEmpty()
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate action = () => fileSystem.File.WriteAllText(string.Empty, "hello world");

            // Assert
            Assert.Throws<ArgumentException>(action);
        }
        public void MockFile_GetLastAccessTimeUtc_ShouldReturnDefaultTimeIfFileDoesNotExist()
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            var actualLastAccessTime = fileSystem.File.GetLastAccessTimeUtc(@"c:\does\not\exist.txt");

            // Assert
            Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc), actualLastAccessTime);
        }
 public void Mockfile_Create_ThrowsWhenPathIsReadOnly()
 {
     string path = XFS.Path(@"c:\something\read-only.txt");
     var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { path, new MockFileData("Content") } });
     var mockFile = new MockFile(fileSystem);
     
     mockFile.SetAttributes(path, FileAttributes.ReadOnly);
  
     var exception =  Assert.Throws<UnauthorizedAccessException>(() => mockFile.Create(path).Close());
     Assert.That(exception.Message, Is.EqualTo(string.Format(CultureInfo.InvariantCulture, "Access to the path '{0}' is denied.", path)));
 }
        public void MockFile_Copy_ShouldThrowExceptionWhenFolderInDestinationDoesNotExist(string sourceFilePath, string destFilePath)
        {
            string sourceFileName = XFS.Path(sourceFilePath);
            string destFileName = XFS.Path(destFilePath);
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                {sourceFileName, MockFileData.NullObject}
            });

            Assert.Throws<DirectoryNotFoundException>(() => fileSystem.File.Copy(sourceFileName, destFileName), string.Format(CultureInfo.InvariantCulture, @"Could not find a part of the path '{0}'.", destFilePath));
        }
        public void MockFile_GetCreationTime_ShouldReturnDefaultTimeIfFileDoesNotExist()
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            var actualCreationTime = fileSystem.File.GetCreationTime(@"c:\does\not\exist.txt");

            // Assert
            Assert.AreEqual(new DateTime(1601, 01, 01, 00, 00, 00, DateTimeKind.Utc).ToLocalTime(), actualCreationTime);
        }
        public void MockDirectoryInfo_GetExtensionWithTrailingSlash_ShouldReturnEmptyString()
        {
            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>());
            var directoryInfo = new MockDirectoryInfo(fileSystem, XFS.Path(@"c:\temp\"));

            // Act
            var result = directoryInfo.Extension;

            // Assert
            Assert.AreEqual(string.Empty, result);
        }
        public void MockDirectoryInfo_GetExtension_ShouldReturnEmptyString(string directoryPath)
        {
            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>());
            var directoryInfo = new MockDirectoryInfo(fileSystem, directoryPath);

            // Act
            var result = directoryInfo.Extension;

            // Assert
            Assert.AreEqual(string.Empty, result);
        }
        public void MockFile_GetLastAccessTimeUtc_ShouldThrowArgumentExceptionIfPathContainsOnlyWhitespaces(string path)
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate action = () => fileSystem.File.GetLastAccessTimeUtc(path);

            // Assert
            var exception = Assert.Throws<ArgumentException>(action);
            Assert.That(exception.ParamName, Is.EqualTo("path"));
        }
        public void Operations_ShouldThrowArgumentNullExceptionIfPathIsNull(Action<FileBase> action)
        {
            // Arrange
            var fileSystem = new MockFileSystem();

            // Act
            TestDelegate wrapped = () => action(fileSystem.File);

            // Assert
            var exception = Assert.Throws<ArgumentNullException>(wrapped);
            Assert.AreEqual("path", exception.ParamName);
        }
示例#28
0
        public void TestJsFileWithExtraNonNodeFile(string nonNodeFile)
        {
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { @"c:\site\hello.js", new MockFileData("some js") },
                { @"c:\site\" + nonNodeFile, new MockFileData("some file") },
            });

            var nodeSiteEnabler = new NodeSiteEnabler(fileSystem, @"c:\repo", @"c:\site");

            Assert.False(nodeSiteEnabler.NeedNodeHandling());
        }
        public void MockDirectoryInfo_Exists(string path, bool expected) 
        {
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> 
            {
                {XFS.Path(@"c:\temp\folder\file.txt"), new MockFileData("Hello World")}
            });
            var directoryInfo = new MockDirectoryInfo(fileSystem, path);

            var result = directoryInfo.Exists;

            Assert.That(result, Is.EqualTo(expected));
        }
        public void TestInitialize()
        {
            this.dte             = new DTEMock();
            this.serviceProvider = new ConfigurableServiceProvider();
            this.solutionMock    = new SolutionMock(dte, Path.Combine(SolutionRoot, "xxx.sln"));
            this.outputPane      = new ConfigurableVsOutputWindowPane();
            this.serviceProvider.RegisterService(typeof(SVsGeneralOutputWindowPane), this.outputPane);
            this.projectSystemHelper  = new ConfigurableVsProjectSystemHelper(this.serviceProvider);
            this.solutionItemsProject = this.solutionMock.AddOrGetProject("Solution items");
            this.projectSystemHelper.SolutionItemsProject  = this.solutionItemsProject;
            this.projectSystemHelper.CurrentActiveSolution = this.solutionMock;
            this.fileSystem    = new MockFileSystem();
            this.sccFileSystem = new ConfigurableSourceControlledFileSystem(fileSystem);
            this.ruleFS        = new ConfigurableRuleSetSerializer(fileSystem);
            this.ruleSetInfo   = new ConfigurableSolutionRuleSetsInformationProvider
            {
                SolutionRootFolder = SolutionRoot
            };

            this.serviceProvider.RegisterService(typeof(IProjectSystemHelper), this.projectSystemHelper);
            this.serviceProvider.RegisterService(typeof(ISourceControlledFileSystem), this.sccFileSystem);
            this.serviceProvider.RegisterService(typeof(IRuleSetSerializer), this.ruleFS);
            this.serviceProvider.RegisterService(typeof(ISolutionRuleSetsInformationProvider), this.ruleSetInfo);
        }
示例#31
0
        public void TestFileCopy()
        {
            // Arrange
            ILoggerFactory loggerFactory = new LoggerFactory();
            ILogger        logger        = loggerFactory.CreateConsoleLogger();

            var mockFileDataMap = new Dictionary <string, MockFileData>()
            {
                { @"C:\myfile.txt", new MockFileData("Test data") }
            };
            IFileSystem mockFileSystem = new MockFileSystem(mockFileDataMap);

            var application = new DriveBackup.Application(mockFileSystem, logger);

            // Act
            application.Run(@"C:\", @"D:\");

            // Assert
            Assert.IsTrue(mockFileSystem.File.Exists(@"D:\myfile.txt"));
            Assert.AreEqual(
                mockFileSystem.File.ReadAllText(@"C:\myfile.txt"),
                mockFileSystem.File.ReadAllText(@"D:\myfile.txt")
                );
        }
示例#32
0
        public async Task CallingCycloneDX_CreatesOutputDirectory()
        {
            var mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { XFS.Path(@"c:\SolutionPath\SolutionFile.sln"), "" }
            });
            var mockSolutionFileService = new Mock <ISolutionFileService>();

            mockSolutionFileService
            .Setup(s => s.GetSolutionNugetPackages(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>()))
            .ReturnsAsync(new HashSet <NugetPackage>());
            Program.fileSystem          = mockFileSystem;
            Program.solutionFileService = mockSolutionFileService.Object;
            var args = new string[]
            {
                XFS.Path(@"c:\SolutionPath\SolutionFile.sln"),
                "-o", XFS.Path(@"c:\NewDirectory")
            };

            var exitCode = await Program.Main(args).ConfigureAwait(false);

            Assert.Equal((int)ExitCode.OK, exitCode);
            Assert.True(mockFileSystem.FileExists(XFS.Path(@"c:\NewDirectory\bom.xml")));
        }
示例#33
0
        public async Task Should_Return_NotFound()
        {
            // Arrange

            var fs = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { "C:/A/wtfd.json", MockData.NestedConfig(isRoot: true).config.ToMockFileData() },
            }, "C:/A/E/");

            MockData.AddDirectories(fs);

            var configs = (await new FindCommandHandler(fs).Handle(new FindRequest(), CancellationToken.None))
                          .Configurations;
            var reporter = new ReportCommandHandler(fs);

            // Act
            var result = await reporter.Handle(new ReportRequest
            {
                Configurations = configs
            }, CancellationToken.None);

            // Assert
            result.NotFound.Should().BeTrue();
        }
示例#34
0
        public void TxFileInfo_NotAddedToJournal()
        {
            var fileName = "/tmp/filetogetinfoof.txt";

            var mockFileSystem = new MockFileSystem();
            var txFileSystem   = new TxFileSystem(mockFileSystem);

            txFileSystem.Directory.CreateDirectory("/tmp");
            txFileSystem.File.Create(fileName);

            IFileInfo fileInfo = null;

            using (var transactionScope = new TransactionScope())
            {
                txFileSystem = new TxFileSystem(mockFileSystem);
                fileInfo     = txFileSystem.FileInfo.FromFileName(fileName);

                transactionScope.Complete();
            }

            Assert.IsType <MockFileInfo>(fileInfo);

            Assert.Empty(txFileSystem.Journal._txJournalEntries);
        }
示例#35
0
        public async Task GetTownNameAsync_WithCorrectData_WorksCorrectly()
        {
            // Arrange
            const string expectedResult = "TestTown";

            var json =
                $@"[
                  {{
                    ""name"": ""Town1"",
                    ""latitude"": 10.5,
                    ""longitude"": 11.7
                  }},
                  {{
                    ""name"": ""{expectedResult}"",
                    ""latitude"": -1.5,
                    ""longitude"": -2.0004
                  }},
                  {{
                    ""name"": ""Town2"",
                    ""latitude"": 7.7,
                    ""longitude"": 6.1
                  }}
                ]";

            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddFile(TownsFileName, new MockFileData(json));

            var locationHelper = new LocationHelper(mockFileSystem);

            // Act
            var actualResult = await locationHelper.GetTownNameAsync(2, 2);

            // Assert
            Assert.Equal(expectedResult, actualResult);
        }
示例#36
0
        public void CompareCheckMissingLabels()
        {
            CurrentProject.SetProjectPath(@"C:/project/");
            List <string> testAllLanguages = new List <string> {
                "en"
            };

            CurrentProject.SetAllLanguage(testAllLanguages);

            MockFileSystem mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { Path.Combine(CurrentProject.Path, testAllLanguages[0], "global.json"), new MockFileData("{'home':'town', 'city':'fun'}") },
                { Path.Combine(CurrentProject.Path, "Meta", "global.json"), new MockFileData("{'home':'otherstuf'}") },
                { Path.Combine(CurrentProject.Path, "Meta", "Default", "global.json"), new MockFileData("{'home':''}") }
            });

            JsonCompare jsonCompare  = new JsonCompare(mockFileSystem);
            bool        checkMissing = jsonCompare.Compare();

            if (checkMissing)
            {
                Assert.Fail();
            }
        }
示例#37
0
        public void VsSettingSwitchesSettingsIfSolutionChanges()
        {
            // Arrange
            var solutionManager = new Mock <MockSolutionManager>();

            solutionManager.Setup(s => s.IsSolutionOpen).Returns(true).Verifiable();
            solutionManager.Setup(s => s.SolutionDirectory).Returns(@"x:\solution").Verifiable();
            var defaultSettings = new Mock <ISettings>(MockBehavior.Strict);

            var fileSystemA = new MockFileSystem();

            fileSystemA.AddFile("nuget.config", @"<?xml version=""1.0"" ?><configuration><solution><add key=""foo"" value=""barA"" /></solution></configuration>");

            var fileSystemB = new MockFileSystem();

            fileSystemB.AddFile("nuget.config", @"<?xml version=""1.0"" ?><configuration><solution><add key=""foo"" value=""barB"" /></solution></configuration>");

            var fileSystemProvider = new Mock <IFileSystemProvider>(MockBehavior.Strict);

            fileSystemProvider.Setup(f => f.GetFileSystem(@"x:\solution\.nuget")).Returns(fileSystemA).Verifiable();
            fileSystemProvider.Setup(f => f.GetFileSystem(@"y:\solution\.nuget")).Returns(fileSystemB).Verifiable();

            // Act
            var vsSettings = new VsSettings(solutionManager.Object, defaultSettings.Object, fileSystemProvider.Object);
            var valueA     = vsSettings.GetValue("solution", "foo");

            solutionManager.Object.CloseSolution();
            solutionManager.Setup(s => s.SolutionDirectory).Returns(@"y:\solution").Verifiable();
            solutionManager.Object.CloseSolution();

            var valueB = vsSettings.GetValue("solution", "foo");

            // Assert
            Assert.Equal("barA", valueA);
            Assert.Equal("barB", valueB);
        }
示例#38
0
        private void validateMoveFiles(string workingDirectoryPath, string[] allFilePathsInSystem, string[] whitelistExtensions, string[] expectedWhitelistFilePaths, string[] expectedOutOfWhitelistFilePaths)
        {
            var mockFileSystem = new MockFileSystem();

            foreach (var item in allFilePathsInSystem)
            {
                mockFileSystem.AddFile(item, new MockFileData(new byte[] { 0x12 }));
            }

            var testFileSystem = new FileSystemForTesting(mockFileSystem);
            var sut            = new MoveAllFilesLogic(testFileSystem);

            sut.Begin(workingDirectoryPath, whitelistExtensions);

            sut.GetAllFilePaths(workingDirectoryPath)
            .Should()
            .BeEquivalentTo(expectedWhitelistFilePaths, "All whitelist files must be here.");

            var tempDirectoryPath = $"{workingDirectoryPath}temp\\";

            sut.GetAllFilePaths(tempDirectoryPath)
            .Should()
            .BeEquivalentTo(expectedOutOfWhitelistFilePaths, "All out of whitelist files must be here.");
        }
        public void InputFileResolver_InitializeShouldCrawlFiles()
        {
            string sourceFile  = File.ReadAllText(_currentDirectory + "/Initialisation/TestResources/ExampleSourceFile.cs");
            string projectFile = @"<Project Sdk=""Microsoft.NET.Sdk"">
 <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
       <IsPackable>false</IsPackable>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include=""Microsoft.NET.Test.Sdk"" Version = ""15.5.0"" />
        <PackageReference Include=""xunit"" Version=""2.3.1"" />
        <PackageReference Include=""xunit.runner.visualstudio"" Version=""2.3.1"" />
        <DotNetCliToolReference Include=""dotnet-xunit"" Version=""2.3.1"" />
    </ItemGroup>
               
    <ItemGroup>
        <ProjectReference Include=""..\ExampleProject\ExampleProject.csproj"" />
    </ItemGroup>
                
</Project>";
            var    fileSystem  = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { @"c:\ExampleProject\ExampleProject.csproj", new MockFileData(projectFile) },
                { @"c:\ExampleProject\Recursive.cs", new MockFileData(sourceFile) },
                { @"c:\TestProject\TestProject.csproj", new MockFileData(projectFile) },
                { @"c:\TestProject\bin\Debug\netcoreapp2.0\ExampleProject.dll", new MockFileData("Bytecode") },
                { @"c:\TestProject\obj\Release\netcoreapp2.0\ExampleProject.dll", new MockFileData("Bytecode") }
            });

            var target = new InputFileResolver(fileSystem);

            var result = target.ResolveInput(@"c:\TestProject\", "");

            result.TestProjectPath.ShouldBe(@"c:\TestProject\");
        }
        public void MockFile_Decrypt_ShouldDecryptTheFile()
        {
            // 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 <string, MockFileData>
            {
                { filePath, fileData }
            });

            // Act
            fileSystem.File.Decrypt(filePath);

            string newcontents;

            using (var newfile = fileSystem.File.OpenText(filePath))
            {
                newcontents = newfile.ReadToEnd();
            }

            // Assert
            Assert.AreNotEqual(Content, newcontents);
        }
    public void Test(
        MockFileSystem fs,
        string outputLocation,
        string inputLocation,
        string[] targetFolderNames,
        string pathToCheck)
    {
        var options = new CliOptions
        {
            OutputLocation      = outputLocation,
            PathToMarkdownFiles = inputLocation
        };

        var sut = new FolderProcessingStrategy(fs, options);

        foreach (var folder in targetFolderNames)
        {
            sut.Execute(new FolderFileSystemObject(folder));
        }

        var success = fs.AllDirectories.Any(d => d == pathToCheck);

        Assert.True(success);
    }
示例#42
0
        public void Should_Process_Less_Imports()
        {
            var filepath1    = @"c:\css\style-dependency.less";
            var fileContent1 = "@brand_color: #4D926F;";
            var filepath2    = @"c:\css\style.less";
            var fileContent2 = "@import \"style-dependency.less\"; a { color: @brand_color; }";

            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { HtmlFilePath, new MockFileData(PageContent) },
                { filepath1, new MockFileData(fileContent1) },
                { filepath2, new MockFileData(fileContent2) }
            });

            var expectedOutput = @"a{color:#4D926F}";

            var minifier = new LessTransform(fileSystem);
            var context  = new SiteContext {
                SourceFolder = @"C:\", OutputFolder = @"C:\_site"
            };

            context.Pages.Add(new NonProcessedPage {
                OutputFile = HtmlFilePath, Content = PageContent
            });
            context.Pages.Add(new NonProcessedPage {
                OutputFile = filepath1, Content = fileContent1, Filepath = filepath1
            });
            context.Pages.Add(new NonProcessedPage {
                OutputFile = filepath2, Content = fileContent2, Filepath = filepath2
            });
            minifier.Transform(context);

            var minifiedFile = fileSystem.File.ReadAllText(@"c:\css\style.css", Encoding.UTF8);

            Assert.Equal(expectedOutput, minifiedFile);
        }
示例#43
0
    static (MockFileSystem disk, string baseDir, GeneralConfig generalConfig, AssetMapping mapping) SetupAssets(IJsonUtil jsonUtil)
    {
        Event.AddEventsFromAssembly(typeof(ActionEvent).Assembly);
        var mapping         = new AssetMapping();
        var disk            = new MockFileSystem(true);
        var baseDir         = ConfigUtil.FindBasePath(disk);
        var assetConfigPath = Path.Combine(baseDir, "mods", "Base", "assets.json");
        var assetConfig     = AssetConfig.Load(assetConfigPath, mapping, disk, jsonUtil);
        var generalConfig   = AssetSystem.LoadGeneralConfig(baseDir, disk, jsonUtil);

        foreach (var assetType in assetConfig.IdTypes.Values)
        {
            var enumType = Type.GetType(assetType.EnumType);
            if (enumType == null)
            {
                throw new InvalidOperationException(
                          $"Could not load enum type \"{assetType.EnumType}\" defined in \"{assetConfigPath}\"");
            }

            mapping.RegisterAssetType(assetType.EnumType, assetType.AssetType);
        }

        return(disk, baseDir, generalConfig, mapping);
    }
            public static IEnumerable ForPathIsDirectory()
            {
                var fileSystem = new MockFileSystem();
                var path       = XFS.Path(@"c:\something");

                fileSystem.Directory.CreateDirectory(path);
                var    fileContentEnumerable = new List <string>();
                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);

                // IEnumerable
                yield return(new object[] { writeEnumberable, path, "WriteAllLines(string, IEnumerable<string>)" });

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

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

                yield return(new object[] { writeArrayUtf32, path, "WriteAllLines(string, string[], Encoding.UTF32)" });
            }
        public void AddPackageAddsEntryToPackagesConfigWithTargetFramework()
        {
            // Arrange
            var    sharedRepository = new Mock <ISharedPackageRepository>();
            string path             = null;

            sharedRepository.Setup(m => m.RegisterRepository(It.IsAny <string>()))
            .Callback <string>(p => path = p);
            var fileSystem          = new MockFileSystem();
            var referenceRepository = new PackageReferenceRepository(fileSystem, sharedRepository.Object);

            //var package = PackageUtility.CreatePackage("A");

            // Act
            referenceRepository.AddPackage("A", new SemanticVersion("1.0"), new FrameworkName("Silverlight, Version=2.0"));

            // Assert
            Assert.Equal(@"C:\MockFileSystem\packages.config", path);
            Assert.True(fileSystem.FileExists("packages.config"));
            AssertConfig(@"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""A"" version=""1.0"" targetFramework=""sl20"" />
</packages>", fileSystem.ReadAllText("packages.config"));
        }
示例#46
0
        public void LoadPlugins_ShouldLoadPluginsDirectoriesWithRelativePaths()
        {
            // arrange
            var currentDirectory = Directory.GetParent(Assembly.GetExecutingAssembly().Location);
            var executingLocationParentFolder = currentDirectory.Parent.FullName;

            var filePath1 = Path.Combine(executingLocationParentFolder, "subDirectory", "plugin_one.dll");

            var fileSystem = new MockFileSystem(
                new Dictionary <string, MockFileData>
            {
                {
                    filePath1, new MockFileData(string.Empty)
                }
            },
                currentDirectory.FullName);

            var assemblyWrapper = new TestAssemblyWrapper();

            var reporter = Substitute.For <IReporter>();

            var pluginPaths = new Dictionary <string, string>
            {
                {
                    "my-first-plugin", @"..\subDirectory\"
                }
            };

            // act
            var pluginHandler = new Lib.Plugins.PluginHandler(reporter, fileSystem, assemblyWrapper);

            pluginHandler.ProcessPaths(pluginPaths);

            // assert
            Assert.AreEqual(1, pluginHandler.Plugins.Count);
        }
示例#47
0
        public void InstallCommandWorksIfExcludedVersionsAndPackageIsNotFoundInRemoteRepository()
        {
            // Arrange
            var fileSystem = new MockFileSystem();
            var packages   = new List <IPackage> {
                PackageUtility.CreatePackage("A", "0.5")
            };
            var repository = new Mock <IPackageRepository>();

            repository.Setup(c => c.GetPackages()).Returns(packages.AsQueryable());
            repository.Setup(c => c.AddPackage(It.IsAny <IPackage>())).Throws(new Exception("Method should not be called"));
            repository.Setup(c => c.RemovePackage(It.IsAny <IPackage>())).Throws(new Exception("Method should not be called"));

            var packageManager = new PackageManager(GetFactory().CreateRepository("Some source"), new DefaultPackagePathResolver(fileSystem), fileSystem, repository.Object);
            var installCommand = new TestInstallCommand(GetFactory(), GetSourceProvider(), fileSystem, packageManager);

            installCommand.ExcludeVersion = true;
            installCommand.Arguments.Add("A");

            // Act and Assert
            ExceptionAssert.Throws <InvalidOperationException>(() => installCommand.ExecuteCommand(), "Unable to find package 'A'.");
            // Ensure packages were not removed.
            Assert.Equal(1, packages.Count);
        }
        public void GetPackageTargetFrameworkReturnsCorrectValue()
        {
            // Arrange
            var repository = new Mock <MockPackageRepository>()
            {
                CallBase = true
            }.As <ISharedPackageRepository>();
            var packageA = PackageUtility.CreatePackage("A");

            repository.Object.AddPackage(packageA);
            var fileSystem = new MockFileSystem();

            fileSystem.AddFile("packages.config", @"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""A"" version=""1.0"" targetFramework=""winrt45"" />
</packages>");
            var referenceRepository = new PackageReferenceRepository(fileSystem, repository.Object);

            // Act
            var targetFramework = referenceRepository.GetPackageTargetFramework("A");

            // Assert
            Assert.Equal(new FrameworkName(".NETCore, Version=4.5"), targetFramework);
        }
示例#49
0
        public void InstallCommandUsesLocalCacheIfNoCacheIsFalse()
        {
            // Arrange
            var fileSystem = new MockFileSystem();
            var localCache = new Mock <IPackageRepository>(MockBehavior.Strict);

            localCache.Setup(c => c.GetPackages()).Returns(new[] { PackageUtility.CreatePackage("Gamma") }.AsQueryable()).Verifiable();
            var installCommand = new TestInstallCommand(GetFactory(), GetSourceProvider(), fileSystem, machineCacheRepository: localCache.Object)
            {
                NoCache = false,
                Version = "1.0"
            };

            installCommand.Arguments.Add("Gamma");
            installCommand.Source.Add("Some Source name");
            installCommand.Source.Add("Some other Source");

            // Act
            installCommand.ExecuteCommand();

            // Assert
            Assert.Equal(@"Gamma.1.0\Gamma.1.0.nupkg", fileSystem.Paths.Single().Key);
            localCache.Verify();
        }
        public void DeserializeMetadataItem_DeserializeXmlFile_ReturnsCorrectResult()
        {
            //arrange
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { testPath + @"\" + "test.xml", new MockFileData("<?xml version=\"1.0\" encoding=\"utf-16\"?><MetadataItem xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><_bezeichnung>testName</_bezeichnung><_itemTyp>testTyp</_itemTyp><_stichwoerter /><_benutzer>chs</_benutzer><_path>C:\\temp\\DMS</_path><_valutaDatum>2020-05-04T03:05:06</_valutaDatum><_erfassungsdatum>2020-05-04T03:05:06</_erfassungsdatum></MetadataItem>") },
                { testPath + @"\" + "test2.xml", new MockFileData("Testing is not...") }
            });
            var xmlService     = new XmlService(fileSystem);
            var expectedResult = new MetadataItem("testName", "testTyp", "", "chs",
                                                  testDateTime, testDateTime, testPath);

            //act
            var result = xmlService.DeserializeMetadataItem(testPath + @"\" + "test.xml");

            //assert
            Assert.AreEqual(result._bezeichnung, expectedResult._bezeichnung);
            Assert.AreEqual(result._itemTyp, expectedResult._itemTyp);
            Assert.AreEqual(result._stichwoerter, expectedResult._stichwoerter);
            Assert.AreEqual(result._benutzer, expectedResult._benutzer);
            Assert.AreEqual(result._path, expectedResult._path);
            Assert.AreEqual(result._valutaDatum, expectedResult._valutaDatum);
            Assert.AreEqual(result._erfassungsdatum, expectedResult._erfassungsdatum);
        }
        public void EmptySolution_ReturnsEmptyDependencyGraph()
        {
            var mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>());

            // Arrange
            var dotNetRunner = new Mock <IDotNetRunner>();

            string solutionProjects = string.Join(Environment.NewLine, "Project(s)", "-----------");

            dotNetRunner.Setup(runner => runner.Run(It.IsAny <string>(), It.Is <string[]>(a => a[0] == "sln")))
            .Returns(new RunStatus(solutionProjects, string.Empty, 0));

            var graphService = new DependencyGraphService(dotNetRunner.Object, mockFileSystem);

            // Act
            var dependencyGraph = graphService.GenerateDependencyGraph(_solutionPath);

            // Assert
            Assert.NotNull(dependencyGraph);
            Assert.Equal(0, dependencyGraph.Projects.Count);

            dotNetRunner.Verify(runner => runner.Run(_path, It.Is <string[]>(a => a[0] == "sln" && a[2] == "list" && a[1] == '\"' + _solutionPath + '\"')));
            dotNetRunner.Verify(runner => runner.Run(It.IsAny <string>(), It.Is <string[]>(a => a[0] == "msbuild")), Times.Never());
        }
示例#52
0
        public void GetPackageReferencesReturnsFalseForNonExistentId()
        {
            // Arrange
            var config     = @"<?xml version=""1.0"" encoding=""utf-8""?>
        <packages>
          <package id=""A"" version=""1.3.4"" />
          <package id=""A"" version=""2.5-beta"" />
          <package id=""B"" version=""1.0"" />
          <package id=""C"" version=""2.1.4"" />
        </packages>";
            var fileSystem = new MockFileSystem();

            fileSystem.AddFile("packages.config", config);
            var sharedRepository           = new Mock <MockPackageRepository>().As <ISharedPackageRepository>();
            var packageReferenceRepository = new PackageReferenceRepository(fileSystem, sharedRepository.Object);

            // Act
            SemanticVersion version;
            bool            result = packageReferenceRepository.TryFindLatestPackageById("does-not-exist", out version);

            // Assert
            Assert.False(result);
            Assert.Null(version);
        }
        public void InitializeShouldFindSpecifiedTestProjectFile()
        {
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { projectUnderTestPath, new MockFileData(defaultTestProjectFileContents) },
                { Path.Combine(_filesystemRoot, "ExampleProject", "Recursive.cs"), new MockFileData(sourceFile) },
                { Path.Combine(_filesystemRoot, "ExampleProject", "OneFolderDeeper", "Recursive.cs"), new MockFileData(sourceFile) },
                { testProjectPath, new MockFileData(defaultTestProjectFileContents) },
            });

            var projectFileReaderMock = new Mock <IProjectFileReader>(MockBehavior.Strict);

            projectFileReaderMock.Setup(x => x.AnalyzeProject(testProjectPath, null))
            .Returns(new ProjectAnalyzerResult(null, null)
            {
                ProjectReferences = new List <string>()
                {
                    projectUnderTestPath
                },
                TargetFrameworkVersionString = "netcoreapp2.1",
                ProjectFilePath = testProjectPath,
                References      = new string[] { "" }
            });
            projectFileReaderMock.Setup(x => x.AnalyzeProject(projectUnderTestPath, null))
            .Returns(new ProjectAnalyzerResult(null, null)
            {
                ProjectReferences            = new List <string>(),
                TargetFrameworkVersionString = "netcoreapp2.1",
                ProjectFilePath = projectUnderTestPath
            });
            var target = new InputFileResolver(fileSystem, projectFileReaderMock.Object);

            var result = target.ResolveInput(new StrykerOptions(fileSystem: fileSystem, basePath: _basePath));

            result.ProjectContents.GetAllFiles().Count().ShouldBe(2);
        }
示例#54
0
        public void GetPackageReferencesFindTheOnlyVersionAsLatestVersion()
        {
            // Arrange
            var config     = @"<?xml version=""1.0"" encoding=""utf-8""?>
        <packages>
          <package id=""A"" version=""1.3.4"" />
          <package id=""A"" version=""2.5-beta"" />
          <package id=""B"" version=""1.0"" />
          <package id=""C"" version=""2.1.4"" />
        </packages>";
            var fileSystem = new MockFileSystem();

            fileSystem.AddFile("packages.config", config);
            var sharedRepository           = new Mock <MockPackageRepository>().As <ISharedPackageRepository>();
            var packageReferenceRepository = new PackageReferenceRepository(fileSystem, sharedRepository.Object);

            // Act
            SemanticVersion version;
            bool            result = packageReferenceRepository.TryFindLatestPackageById("B", out version);

            // Assert
            Assert.True(result);
            Assert.Equal(new SemanticVersion("1.0"), version);
        }
示例#55
0
        public void ReadRegistry_Upgrade_ExistingVersion1()
        {
            string         dataLocation = @"mock:\registryDataFolder";
            MockFileSystem fileSystem   = new MockFileSystem(new MockDirectory(dataLocation, null, null));

            // Create a version 1 registry file
            fileSystem.WriteAllText(
                Path.Combine(dataLocation, RepoRegistry.RegistryName),
                @"1
{""EnlistmentRoot"":""c:\\code\\repo1"",""IsActive"":false}
{""EnlistmentRoot"":""c:\\code\\repo2"",""IsActive"":true}
");

            RepoRegistry registry = new RepoRegistry(new MockTracer(), fileSystem, dataLocation);

            registry.Upgrade();

            Dictionary <string, RepoRegistration> repos = registry.ReadRegistry();

            repos.Count.ShouldEqual(2);

            this.VerifyRepo(repos["c:\\code\\repo1"], expectedOwnerSID: null, expectedIsActive: false);
            this.VerifyRepo(repos["c:\\code\\repo2"], expectedOwnerSID: null, expectedIsActive: true);
        }
        public void AppendAllText_WithWeirdEncoding()
        {
            var linesToAppend = "first line Î♫";

            var subFolder = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            Func <IFileSystem, FileInfoBase> prepare = system =>
            {
                var tempPath       = system.Path.Combine(_fileSystemFixture.BaseDirectory, subFolder);
                var tempDirectory2 = system.Directory.CreateDirectory(tempPath);
                _output.WriteLine("Temporary Directory {0}", tempDirectory2.FullName);
                var realFilePath = tempPath + "\\willbecreated.txt";
                var result       = system.FileInfo.FromFileName(realFilePath);
                return(result);
            };

            var mockFileSystem = new MockFileSystem();
            var realFileSystem = new FileSystem();

            var realFile = prepare(realFileSystem);
            var mockFile = prepare(mockFileSystem);
            Action <IFileSystem, FileSystemType, FileInfoBase> execute = (fs, _, file) => fs.File.AppendAllText(file.FullName, linesToAppend, Encoding.UTF32);

            execute.OnFileSystemsWithParameter(realFileSystem, mockFileSystem, realFile, mockFile);
        }
        public void GetPackageTargetFrameworkReturnsNullIfPackageIdIsNotPresent()
        {
            // Arrange
            var repository = new Mock <MockPackageRepository>()
            {
                CallBase = true
            }.As <ISharedPackageRepository>();
            var packageA = PackageUtility.CreatePackage("A");

            repository.Object.AddPackage(packageA);
            var fileSystem = new MockFileSystem();

            fileSystem.AddFile("packages.config", @"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""A"" version=""1.0"" />
</packages>");
            var referenceRepository = new PackageReferenceRepository(fileSystem, repository.Object);

            // Act
            var targetFramework = referenceRepository.GetPackageTargetFramework("B");

            // Assert
            Assert.Null(targetFramework);
        }
            private static IEnumerable GetCasesForArgumentChecking(string path)
            {
                var          fileSystem            = new MockFileSystem();
                var          fileContentEnumerable = new List <string>();
                var          fileContentArray      = fileContentEnumerable.ToArray();
                TestDelegate writeEnumberable      = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable);
                TestDelegate writeEnumberableUtf32 = () => fileSystem.File.WriteAllLines(path, fileContentEnumerable, Encoding.UTF32);
                TestDelegate writeArray            = () => fileSystem.File.WriteAllLines(path, fileContentArray);
                TestDelegate writeArrayUtf32       = () => fileSystem.File.WriteAllLines(path, fileContentArray, Encoding.UTF32);

                // IEnumerable
                yield return(new TestCaseData(writeEnumberable)
                             .SetName("WriteAllLines(string, IEnumerable<string>) input: " + path));

                yield return(new TestCaseData(writeEnumberableUtf32)
                             .SetName("WriteAllLines(string, IEnumerable<string>, 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));
            }
        public void RemovePackageRemovesEntryFromPackagesConfig()
        {
            // Arrange
            var sharedRepository = new Mock <ISharedPackageRepository>();
            var fileSystem       = new MockFileSystem();

            fileSystem.AddFile("packages.config", @"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""A"" version=""1.0"" />
  <package id=""B"" version=""1.0"" />
</packages>");
            var referenceRepository = new PackageReferenceRepository(fileSystem, sharedRepository.Object);
            var package             = PackageUtility.CreatePackage("A");

            // Act
            referenceRepository.RemovePackage(package);

            // Assert
            Assert.True(fileSystem.FileExists("packages.config"));
            AssertConfig(@"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""B"" version=""1.0"" />
</packages>", fileSystem.ReadAllText("packages.config"));
        }
示例#60
-1
 public void Drives_On_Different_FileSystems_Are_Not_Equal()
 {
     var driveA = FileSystem.DriveDescribing("c:");
     var driveB = new MockFileSystem().DriveDescribing("c:");
     AssertEqualityNotEquals(driveA, driveB);
     AssertOperatorNotEquals(driveA, driveB);
 }