public InputFileResolverTests()
        {
            _currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            _filesystemRoot   = Path.GetPathRoot(_currentDirectory);
            _basePath         = Path.Combine(_filesystemRoot, "TestProject");

            sourceFile                     = File.ReadAllText(_currentDirectory + "/TestResources/ExampleSourceFile.cs");
            testProjectPath                = FilePathUtils.ConvertPathSeparators(Path.Combine(_filesystemRoot, "TestProject", "TestProject.csproj"));
            projectUnderTestPath           = FilePathUtils.ConvertPathSeparators(Path.Combine(_filesystemRoot, "ExampleProject", "ExampleProject.csproj"));
            defaultTestProjectFileContents = @"<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>";
        }
示例#2
0
        public void StrykerCLI_WithConfigFile_ShouldStartStrykerWithConfigFileOptions(string argName)
        {
            var            fileToExclude = FilePathUtils.ConvertPathSeparators("./Recursive.cs");
            StrykerOptions actualOptions = null;
            var            runResults    = new StrykerRunResult(new StrykerOptions(), 0.3M);

            var mock = new Mock <IStrykerRunner>(MockBehavior.Strict);

            mock.Setup(x => x.RunMutationTest(It.IsAny <StrykerOptions>()))
            .Callback <StrykerOptions>((c) => actualOptions = c)
            .Returns(runResults)
            .Verifiable();

            var target = new StrykerCLI(mock.Object);

            target.Run(new string[] { argName, "filled-stryker-config.json" });

            mock.VerifyAll();

            actualOptions.AdditionalTimeoutMS.ShouldBe(9999);
            actualOptions.LogOptions.LogLevel.ShouldBe(LogEventLevel.Verbose);
            actualOptions.ProjectUnderTestNameFilter.ShouldBe("ExampleProject.csproj");
            actualOptions.Reporters.ShouldHaveSingleItem();
            actualOptions.Reporters.ShouldContain(Reporter.ConsoleReport);
            actualOptions.ConcurrentTestrunners.ShouldBe(1);
            actualOptions.Thresholds.Break.ShouldBe(20);
            actualOptions.Thresholds.Low.ShouldBe(30);
            actualOptions.Thresholds.High.ShouldBe(40);
            actualOptions.FilesToExclude.ShouldHaveSingleItem();
            actualOptions.FilesToExclude.ShouldContain(fileToExclude);
        }
示例#3
0
        private void InitializeVsTestConsole()
        {
            var testBinariesPath = _projectInfo.GetTestBinariesPath();

            if (!_fileSystem.File.Exists(testBinariesPath))
            {
                throw new ApplicationException($"The test project binaries could not be found at {testBinariesPath}, exiting...");
            }

            var testBinariesLocation = Path.GetDirectoryName(testBinariesPath);

            _sources = new List <string>()
            {
                FilePathUtils.ConvertPathSeparators(testBinariesPath)
            };

            try
            {
                _vsTestConsole.StartSession();
                _vsTestConsole.InitializeExtensions(new List <string>
                {
                    testBinariesLocation,
                    _vsTestHelper.GetDefaultVsTestExtensionsPath(_vsTestHelper.GetCurrentPlatformVsTestToolPath())
                });
            }
            catch (Exception e)
            {
                throw new ApplicationException("Stryker failed to connect to vstest.console", e);
            }

            DiscoverTests();
        }
示例#4
0
        public void StrykerCLI_WithFilesToExcludeSet_ShouldPassFilesToExcludeToStryker(string argName)
        {
            var              mock          = new Mock <IStrykerRunner>(MockBehavior.Strict);
            StrykerOptions   actualOptions = null;
            StrykerRunResult runResults    = new StrykerRunResult(new StrykerOptions(), 0.1M);

            mock.Setup(x => x.RunMutationTest(It.IsAny <StrykerOptions>()))
            .Callback <StrykerOptions>((c) => actualOptions = c)
            .Returns(runResults)
            .Verifiable();

            var target = new StrykerCLI(mock.Object);

            target.Run(new[] { argName, @"['./StartUp.cs','./ExampleDirectory/Recursive.cs', '.\\ExampleDirectory/Recursive2.cs']" });

            var firstFileToExclude  = FilePathUtils.ConvertPathSeparators("./StartUp.cs");
            var secondFileToExclude = FilePathUtils.ConvertPathSeparators("./ExampleDirectory/Recursive.cs");
            var thirdFileToExclude  = FilePathUtils.ConvertPathSeparators(@".\ExampleDirectory/Recursive2.cs");

            var filesToExclude = actualOptions.FilesToExclude.ToArray();

            filesToExclude.Length.ShouldBe(3);
            filesToExclude.ShouldContain(firstFileToExclude);
            filesToExclude.ShouldContain(secondFileToExclude);
            filesToExclude.ShouldContain(thirdFileToExclude);
        }
示例#5
0
        /// <summary>
        /// Finds the referencedProjects and looks for all files that should be mutated in those projects
        /// </summary>
        public ProjectInfo ResolveInput(string currentDirectory, string projectName)
        {
            var projectFile          = ScanProjectFile(currentDirectory);
            var currentProjectInfo   = ReadProjectFile(projectFile, projectName);
            var projectReferencePath = FilePathUtils.ConvertPathSeparators(currentProjectInfo.ProjectReference);

            var projectUnderTestPath = Path.GetDirectoryName(Path.GetFullPath(Path.Combine(currentDirectory, projectReferencePath)));
            var projectReference     = Path.Combine(projectUnderTestPath, Path.GetFileName(projectReferencePath));
            var projectFilePath      = Path.GetFullPath(projectReference);
            var projectUnderTestInfo = FindProjectUnderTestAssemblyName(projectFilePath);
            var inputFiles           = new FolderComposite();

            foreach (var dir in ExtractProjectFolders(projectFilePath))
            {
                var folder = _fileSystem.Path.Combine(Path.GetDirectoryName(projectFilePath), dir);

                _logger.LogDebug($"Scanning {folder}");
                if (!_fileSystem.Directory.Exists(folder))
                {
                    throw new DirectoryNotFoundException($"Can't find {folder}");
                }
                inputFiles.Add(FindInputFiles(folder));
            }

            return(new ProjectInfo()
            {
                TestProjectPath = currentDirectory,
                TestProjectFileName = Path.GetFileName(projectFile),
                TargetFramework = currentProjectInfo.TargetFramework,
                ProjectContents = inputFiles,
                ProjectUnderTestPath = projectUnderTestPath,
                ProjectUnderTestAssemblyName = projectUnderTestInfo ?? Path.GetFileNameWithoutExtension(projectReferencePath),
                ProjectUnderTestProjectName = Path.GetFileNameWithoutExtension(projectReferencePath),
            });
        }
示例#6
0
        public DotnetTestRunner(string path, IProcessExecutor processProxy, OptimizationFlags flags, ILogger logger = null)
        {
            _logger = logger ?? ApplicationLogging.LoggerFactory.CreateLogger <DotnetTestRunner>();

            _flags           = flags;
            _path            = Path.GetDirectoryName(FilePathUtils.ConvertPathSeparators(path));
            _processExecutor = processProxy;
            CoverageMutants  = new TestCoverageInfos();
        }
示例#7
0
 private IEnumerable <string> ValidateFilesToExclude(string[] filesToExclude)
 {
     foreach (var excludedFile in filesToExclude ?? Enumerable.Empty <string>())
     {
         // The logger is not yet available here. The paths will be validated in the InputFileResolver
         var platformFilePath = FilePathUtils.ConvertPathSeparators(excludedFile);
         yield return(platformFilePath);
     }
 }
示例#8
0
        // initialize the test context and mock objects
        public VsTestRunnersShould()
        {
            var currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var filesystemRoot   = Path.GetPathRoot(currentDirectory);

            var          sourceFile                     = File.ReadAllText(currentDirectory + "/TestResources/ExampleSourceFile.cs");
            var          testProjectPath                = FilePathUtils.ConvertPathSeparators(Path.Combine(filesystemRoot, "TestProject", "TestProject.csproj"));
            var          projectUnderTestPath           = FilePathUtils.ConvertPathSeparators(Path.Combine(filesystemRoot, "ExampleProject", "ExampleProject.csproj"));
            const string defaultTestProjectFileContents = @"<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>";

            _testAssemblyPath = Path.Combine(filesystemRoot, "_firstTest", "bin", "Debug", "TestApp.dll");
            var firstTest  = new TestCase("myFirsTest", new Uri("exec://nunit"), _testAssemblyPath);
            var secondTest = new TestCase("myOtherTest", new Uri("exec://nunit"), _testAssemblyPath);

            _targetProject = new ProjectInfo()
            {
                TestProjectAnalyzerResult = new ProjectAnalyzerResult(null, null)
                {
                    AssemblyPath    = _testAssemblyPath,
                    TargetFramework = "toto"
                },
                ProjectUnderTestAnalyzerResult = new ProjectAnalyzerResult(null, null)
                {
                    AssemblyPath    = Path.Combine(filesystemRoot, "app", "bin", "Debug", "AppToTest.dll"),
                    TargetFramework = "toto"
                }
            };
            _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) },
                { _testAssemblyPath, new MockFileData("Bytecode") },
                { Path.Combine(filesystemRoot, "app", "bin", "Debug", "AppToTest.dll"), new MockFileData("Bytecode") },
            });

            _mutant = new Mutant {
                Id = 1
            };
            _testCases = new [] { firstTest, secondTest };
        }
示例#9
0
        private string ValidateSolutionPath(string basePath, string solutionPath)
        {
            if (string.IsNullOrWhiteSpace(basePath) || string.IsNullOrWhiteSpace(solutionPath))
            {
                return(null);
            }

            solutionPath = FilePathUtils.ConvertPathSeparators(Path.Combine(basePath, solutionPath));

            return(solutionPath);
        }
示例#10
0
        private IVsTestConsoleWrapper PrepareVsTestConsole()
        {
            var logPath = FilePathUtils.ConvertPathSeparators(Path.Combine(_options.OutputPath, "vstest", "vstest-log.txt"));

            _fileSystem.Directory.CreateDirectory(Path.GetDirectoryName(logPath));

            return(new VsTestConsoleWrapper(_vsTestHelper.GetCurrentPlatformVsTestToolPath(), new ConsoleParameters
            {
                TraceLevel = DetermineTraceLevel(),
                LogFilePath = logPath
            }));
        }
示例#11
0
        private string ValidateOutputPath(string basePath)
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                return("");
            }

            var outputPath = Path.Combine(basePath, "StrykerOutput", DateTime.Now.ToString("yyyy-MM-dd.HH-mm-ss"));

            _fileSystem.Directory.CreateDirectory(FilePathUtils.ConvertPathSeparators(outputPath));

            return(outputPath);
        }
示例#12
0
        public IEnumerable <string> FindSharedProjects(XDocument document)
        {
            var importStatements = document.Elements().Descendants()
                                   .Where(projectElement => string.Equals(projectElement.Name.LocalName, "Import", StringComparison.OrdinalIgnoreCase));

            var sharedProjects = importStatements
                                 .SelectMany(importStatement => importStatement.Attributes(
                                                 XName.Get("Project")))
                                 .Select(importFileLocation => FilePathUtils.ConvertPathSeparators(importFileLocation.Value))
                                 .Where(importFileLocation => importFileLocation.EndsWith(".projitems"));

            return(sharedProjects);
        }
示例#13
0
        public string DetermineProjectUnderTest(IEnumerable <string> projectReferences, string projectUnderTestNameFilter)
        {
            var referenceChoise = BuildReferenceChoise(projectReferences);

            var stringBuilder = new StringBuilder();

            if (string.IsNullOrEmpty(projectUnderTestNameFilter))
            {
                if (projectReferences.Count() > 1)
                {
                    stringBuilder.AppendLine("Test project contains more than one project references. Please add the --project-file=[projectname] argument to specify which project to mutate.");
                    stringBuilder.Append(referenceChoise);
                    AppendExampleIfPossible(stringBuilder, projectReferences);

                    throw new StrykerInputException(ErrorMessage, stringBuilder.ToString());
                }

                if (!projectReferences.Any())
                {
                    stringBuilder.AppendLine("No project references found. Please add a project reference to your test project and retry.");

                    throw new StrykerInputException(ErrorMessage, stringBuilder.ToString());
                }

                return(projectReferences.Single());
            }
            else
            {
                var searchResult = projectReferences.Where(x => x.ToLower().Contains(projectUnderTestNameFilter.ToLower())).ToList();
                if (!searchResult.Any())
                {
                    stringBuilder.Append("No project reference matched your --project-file=");
                    stringBuilder.AppendLine(projectUnderTestNameFilter);
                    stringBuilder.Append(referenceChoise);
                    AppendExampleIfPossible(stringBuilder, projectReferences, projectUnderTestNameFilter);

                    throw new StrykerInputException(ErrorMessage, stringBuilder.ToString());
                }
                else if (searchResult.Count() > 1)
                {
                    stringBuilder.Append("More than one project reference matched your --project-file=");
                    stringBuilder.Append(projectUnderTestNameFilter);
                    stringBuilder.AppendLine(" argument to specify the project to mutate, please specify the name more detailed.");
                    stringBuilder.Append(referenceChoise);
                    AppendExampleIfPossible(stringBuilder, projectReferences, projectUnderTestNameFilter);

                    throw new StrykerInputException(ErrorMessage, stringBuilder.ToString());
                }
                return(FilePathUtils.ConvertPathSeparators(searchResult.Single()));
            }
        }
示例#14
0
        public void RunAllExceptionStatusCodeSuccessShouldBeFalse()
        {
            var processMock = new Mock <IProcessExecutor>(MockBehavior.Strict);

            processMock.SetupProcessMockToReturn("Testrun failed other way", -100);

            string path   = FilePathUtils.ConvertPathSeparators("c://test//");
            var    target = new DotnetTestRunner(path, processMock.Object, OptimizationFlags.NoOptimization);

            var result = target.RunAll(null, null);

            Assert.False(result.Success);
            processMock.Verify(m => m.Start(Path.GetDirectoryName(path), "dotnet", It.Is <string>(s => s.Contains("test")), It.IsAny <IEnumerable <KeyValuePair <string, string> > >(), It.IsAny <int>()));
        }
        public void RunAllExitCode0SuccessShouldBeTrue()
        {
            var processMock = new Mock <IProcessExecutor>(MockBehavior.Strict);

            processMock.SetupProcessMockToReturn("Testrun successful");

            string path   = FilePathUtils.ConvertPathSeparators("c://test");
            var    target = new DotnetTestRunner(path, processMock.Object, OptimizationFlags.NoOptimization);

            var result = target.RunAll(null, null);

            Assert.True(result.Success);
            processMock.Verify(m => m.Start(path, "dotnet", It.Is <string>(s => s.Contains("test")), It.IsAny <IEnumerable <KeyValuePair <string, string> > >(), It.IsAny <int>()));
        }
示例#16
0
        public void CustomTestProjectFilter_WithRelativePath_ShouldIncludeBasePath()
        {
            var userSuppliedFilter = "..\\ExampleActualTestProject\\TestProject.csproj";
            var basePath           = FilePathUtils.ConvertPathSeparators(Path.Combine("C:", "ExampleProject", "TestProject"));
            var fullPath           = FilePathUtils.ConvertPathSeparators(Path.Combine("C:", "ExampleProject", "ExampleActualTestProject", "TestProject.csproj"));

            var ex = Assert.Throws <StrykerInputException>(() =>
            {
                new StrykerOptions(
                    basePath: basePath,
                    testProjectNameFilter: userSuppliedFilter);
            });

            ex.Details.ShouldContain($"The test project filter {userSuppliedFilter} is invalid.");
        }
示例#17
0
        public void InputFileResolver_ShouldChooseGivenTestProjectFileIfPossible_AtFullPath()
        {
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { Path.Combine(_filesystemRoot, "ExampleProject", "ExampleProject.csproj"), new MockFileData(defaultTestProjectFileContents) },
                { Path.Combine(_filesystemRoot, "ExampleProject", "SubFolder", "TestProject.csproj"), new MockFileData(defaultTestProjectFileContents) },
                { Path.Combine(_filesystemRoot, "ExampleProject", "Recursive.cs"), new MockFileData("content") }
            });
            var target = new InputFileResolver(fileSystem, null);

            var actual = target.FindProjectFile(Path.Combine(_filesystemRoot, "ExampleProject"),
                                                FilePathUtils.ConvertPathSeparators(Path.Combine(_filesystemRoot, "ExampleProject", "SubFolder", "TestProject.csproj")));

            actual.ShouldBe(Path.Combine(_filesystemRoot, "ExampleProject", "SubFolder", "TestProject.csproj"));
        }
示例#18
0
        private void InitializeVsTestConsole()
        {
            var testBinariesPath = FilePathUtils.ConvertPathSeparators(Path.Combine(_options.BasePath, "bin", "Debug", _projectInfo.TargetFramework));

            _sources = new List <string>()
            {
                FilePathUtils.ConvertPathSeparators(Path.Combine(testBinariesPath, _projectInfo.TestProjectFileName.Replace("csproj", "dll")))
            };

            _vsTestConsole.StartSession();
            _vsTestConsole.InitializeExtensions(new List <string>
            {
                testBinariesPath,
                _vsTestHelper.GetDefaultVsTestExtensionsPath(_vsTestHelper.GetCurrentPlatformVsTestToolPath())
            });
        }
示例#19
0
        private string BuildTestProjectFilter(string basePath, string testProjectNameFilter)
        {
            // Make sure the filter is relative to the base path otherwise we cannot find it
            var filter = FilePathUtils.ConvertPathSeparators(testProjectNameFilter.Replace(basePath, "", StringComparison.InvariantCultureIgnoreCase));

            // If the filter starts with directory separator char, remove it
            if (filter.Replace("*", "").StartsWith(Path.DirectorySeparatorChar))
            {
                filter = filter.Remove(filter.IndexOf(Path.DirectorySeparatorChar), $"{Path.DirectorySeparatorChar}".Length);
            }

            // Make sure filter contains wildcard
            filter = $"*{filter}";

            return(filter);
        }
示例#20
0
        public Dictionary <OSPlatform, string> GetVsTestToolPaths()
        {
            Dictionary <OSPlatform, string> vsTestPaths = new Dictionary <OSPlatform, string>();
            string versionString       = "15.9.0";
            string portablePackageName = "microsoft.testplatform.portable";

            var nugetPackageFolders = CollectNugetPackageFolders();

            bool dllFound = false;
            bool exeFound = false;

            foreach (string nugetPackageFolder in nugetPackageFolders)
            {
                if (dllFound && exeFound)
                {
                    break;
                }

                string portablePackageFolder = _fileSystem.Directory.GetDirectories(nugetPackageFolder, portablePackageName, SearchOption.AllDirectories).First();

                string dllPath = FilePathUtils.ConvertPathSeparators(
                    Path.Combine(nugetPackageFolder, portablePackageFolder, versionString, "tools", "netcoreapp2.0", "vstest.console.dll"));
                string exePath = FilePathUtils.ConvertPathSeparators(
                    Path.Combine(nugetPackageFolder, portablePackageFolder, versionString, "tools", "net451", "vstest.console.exe"));

                if (!dllFound && _fileSystem.File.Exists(dllPath))
                {
                    vsTestPaths.Add(OSPlatform.Linux, dllPath);
                    vsTestPaths.Add(OSPlatform.OSX, dllPath);
                    dllFound = true;
                }
                if (!exeFound && _fileSystem.File.Exists(exePath))
                {
                    vsTestPaths.Add(OSPlatform.Windows, exePath);
                    exeFound = true;
                }
            }

            if (dllFound && exeFound)
            {
                return(vsTestPaths);
            }
            else
            {
                throw new FileNotFoundException("VsTest executables could not be found in any of the following directories, please submit a bug report: " + string.Join(", ", nugetPackageFolders));
            }
        }
示例#21
0
        public void ShouldGenerateInjectionPath()
        {
            var target = new ProjectInfo()
            {
                TestProjectAnalyzerResult = new ProjectAnalyzerResult(null, null)
                {
                    AssemblyPath = FilePathUtils.ConvertPathSeparators("\\test\\bin\\Debug\\TestApp.dll"),
                },
                ProjectUnderTestAnalyzerResult = new ProjectAnalyzerResult(null, null)
                {
                    AssemblyPath = FilePathUtils.ConvertPathSeparators("\\app\\bin\\Debug\\AppToTest.dll"),
                }
            };

            string expectedPath = FilePathUtils.ConvertPathSeparators("\\test\\bin\\Debug\\AppToTest.dll");

            target.GetInjectionPath().ShouldBe(expectedPath);
        }
示例#22
0
        private string FindProjectReference(XDocument document, string projectUnderTestNameFilter)
        {
            _logger.LogDebug("Determining project under test with name filter {0}", projectUnderTestNameFilter);

            var projectReferenceElements = document.Elements().Descendants().Where(x => string.Equals(x.Name.LocalName, "ProjectReference", StringComparison.OrdinalIgnoreCase));
            // get all the values from the projectReferenceElements
            var projectReferences = projectReferenceElements.SelectMany(x => x.Attributes()).Where(x => string.Equals(x.Name.LocalName, "Include", StringComparison.OrdinalIgnoreCase)).Select(x => x?.Value).ToList();

            if (!projectReferences.Any())
            {
                throw new StrykerInputException(
                          ErrorMessage,
                          "No project references found in test project file, unable to find project to mutate.");
            }

            var projectUnderTest = DetermineProjectUnderTest(projectReferences, projectUnderTestNameFilter);

            return(FilePathUtils.ConvertPathSeparators(projectUnderTest));
        }
示例#23
0
        public void EnvironmentVariableGetsPassed()
        {
            var processMock = new Mock <IProcessExecutor>(MockBehavior.Strict);

            processMock.SetupProcessMockToReturn("Testrun failed other way", -100);

            string path   = FilePathUtils.ConvertPathSeparators("c://test//");
            var    target = new DotnetTestRunner(path, processMock.Object, OptimizationFlags.NoOptimization);

            var result = target.RunAll(null, 1);

            Assert.False(result.Success);
            processMock.Verify(m => m.Start(
                                   Path.GetDirectoryName(path),
                                   "dotnet",
                                   It.Is <string>(s => s.Contains("test")),
                                   It.Is <IDictionary <string, string> >(x => x.Any(y => y.Value == "1" && y.Key == "ActiveMutation")),
                                   It.IsAny <int>()));
        }
示例#24
0
        /// <summary>
        /// Finds the referencedProjects and looks for all files that should be mutated in those projects
        /// </summary>
        public ProjectInfo ResolveInput(string currentDirectory, string projectName)
        {
            string projectFile          = ScanProjectFile(currentDirectory);
            var    currentProjectInfo   = ReadProjectFile(projectFile, projectName);
            var    projectReferencePath = FilePathUtils.ConvertPathSeparators(currentProjectInfo.ProjectReference);
            var    projectUnderTestPath = Path.GetDirectoryName(Path.GetFullPath(Path.Combine(currentDirectory, projectReferencePath)));
            var    projectUnderTestInfo = FindProjectUnderTestAssemblyName(Path.GetFullPath(Path.Combine(projectUnderTestPath, Path.GetFileName(projectReferencePath))));
            var    inputFiles           = FindInputFiles(projectUnderTestPath);

            return(new ProjectInfo()
            {
                TestProjectPath = currentDirectory,
                TestProjectFileName = Path.GetFileName(projectFile),
                TargetFramework = currentProjectInfo.TargetFramework,
                ProjectContents = inputFiles,
                ProjectUnderTestPath = projectUnderTestPath,
                ProjectUnderTestAssemblyName = projectUnderTestInfo ?? Path.GetFileNameWithoutExtension(projectReferencePath),
                ProjectUnderTestProjectName = Path.GetFileNameWithoutExtension(projectReferencePath),
            });
        }
示例#25
0
        private string ValidateTestProjectFilter(string basePath, string userSuppliedFilter)
        {
            string filter;

            if (userSuppliedFilter.Contains(".."))
            {
                filter = FilePathUtils.ConvertPathSeparators(Path.GetFullPath(Path.Combine(basePath, userSuppliedFilter)));
            }
            else
            {
                filter = FilePathUtils.ConvertPathSeparators(userSuppliedFilter);
            }

            if (userSuppliedFilter.Contains("..") && !filter.StartsWith(basePath))
            {
                throw new StrykerInputException(ErrorMessage,
                                                $"The test project filter {userSuppliedFilter} is invalid. Test project file according to filter should exist at {filter} but this is not a child of {FilePathUtils.ConvertPathSeparators(basePath)} so this is not allowed.");
            }
            return(filter);
        }
示例#26
0
        public ProcessResult Start(
            string path,
            string application,
            string arguments,
            IEnumerable <KeyValuePair <string, string> > environmentVariables = null,
            int timeoutMS = 0)
        {
            var info = new ProcessStartInfo(application, arguments)
            {
                UseShellExecute        = false,
                WorkingDirectory       = Path.GetDirectoryName(FilePathUtils.ConvertPathSeparators(path)),
                RedirectStandardOutput = RedirectOutput,
                RedirectStandardError  = RedirectOutput
            };

            foreach (var environmentVariable in environmentVariables ?? Enumerable.Empty <KeyValuePair <string, string> >())
            {
                info.EnvironmentVariables[environmentVariable.Key] = environmentVariable.Value;
            }

            return(RunProcess(info, timeoutMS));
        }
示例#27
0
        private string FindProjectReference(XDocument document, string projectUnderTestNameFilter)
        {
            _logger.LogDebug("Determining project under test with name filter {0}", projectUnderTestNameFilter);

            var projectReferenceElements = document.Elements().Descendants().Where(x => string.Equals(x.Name.LocalName, "ProjectReference", StringComparison.OrdinalIgnoreCase));
            // get all the values from the projectReferenceElements
            var projectReferences = projectReferenceElements.SelectMany(x => x.Attributes()).Where(x => string.Equals(x.Name.LocalName, "Include", StringComparison.OrdinalIgnoreCase)).Select(x => x?.Value).ToList();

            if (projectReferences.Count() > 1)
            {
                // put the references together in one string seperated by ", "
                string referencesString = string.Join(", ", projectReferences);
                if (string.IsNullOrEmpty(projectUnderTestNameFilter))
                {
                    throw new NotSupportedException("Only one referenced project is supported, please add the --project-file=[projectname] argument to specify the project to mutate", innerException: new Exception($"Found the following references: {referencesString}"));
                }
                else
                {
                    var searchResult = projectReferences.Where(x => x.ToLower().Contains(projectUnderTestNameFilter.ToLower())).ToList();
                    if (!searchResult.Any())
                    {
                        throw new ArgumentException($"No project reference matched your --project-file={projectUnderTestNameFilter} argument to specify the project to mutate, was the name spelled correctly?", innerException: new Exception($"Found the following references: {referencesString}"));
                    }
                    else if (searchResult.Count() > 1)
                    {
                        throw new ArgumentException($"More than one project reference matched your --project-file={projectUnderTestNameFilter} argument to specify the project to mutate, please specify the name more detailed", innerException: new Exception($"Found the following references: {referencesString}"));
                    }
                    return(FilePathUtils.ConvertPathSeparators(searchResult.Single()));
                }
            }
            else if (!projectReferences.Any())
            {
                throw new NotSupportedException("No project references found in test project file, unable to find project to mutate.");
            }
            return(FilePathUtils.ConvertPathSeparators(projectReferences.Single()));
        }
示例#28
0
        public IEnumerable <string> FindSharedProjects(XDocument document)
        {
            var projectReferenceElements = document.Elements().Descendants().Where(x => string.Equals(x.Name.LocalName, "Import", StringComparison.OrdinalIgnoreCase));

            return(projectReferenceElements.SelectMany(x => x.Attributes(XName.Get("Project"))).Select(y => FilePathUtils.ConvertPathSeparators(y.Value)));
        }
示例#29
0
 public string GetInjectionPath()
 {
     return(FilePathUtils.ConvertPathSeparators(Path.Combine(
                                                    FilePathUtils.ConvertPathSeparators(Path.GetDirectoryName(TestProjectAnalyzerResult.AssemblyPath)),
                                                    FilePathUtils.ConvertPathSeparators(Path.GetFileName(ProjectUnderTestAnalyzerResult.AssemblyPath)))));
 }
示例#30
0
        public string GetDefaultVsTestExtensionsPath(string vstestToolPath)
        {
            string vstestMainPath = vstestToolPath.Substring(0, vstestToolPath.LastIndexOf(FilePathUtils.ConvertPathSeparators("\\")));
            string extensionPath  = Path.Combine(vstestMainPath, "Extensions");

            if (_fileSystem.Directory.Exists(extensionPath))
            {
                return(extensionPath);
            }
            else
            {
                throw new FileNotFoundException("VsTest test framework adapters not found at " + extensionPath);
            }
        }