public void Mockfile_Create_ShouldCreateNewStream()
        {
            string fullPath = XFS.Path(@"c:\something\demo.txt");
            var fileSystem = new MockFileSystem();

            var sut = new MockFile(fileSystem);

            Assert.That(fileSystem.FileExists(fullPath), Is.False);

            sut.Create(fullPath).Close();

            Assert.That(fileSystem.FileExists(fullPath), Is.True);
        }
        public void MockFile_Move_ShouldMoveFileWithinMemoryFileSystem()
        {
            string sourceFilePath = XFS.Path(@"c:\something\demo.txt");
            string sourceFileContent = "this is some content";
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                {sourceFilePath, new MockFileData(sourceFileContent)},
                {XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] {0})}
            });

            string destFilePath = XFS.Path(@"c:\somethingelse\demo1.txt");

            fileSystem.File.Move(sourceFilePath, destFilePath);

            Assert.That(fileSystem.FileExists(destFilePath), Is.True);
            Assert.That(fileSystem.GetFile(destFilePath).TextContents, Is.EqualTo(sourceFileContent));
            Assert.That(fileSystem.FileExists(sourceFilePath), Is.False);
        }
        public void MockDirectory_CreateDirectory_ShouldCreatePlaceholderFileInMemoryFileSystem()
        {
            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { @"c:\foo.txt", new MockFileData("Demo text content") }
            });

            // Act
            fileSystem.Directory.CreateDirectory(@"c:\bar");

            // Assert
            Assert.IsTrue(fileSystem.FileExists(@"c:\bar\__PLACEHOLDER__.dir"));
        }
Exemple #4
0
        public void WriteConfigFile_FileDoesntExist_ShouldCreateFile()
        {
            // arrange
            var testFile   = Path.Combine(MockDirectory, @".tsqllintrc");
            var fileSystem = new MockFileSystem();

            fileSystem.AddDirectory(MockDirectory);
            var configFileGenerator = new ConfigFileGenerator(fileSystem);

            // act
            configFileGenerator.WriteConfigFile(testFile);

            // assert
            Assert.IsTrue(fileSystem.FileExists(testFile));
        }
        public void MockDirectory_CreateDirectory_ShouldCreateFolderInMemoryFileSystem()
        {
            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { @"c:\foo.txt", new MockFileData("Demo text content") }
            });

            // Act
            fileSystem.Directory.CreateDirectory(@"c:\bar");

            // Assert
            Assert.IsTrue(fileSystem.FileExists(@"c:\bar\"));
            Assert.IsTrue(fileSystem.AllDirectories.Any(d => d == @"c:\bar\"));
        }
        public void MockFile_OpenWrite_ShouldCreateNewFiles()
        {
            string filePath    = XFS.Path(@"c:\something\demo.txt");
            string fileContent = "this is some content";
            var    fileSystem  = new MockFileSystem();

            var bytes  = new UTF8Encoding(true).GetBytes(fileContent);
            var stream = fileSystem.File.OpenWrite(filePath);

            stream.Write(bytes, 0, bytes.Length);
            stream.Dispose();

            Assert.That(fileSystem.FileExists(filePath), Is.True);
            Assert.That(fileSystem.GetFile(filePath).TextContents, Is.EqualTo(fileContent));
        }
Exemple #7
0
        public void CallRemovePackageWillRemoveNupkgFile(string id, string version, string unexpectedPath)
        {
            // Arrange
            var fileSystem = new MockFileSystem("x:\\root");

            fileSystem.AddFile(unexpectedPath);
            var configFileSystem = new MockFileSystem();
            var repository       = new SharedPackageRepository(new DefaultPackagePathResolver(fileSystem), fileSystem, configFileSystem);

            // Act
            repository.RemovePackage(PackageUtility.CreatePackage(id, version));

            // Assert
            Assert.False(fileSystem.FileExists(unexpectedPath));
        }
Exemple #8
0
        public void TestStoreInitialize()
        {
            var fileSystem = new MockFileSystem();

            var gameobj = new GameObject("gameObj");

            var bp = gameobj.AddComponent <BehaviorParameters>();

            bp.BrainParameters.VectorObservationSize        = 3;
            bp.BrainParameters.NumStackedVectorObservations = 2;
            bp.BrainParameters.VectorActionDescriptions     = new[] { "TestActionA", "TestActionB" };
            bp.BrainParameters.ActionSpec = ActionSpec.MakeDiscrete(2, 2);

            gameobj.AddComponent <TestAgent>();

            Assert.IsFalse(fileSystem.Directory.Exists(k_DemoDirectory));

            var demoRec = gameobj.AddComponent <DemonstrationRecorder>();

            demoRec.Record                 = true;
            demoRec.DemonstrationName      = k_DemoName;
            demoRec.DemonstrationDirectory = k_DemoDirectory;
            var demoWriter = demoRec.LazyInitialize(fileSystem);

            Assert.IsTrue(fileSystem.Directory.Exists(k_DemoDirectory));
            Assert.IsTrue(fileSystem.FileExists(k_DemoDirectory + k_DemoName + k_ExtensionType));

            var agentInfo = new AgentInfo
            {
                reward = 1f,
                discreteActionMasks = new[] { false, true },
                done                = true,
                episodeId           = 5,
                maxStepReached      = true,
                storedVectorActions = new ActionBuffers(null, new int[] { 0, 1 }),
            };


            demoWriter.Record(agentInfo, new System.Collections.Generic.List <ISensor>());
            demoRec.Close();

            // Make sure close can be called multiple times
            demoWriter.Close();
            demoRec.Close();

            // Make sure trying to write after closing doesn't raise an error.
            demoWriter.Record(agentInfo, new System.Collections.Generic.List <ISensor>());
        }
        public void EntityBuilder_CreateEntity_createsEntityFile()
        {
            var solutionDirectory = @"c:\myrepo";
            var fileSystem        = new MockFileSystem();

            fileSystem.AddDirectory(solutionDirectory);

            var entity           = CannedGenerator.FakeBasicProduct();
            var expectedFilePath = ClassPathHelper.EntityClassPath(solutionDirectory, $"{entity.Name}.cs").FullClassPath;

            EntityBuilder.CreateEntity(solutionDirectory, entity, fileSystem);

            var exists = fileSystem.FileExists(expectedFilePath);

            exists.Should().BeTrue();
        }
Exemple #10
0
        public async Task UploadModel_ShouldSaveFile()
        {
            // Arrange
            var mockFileSystem = new MockFileSystem();
            var folderPath     = mockFileSystem.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".mlops");

            mockFileSystem.AddFile("model.zip", new MockFileData("test"));
            var sut = new LocalFileModelRepository(mockFileSystem);
            var expectedFilePath = mockFileSystem.Path.Combine(folderPath, $"{new Guid()}.zip");

            // Act
            await sut.UploadModelAsync(new Guid(), "model.zip");

            // Assert
            mockFileSystem.FileExists(expectedFilePath).Should().Be(true);
        }
Exemple #11
0
        public void DeleteFileAndEmptyParentDirectoriesCorrectly()
        {
            // Arrange
            var fileSystem = new MockFileSystem("x:\\");

            fileSystem.AddFile("foo\\bar\\hell\\x.txt");

            // Act
            fileSystem.DeleteFileAndParentDirectoriesIfEmpty("foo\\bar\\hell\\x.txt");

            // Assert
            Assert.False(fileSystem.FileExists("foo\\bar\\hell\\x.txt"));
            Assert.False(fileSystem.DirectoryExists("foo"));
            Assert.False(fileSystem.DirectoryExists("foo\\bar"));
            Assert.False(fileSystem.DirectoryExists("foo\\bar\\hell"));
        }
Exemple #12
0
        public void MockFile_AppendText_CreatesNewFileForAppendToNonExistingFile()
        {
            string filepath   = XFS.Path(@"c:\something\doesnt\exist.txt");
            var    filesystem = new MockFileSystem(new Dictionary <string, MockFileData>());

            var stream = filesystem.File.AppendText(filepath);

            stream.Write("New too!");
            stream.Flush();
            stream.Close();

            var file = filesystem.GetFile(filepath);

            Assert.That(file.TextContents, Is.EqualTo("New too!"));
            Assert.That(filesystem.FileExists(filepath));
        }
        public void InstallCommandUsesMultipleSourcesIfSpecified()
        {
            // Arrange
            var fileSystem     = new MockFileSystem();
            var installCommand = new TestInstallCommand(GetFactory(), GetSourceProvider(), fileSystem);

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

            // Act
            installCommand.ExecuteCommand();

            // Assert
            Assert.True(fileSystem.FileExists(@"Baz.0.7\Baz.0.7.nupkg"));
        }
        public void OutputProcessedOrderCsvData()
        {
            const string inputDir      = @"c:\root\in";
            const string inputFileName = "myfile.csv";
            var          inputFilePath = Path.Combine(inputDir, inputFileName);

            const string outputDir      = @"c:\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.Append("44, 300003, Cap, V");

            var mockInputFile = new MockFileData(csvLines.ToString());


            var mockFileSystem = new MockFileSystem();

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


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

            sut.Process();


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

            var processedFile = mockFileSystem.GetFile(outputFilePath);

            var lines = processedFile.TextContents.SplitLines();

            //Assert.Equal("OrderNumber,Customer,Amount", lines[0]);
            //Assert.Equal("42,100001,2", lines[1]);
            //Assert.Equal("43,200002,1", lines[2]);
            //Assert.Equal("44,300003,5", lines[3]);

            Approvals.Verify(processedFile.TextContents);
        }
Exemple #15
0
        public void TrySerializeAndDeserializeEmptyTree()
        {
            var fileSystem = new MockFileSystem();

            fileSystem.Directory.CreateDirectory(Directory.GetCurrentDirectory());
            string path = Path.Combine(Directory.GetCurrentDirectory(), "binary_search_tree.dat");

            var serializer = new BinarySearchTreePersistable <int, int>(fileSystem);

            serializer.Serialize(path, new BinarySearchTree <int, int>());

            Assert.True(fileSystem.FileExists(path));

            var treeDeserialized = (BinarySearchTree <int, int>)serializer.Deserialize(path);

            Assert.True(treeDeserialized.Count == 0);
        }
        public void WriteConfigFile_FileExists_ShouldCreateFile()
        {
            // arrange
            var testFile   = Path.Combine(MockDirectory, @".tsqllintrc");
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { testFile, new MockFileData("{}") },
            });

            var configFileGenerator = new ConfigFileGenerator(fileSystem);

            // act
            configFileGenerator.WriteConfigFile(testFile);

            // assert
            Assert.IsTrue(fileSystem.FileExists(testFile));
        }
        public void MockFile_Move_SameSourceAndTargetIsANoOp()
        {
            string sourceFilePath    = XFS.Path(@"c:\something\demo.txt");
            string sourceFileContent = "this is some content";
            var    fileSystem        = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { sourceFilePath, new MockFileData(sourceFileContent) },
                { XFS.Path(@"c:\somethingelse\dummy.txt"), new MockFileData(new byte[] { 0 }) }
            });

            string destFilePath = XFS.Path(@"c:\somethingelse\demo.txt");

            fileSystem.File.Move(sourceFilePath, destFilePath);

            Assert.That(fileSystem.FileExists(destFilePath), Is.True);
            Assert.That(fileSystem.GetFile(destFilePath).TextContents, Is.EqualTo(sourceFileContent));
        }
        public void MarkPackageDirectoryForDeletionDoesNotAddDeletemeFileWhenDirectoryRemovalSuccessful()
        {
            // Arrange
            IPackage package              = NuGet.Test.PackageUtility.CreatePackage("foo", "1.0.0");
            var      fileSystem           = new MockFileSystem();
            var      pathResolver         = new DefaultPackagePathResolver(fileSystem);
            string   packageDirectoryPath = pathResolver.GetPackageDirectory(package);

            var deleteOnRestartManager = new DeleteOnRestartManager(() => fileSystem, () => pathResolver);

            // Act
            deleteOnRestartManager.MarkPackageDirectoryForDeletion(package);

            // Assert
            Assert.False(fileSystem.DirectoryExists(packageDirectoryPath));
            Assert.False(fileSystem.FileExists(packageDirectoryPath + _deletionMarkerSuffix));
        }
Exemple #19
0
        public void UninstallingSatellitePackageRemovesCollidingRuntimeFiles()
        {
            // Arrange
            // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the
            // local suffix convention.
            var runtimePackage = PackageUtility.CreatePackage(
                "foo", "1.0.0",
                content: Enumerable.Empty <string>(),
                assemblyReferences: new[] { @"lib\ja-jp\collision.txt" });

            var satellitePackage = PackageUtility.CreatePackage(
                "foo.ja-jp", "1.0.0", language: "ja-jp",
                content: Enumerable.Empty <string>(),
                satelliteAssemblies: new[] { @"lib\ja-jp\collision.txt" },
                dependencies: new[] { new PackageDependency("foo", VersionUtility.ParseVersionSpec("[1.0.0]")) });

            var packagesFolder   = new MockFileSystem(@"c:\packagesFolder");
            var sharedRepository = new MockSharedPackageRepository2();
            var sourceRepository = new MockPackageRepository();
            var packageManager   = new PackageManager(sourceRepository, new DefaultPackagePathResolver(packagesFolder), packagesFolder, sharedRepository);

            sourceRepository.AddPackage(runtimePackage);
            sourceRepository.AddPackage(satellitePackage);

            var projectSystem    = new MockProjectSystem();
            var projectLocalRepo = new PackageReferenceRepository(
                new MockFileSystem(@"c:\project"),
                "projectName",
                sharedRepository);
            var projectManager = new ProjectManager(
                packageManager,
                packageManager.PathResolver,
                projectSystem,
                projectLocalRepo);

            // Act
            Install("foo", projectManager);
            Install("foo.ja-jp", projectManager);

            Uninstall("foo.ja-jp", packageManager, projectManager);

            // Assert
            Assert.Equal(0, packagesFolder.Paths.Count);
            Assert.False(packagesFolder.FileExists(@"foo.1.0.0\lib\ja-jp\collision.txt"));
        }
Exemple #20
0
        public void TestConfigCanMerge()
        {
            var now         = DateTime.Now;
            var mockE1      = new Entry(@"c:\dir2\", 1, now, false);
            var mockE2      = new Entry(@"c:\dir2\file3", 10, now, true);
            var mockE3      = new Entry(@"c:\dir3\file1", 101, now, true);
            var mockContent = string.Join(Environment.NewLine,
                                          mockE1.ToString(),
                                          mockE2.ToString(),
                                          mockE3.ToString());

            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> {
                { FileSystemConfigPath, new MockFileData(mockContent) }
            });

            var db  = new Database(fileSystem);
            var fsp = new Provider("FileSystem");

            db.Providers.Add("FileSystem", fsp);
            now = now.AddSeconds(1);
            var e1 = new Entry(@"c:\dir1\", 12, now, false);
            var e2 = new Entry(@"c:\dir1\file2", 34, now, true);
            var e3 = new Entry(@"c:\dir2\file3", 11, now, true);
            var e4 = new Entry(@"c:\dir3\file1", 11, now, true);

            fsp.Add(e1);
            fsp.Add(e2);
            fsp.Add(e3);
            fsp.Add(e4);
            Assert.IsTrue(fsp.Remove(e4.FullPath));
            db.Save(100);

            var fsFileName = System.IO.Path.Combine(db.ConfigDir, $"{Database.ConfigFilePrefix}.FileSystem.txt");

            Assert.IsTrue(fileSystem.FileExists(FileSystemConfigPath));
            var configContent = fileSystem.File.ReadAllText(fsFileName);

            StringAssert.Contains(e1 + Environment.NewLine, configContent);
            StringAssert.Contains(e2 + Environment.NewLine, configContent);
            StringAssert.Contains(e3 + Environment.NewLine, configContent);
            StringAssert.Contains(mockE1 + Environment.NewLine, configContent);
            StringAssert.DoesNotContain(mockE2 + Environment.NewLine, configContent);
            StringAssert.DoesNotContain(mockE3 + Environment.NewLine, configContent);
            StringAssert.DoesNotContain(e4 + Environment.NewLine, configContent);
        }
Exemple #21
0
        public void CallAddPackageWillNotCreatePackageConfigEntryToPackageConfig()
        {
            // Arrange
            var fileSystem = new Mock <MockFileSystem>()
            {
                CallBase = true
            };

            fileSystem.Setup(m => m.Root).Returns(@"c:\foo\");
            var configFileSystem = new MockFileSystem();
            var repository       = new SharedPackageRepository(new DefaultPackagePathResolver(fileSystem.Object), fileSystem.Object, configFileSystem);

            // Act
            repository.AddPackage(PackageUtility.CreatePackage("A", "2.0"));

            // Assert
            Assert.False(configFileSystem.FileExists("packages.config"));
        }
        public async Task ExecutesCorrectly()
        {
            var configFile      = new ConfigFile("C:\\SFM");
            var fs              = new MockFileSystem();
            var revisionManager = new RevisionManager(configFile, fs);

            fs.CreateDirectory("C:\\SFM");
            fs.CreateDirectory("C:\\SFM\\ponysfm");

            fs.CreateDirectory("C:\\tmp");
            fs.CreateDirectory("C:\\tmp\\models");
            fs.CreateFile("C:\\tmp\\models\\pony.vtf");

            fs.CreateDirectory("C:\\tmp\\materials");
            fs.CreateFile("C:\\tmp\\materials\\pony.vmt");

            var files = new List <RevisionFileEntry>
            {
                RevisionFileEntry.FromFile("C:\\tmp\\models\\pony.vtf", fs),
                RevisionFileEntry.FromFile("C:\\tmp\\materials\\pony.vmt", fs)
            };

            var revision = new Revision(1, files);

            await revisionManager.InstallRevision(revision, "C:\\tmp", null);

            Assert.IsTrue(revisionManager.VerifyInstalled(revision, null));

            var list = new List <int> {
                1
            };

            var deinstallationPresenter = new DeinstallationPresenter(revisionManager, list);

            await deinstallationPresenter.Execute();

            Assert.IsFalse(revisionManager.VerifyInstalled(revision, null));

            foreach (var file in revision.Files)
            {
                Assert.IsFalse(fs.FileExists(file.Path));
            }
        }
        public async Task TestAddFileNothingExists()
        {
            var fs      = new MockFileSystem();
            var options = new ServerFilesOptions {
                Directory = "D:\\files", TempDirectory = "D:\\temp"
            };

            var filesManager   = new ServerFilesManager(fs, Options.Create(options), GetNullLogger());
            var testFileStream = new MemoryStream(_testFile1);

            // act
            var storedFile = await filesManager.AddFile(testFileStream);

            // assert
            Assert.Equal(_testFile1Hash.ToString(), storedFile.FileHash);
            Assert.Equal(_testFile1.Length, storedFile.Length);
            Assert.True(fs.FileExists($"{options.Directory}\\{_testFile1Hash}"));
            Assert.Empty(fs.Directory.GetFiles(options.TempDirectory));
        }
Exemple #24
0
        public void TestStoreInitalize()
        {
            var fileSystem = new MockFileSystem();
            var demoStore  = new DemonstrationStore(fileSystem);

            Assert.IsFalse(fileSystem.Directory.Exists(DemoDirecory));

            var brainParameters = new BrainParameters
            {
                vectorObservationSize        = 3,
                numStackedVectorObservations = 2,
                cameraResolutions            = new [] { new Resolution() },
                vectorActionDescriptions     = new [] { "TestActionA", "TestActionB" },
                vectorActionSize             = new [] { 2, 2 },
                vectorActionSpaceType        = SpaceType.discrete
            };

            demoStore.Initialize(DemoName, brainParameters, "TestBrain");

            Assert.IsTrue(fileSystem.Directory.Exists(DemoDirecory));
            Assert.IsTrue(fileSystem.FileExists(DemoDirecory + DemoName + ExtensionType));

            var agentInfo = new AgentInfo
            {
                reward             = 1f,
                visualObservations = new List <Texture2D>(),
                actionMasks        = new [] { false, true },
                done                     = true,
                id                       = 5,
                maxStepReached           = true,
                memories                 = new List <float>(),
                stackedVectorObservation = new List <float>()
                {
                    1f, 1f, 1f
                },
                storedTextActions   = "TestAction",
                storedVectorActions = new [] { 0f, 1f },
                textObservation     = "TestAction",
            };

            demoStore.Record(agentInfo);
            demoStore.Close();
        }
        public void CallingCycloneDX_CreatesBomFromPackagesFile()
        {
            var mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { XFS.Path(@"c:\SolutionPath\Project\packages.config"), Helpers.GetPackagesFileWithPackageReferences(
                      new List <NugetPackage> {
                        new NugetPackage {
                            Name = "Package1", Version = "1.2.3"
                        },
                        new NugetPackage {
                            Name = "Package2", Version = "1.2.3"
                        },
                        new NugetPackage {
                            Name = "Package3", Version = "1.2.3"
                        },
                    }) },
            });
            var mockHttpClient = Helpers.GetNugetMockHttpClient(new List <NugetPackage>
            {
                new NugetPackage {
                    Name = "Package1", Version = "1.2.3"
                },
                new NugetPackage {
                    Name = "Package2", Version = "1.2.3"
                },
                new NugetPackage {
                    Name = "Package3", Version = "1.2.3"
                },
            });

            Program.fileSystem = mockFileSystem;
            Program.httpClient = mockHttpClient;
            var args = new string[]
            {
                XFS.Path(@"c:\SolutionPath\Project\packages.config"),
                "-o", XFS.Path(@"c:\SolutionPath")
            };

            var exitCode = Program.Main(args);

            Assert.Equal((int)ExitCode.OK, exitCode);
            Assert.True(mockFileSystem.FileExists(XFS.Path(@"c:\SolutionPath\bom.xml")));
        }
Exemple #26
0
        public async System.Threading.Tasks.Task BlogPostSaveTest(KeyValuePair <string, MockFileData> data, string fileName)
        {
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>()
            {
                { data.Key, data.Value }
            });
            var loader = new BlogPostLoader(fileSystem, new PostSerializer());

            var item = new BlogItem {
                Title = "title", Content = "x", Tags = new string[] { "a", "b", "c" }
            };
            await loader.SaveBlogItem(item, fileName).ConfigureAwait(true);

            Assert.True(fileSystem.FileExists(AppPathInfo.BlogInputPath + fileName));
            string[] fileContents = fileSystem.File.ReadAllLines(AppPathInfo.BlogInputPath + fileName);
            Assert.Equal("[a,b,c]", fileContents[0]);
            Assert.Equal("# title", fileContents[1]);
            Assert.Equal("x", fileContents[2]);
        }
        public void ShouldWriteJsonToFile()
        {
            var mockProcess    = new Mock <IWebbrowserOpener>();
            var mockFileSystem = new MockFileSystem();
            var options        = new StrykerOptions
            {
                Thresholds = new Thresholds {
                    High = 80, Low = 60, Break = 0
                },
                OutputPath     = Directory.GetCurrentDirectory(),
                ReportFileName = "mutation-report"
            };
            var reporter = new HtmlReporter(options, mockFileSystem, processWrapper: mockProcess.Object);

            reporter.OnAllMutantsTested(JsonReportTestHelper.CreateProjectWith());
            var reportPath = Path.Combine(options.OutputPath, "reports", $"mutation-report.html");

            mockFileSystem.FileExists(reportPath).ShouldBeTrue($"Path {reportPath} should exist but it does not.");
        }
Exemple #28
0
        public void ReadsFile()
        {
            // Create Mock test file
            var mockFile = new MockFileData("Lorem ipsum dolor sit.");

            // Setup Mock File System with test file
            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddDirectory("tests");
            mockFileSystem.AddFile(@"tests/text.txt", mockFile);

            var fileIngestService = new FileIngestService(@"tests/text.txt", mockFileSystem);
            var file = fileIngestService.GetFileAsText();

            Assert.True(mockFileSystem.FileExists(@"tests/text.txt"));
            //Assert.Equal("Lorem ipsum dolor sit.", file);

            Approvals.Verify(file); // Uses app `Beyond Compare` or system diff tool to compare file with approved version
        }
        public void InstallCommandInstallsPrereleasePackageIfFlagIsSpecified()
        {
            // Arrange
            var fileSystem     = new MockFileSystem();
            var installCommand = new TestInstallCommand(GetFactory(), GetSourceProvider(), fileSystem)
            {
                Prerelease = true
            };

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

            // Act
            installCommand.ExecuteCommand();

            // Assert
            Assert.True(fileSystem.FileExists(@"Baz.0.8.1-alpha\Baz.0.8.1-alpha.nupkg"));
        }
Exemple #30
0
        public void MockFile_OpenWrite_ShouldOverwriteExistingFiles()
        {
            string filePath         = XFS.Path(@"c:\something\demo.txt");
            string startFileContent = "this is some content";
            string endFileContent   = "this is some other content";
            var    fileSystem       = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { filePath, new MockFileData(startFileContent) }
            });

            var bytes  = new UTF8Encoding(true).GetBytes(endFileContent);
            var stream = fileSystem.File.OpenWrite(filePath);

            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            Assert.That(fileSystem.FileExists(filePath), Is.True);
            Assert.That(fileSystem.GetFile(filePath).TextContents, Is.EqualTo(endFileContent));
        }
Exemple #31
0
        public void OutputProcessedPolicyXmlData()
        {
            // Create mock file system to test program
            const string inputDir      = @"c:\root\in";
            const string inputFileName = "myFile.csv";
            string       inputFilePath = Path.Combine(inputDir, inputFileName);

            const string outputDir      = @"c:\root\out";
            const string outputFileName = "myFileOut.xml";
            string       outputFilePath = Path.Combine(outputDir, outputFileName);

            // Create dummy test data to test program produces correct values
            StringBuilder csvLines = new StringBuilder();

            csvLines.AppendLine("policy_number,policy_start_date,premiums,membership,discretionary_bonus,uplift_percentage");
            csvLines.AppendLine("A100001,01/06/1986,10000,Y,1000,40");
            csvLines.AppendLine("A100002,01/01/1990,12500,N,1350,37.5");
            csvLines.AppendLine("A100003,31/12/1989,15250,N,1600,42");
            csvLines.AppendLine("B100001,01/01/1995,12000,Y,2000,41");
            csvLines.AppendLine("B100002,01/01/1970,18000,N,3000,43");
            csvLines.AppendLine("B100003,20/07/1969,20000,Y,4000,45");
            csvLines.AppendLine("C100001,01/01/1992,13000,N,1000,42");
            csvLines.AppendLine("C100002,31/12/1989,15000,Y,2000,44");
            csvLines.Append("C100003,01/01/1990,17000,Y,3000,46");

            MockFileData mockInputFile = new MockFileData(csvLines.ToString());

            MockFileSystem mockFileSystem = new MockFileSystem();

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

            CsvFileProcessor csvFileProcessor = new CsvFileProcessor(inputFilePath, outputFilePath, mockFileSystem);

            csvFileProcessor.Process();

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

            MockFileData processedFile = mockFileSystem.GetFile(outputFilePath);

            Approvals.Verify(processedFile.TextContents);
        }
Exemple #32
0
        public void AddConnectionString_Creates_App_Settings_File()
        {
            //Arrange
            var fs      = new MockFileSystem();
            var testObj = GetTestObject(fs);

            //Act
            testObj.AddConnectionString("MyDbContext", "MyDbContext-NewGuid", false);

            //Assert
            string expected        = @"{
  ""ConnectionStrings"": {
    ""MyDbContext"": ""Server=(localdb)\\mssqllocaldb;Database=MyDbContext-NewGuid;Trusted_Connection=True;MultipleActiveResultSets=true""
  }
}";
            var    appSettingsPath = Path.Combine(AppBase, "appsettings.json");

            fs.FileExists(appSettingsPath);
            Assert.Equal(expected, fs.ReadAllText(appSettingsPath), ignoreCase: false, ignoreLineEndingDifferences: true);
        }
        public void InstallCommandDoesNotUseLocalCacheIfNoCacheIsTrue()
        {
            // Arrange
            var fileSystem     = new MockFileSystem();
            var localCache     = new Mock <IPackageRepository>(MockBehavior.Strict);
            var installCommand = new TestInstallCommand(GetFactory(), GetSourceProvider(), fileSystem, machineCacheRepository: localCache.Object)
            {
                NoCache = true
            };

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

            // Act
            installCommand.ExecuteCommand();

            // Assert
            Assert.True(fileSystem.FileExists(@"Baz.0.7\Baz.0.7.nupkg"));
            localCache.Verify(c => c.GetPackages(), Times.Never());
        }
        public void MockDirectory_CreateDirectory_ShouldCreateFolderInMemoryFileSystem()
        {
            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { XFS.Path(@"c:\foo.txt"), new MockFileData("Demo text content") }
            });

            // Act
            fileSystem.Directory.CreateDirectory(XFS.Path(@"c:\bar"));

            // Assert
            Assert.IsTrue(fileSystem.FileExists(XFS.Path(@"c:\bar\")));
            Assert.IsTrue(fileSystem.AllDirectories.Any(d => d == XFS.Path(@"c:\bar\")));
        }
        public void MockFile_Delete_ShouldRemoveFileFromFileSystem()
        {
            const string fullPath = @"c:\something\demo.txt";
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { fullPath, new MockFileData("Demo text content") }
            });

            var file = new MockFile(fileSystem);

            file.Delete(fullPath);

            Assert.That(fileSystem.FileExists(fullPath), Is.False);
        }
        public void MockFile_OpenWrite_ShouldOverwriteExistingFiles()
        {
            const string filePath = @"c:\something\demo.txt";
            const string startFileContent = "this is some content";
            const string endFileContent = "this is some other content";
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                {filePath, new MockFileData(startFileContent)}
            });

            var bytes = new UTF8Encoding(true).GetBytes(endFileContent);
            var stream = fileSystem.File.OpenWrite(filePath);
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            Assert.That(fileSystem.FileExists(filePath), Is.True);
            Assert.That(fileSystem.GetFile(filePath).TextContents, Is.EqualTo(endFileContent));
        }
        public void MockFile_OpenWrite_ShouldCreateNewFiles() {
            const string filePath = @"c:\something\demo.txt";
            const string fileContent = "this is some content";
            var fileSystem = new MockFileSystem();

            var bytes = new UTF8Encoding(true).GetBytes(fileContent);
            var stream = fileSystem.File.OpenWrite(filePath);
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            Assert.That(fileSystem.FileExists(filePath), Is.True);
            Assert.That(fileSystem.GetFile(filePath).TextContents, Is.EqualTo(fileContent));
        }
        public void Mockfile_Create_ShouldCreateNewStream()
        {
            const string fullPath = @"c:\something\demo.txt";
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>());

            var sut = new MockFile(fileSystem);

            Assert.That(fileSystem.FileExists(fullPath), Is.False);

            sut.Create(fullPath).Close();

            Assert.That(fileSystem.FileExists(fullPath), Is.True);
        }
        public void MockFile_AppendText_CreatesNewFileForAppendToNonExistingFile()
        {
            string filepath = XFS.Path(@"c:\something\doesnt\exist.txt");
            var filesystem = new MockFileSystem(new Dictionary<string, MockFileData>());

            var stream = filesystem.File.AppendText(filepath);

            stream.Write("New too!");
            stream.Flush();
            stream.Close();

            var file = filesystem.GetFile(filepath);
            Assert.That(file.TextContents, Is.EqualTo("New too!"));
            Assert.That(filesystem.FileExists(filepath));
        }
        public void GetTempFileName_Called_CreatesEmptyFileInTempDirectory()
        {
            //Arrange
            var fileSystem = new MockFileSystem();
            var mockPath = new MockPath(fileSystem);

            //Act
            var result = mockPath.GetTempFileName();

            Assert.True(fileSystem.FileExists(result));
            Assert.AreEqual(0, fileSystem.FileInfo.FromFileName(result).Length);
        }
        public void GetTempFileName_Called_CreatesEmptyFileInTempDirectory()
        {
            //Arrange
            var fileSystem = new MockFileSystem();
            var mockPath = new MockPath(fileSystem);

            //Creating directory explicitly because in normal system Tempory path always exist.
            fileSystem.Directory.CreateDirectory(mockPath.GetTempPath());

            //Act
            var result = mockPath.GetTempFileName();

            Assert.True(fileSystem.FileExists(result));
            Assert.AreEqual(0, fileSystem.FileInfo.FromFileName(result).Length);
        }