Пример #1
0
        public static IActionWrapper <SarifLog> GetActionStage(SarifLogAction action, params string[] args)
        {
            switch (action)
            {
            case SarifLogAction.None:
            {
                return(new GenericMappingAction <SarifLog>(a => a));
            }

            case SarifLogAction.MakeUrisAbsolute:
            {
                return(new GenericMappingAction <SarifLog>(log =>
                    {
                        AbsoluteUrisVisitor visitor = new AbsoluteUrisVisitor();
                        return visitor.VisitSarifLog(log);
                    }));
            }

            case SarifLogAction.RebaseUri:
            {
                return(new GenericMappingAction <SarifLog>(log =>
                    {
                        bool rebaseRelativeUris = false;
                        bool castRelativeUrisArg = bool.TryParse(args[1], out rebaseRelativeUris);
                        Debug.Assert(castRelativeUrisArg);

                        RebaseUriVisitor visitor = new RebaseUriVisitor(args[0], rebaseRelativeUris, new Uri(args[2]));
                        return visitor.VisitSarifLog(log);
                    }));
            }

            case SarifLogAction.Merge:
            {
                return(new GenericFoldAction <SarifLog>(mergeFunction));
            }

            case SarifLogAction.Sort:
            {
                throw new NotImplementedException();
            }

            case SarifLogAction.MakeDeterministic:
            {
                throw new NotImplementedException();
            }

            default:
                throw new ArgumentException($"Unknown/Not Supported Action {action}.", nameof(action));
            }
        }
Пример #2
0
        protected override string ConstructTestOutputFromInputResource(string inputResourceName, object parameter)
        {
            string v2LogText = GetResourceText(inputResourceName);

            string inputLogDirectory = this.OutputFolderPath;
            string inputLogFileName  = Path.GetFileName(inputResourceName);
            string inputLogFilePath  = Path.Combine(this.OutputFolderPath, inputLogFileName);

            string actualLogFilePath = Guid.NewGuid().ToString();

            string ruleUnderTest = Path.GetFileNameWithoutExtension(inputLogFilePath).Split('.')[1];

            // All SARIF rule prefixes require update to current release.
            // All rules with JSON prefix are low level syntax/deserialization checks.
            // We can't transform these test inputs as that operation fixes up errors in the file.
            // Also, don't transform the tests for SARIF1011 or SARIF2008, because these rules
            // examine the actual contents of the $schema property.

            string[] shouldNotTransform = { "SARIF1011", "SARIF2008" };

            bool updateInputsToCurrentSarif = IsSarifRule(ruleUnderTest) &&
                                              !shouldNotTransform.Contains(ruleUnderTest);

            var validateOptions = new ValidateOptions
            {
                SarifOutputVersion   = SarifVersion.Current,
                TargetFileSpecifiers = new[] { inputLogFilePath },
                OutputFilePath       = actualLogFilePath,
                Quiet = true,
                UpdateInputsToCurrentSarif = updateInputsToCurrentSarif,
                PrettyPrint = true,
                Optimize    = true,
                Kind        = new List <ResultKind> {
                    ResultKind.Fail
                },
                Level = new List <FailureLevel> {
                    FailureLevel.Error, FailureLevel.Warning, FailureLevel.Note, FailureLevel.None
                },
            };

            var mockFileSystem = new Mock <IFileSystem>();

            mockFileSystem.Setup(x => x.DirectoryExists(inputLogDirectory)).Returns(true);
            mockFileSystem.Setup(x => x.DirectoryGetDirectories(It.IsAny <string>())).Returns(new string[0]);
            mockFileSystem.Setup(x => x.DirectoryGetFiles(inputLogDirectory, inputLogFileName)).Returns(new string[] { inputLogFilePath });
            mockFileSystem.Setup(x => x.FileReadAllText(inputLogFilePath)).Returns(v2LogText);
            mockFileSystem.Setup(x => x.FileReadAllText(It.IsNotIn <string>(inputLogFilePath))).Returns <string>(path => File.ReadAllText(path));
            mockFileSystem.Setup(x => x.FileWriteAllText(It.IsAny <string>(), It.IsAny <string>()));

            // Some rules are disabled by default, so create a configuration file that explicitly
            // enables the rule under test.
            using (TempFile configFile = CreateTempConfigFile(ruleUnderTest, parameter))
            {
                validateOptions.ConfigurationFilePath = configFile.Name;
                mockFileSystem.Setup(x => x.FileExists(validateOptions.ConfigurationFilePath)).Returns(true);

                var validateCommand = new ValidateCommand(mockFileSystem.Object);

                int returnCode = validateCommand.Run(validateOptions);

                if (validateCommand.ExecutionException != null)
                {
                    Console.WriteLine(validateCommand.ExecutionException.ToString());
                }

                returnCode.Should().Be(0);
            }

            string   actualLogFileContents = File.ReadAllText(actualLogFilePath);
            SarifLog actualLog             = JsonConvert.DeserializeObject <SarifLog>(actualLogFileContents);
            Run      run = actualLog.Runs[0];

            // First, we'll strip any validation results that don't originate with the rule under test.
            // But leave the results that originate from JSchema! Also, be careful because output files
            // from "valid" test cases don't have any results.
            run.Results = run.Results
                          ?.Where(r => IsRelevant(r.RuleId, ruleUnderTest))
                          ?.ToList();

            // Next, remove any rule metadata for those rules. The output files from "valid" test
            // cases don't have any rules.
            run.Tool.Driver.Rules = run.Tool.Driver.Rules
                                    ?.Where(r => IsRelevant(r.Id, ruleUnderTest))
                                    ?.ToList();

            // Since there's only one rule in the metadata, the ruleIndex for all remaining results
            // must be 0.
            foreach (Result result in run.Results)
            {
                result.RuleIndex = 0;
            }

            // Next, we'll remove non-deterministic information, most notably, timestamps emitted for the invocation data.
            var removeTimestampsVisitor = new RemoveOptionalDataVisitor(OptionallyEmittedData.NondeterministicProperties);

            removeTimestampsVisitor.Visit(actualLog);

            // Finally, we'll elide non-deterministic build root details
            var rebaseUrisVisitor = new RebaseUriVisitor("TEST_DIR", new Uri(inputLogDirectory));

            rebaseUrisVisitor.Visit(actualLog);

            // There are differences in log file output depending on whether we are invoking xunit
            // from within Visual Studio or at the command-line via xunit.exe. We elide these differences.

            ToolComponent driver = actualLog.Runs[0].Tool.Driver;

            driver.Name                  = "SARIF Functional Testing";
            driver.Version               = null;
            driver.FullName              = null;
            driver.SemanticVersion       = null;
            driver.DottedQuadFileVersion = null;
            driver.Product               = null;
            driver.Organization          = null;
            driver.Properties?.Clear();
            actualLog.Runs[0].OriginalUriBaseIds = null;

            return(JsonConvert.SerializeObject(actualLog, Formatting.Indented));
        }
Пример #3
0
        protected override string ConstructTestOutputFromInputResource(string inputResourceName, object parameter)
        {
            string v2LogText = GetResourceText(inputResourceName);

            string inputLogDirectory = this.OutputFolderPath;
            string inputLogFileName  = Path.GetFileName(inputResourceName);
            string inputLogFilePath  = Path.Combine(this.OutputFolderPath, inputLogFileName);

            string actualLogFilePath = Guid.NewGuid().ToString();

            string ruleUnderTest = Path.GetFileNameWithoutExtension(inputLogFilePath).Split('.')[1];

            // All SARIF rule prefixes require update to current release.
            // All rules with JSON prefix are low level syntax/deserialization checks.
            // We can't transform these test inputs as that operation fixes up erros in the file.
            bool updateInputsToCurrentSarif = ruleUnderTest.StartsWith("SARIF") ? true : false;

            var validateOptions = new ValidateOptions
            {
                SarifOutputVersion   = SarifVersion.Current,
                TargetFileSpecifiers = new[] { inputLogFilePath },
                OutputFilePath       = actualLogFilePath,
                Quiet = true,
                UpdateInputsToCurrentSarif = updateInputsToCurrentSarif,
                PrettyPrint = true,
                Optimize    = true
            };

            var mockFileSystem = new Mock <IFileSystem>();

            mockFileSystem.Setup(x => x.DirectoryExists(inputLogDirectory)).Returns(true);
            mockFileSystem.Setup(x => x.GetDirectoriesInDirectory(It.IsAny <string>())).Returns(new string[0]);
            mockFileSystem.Setup(x => x.GetFilesInDirectory(inputLogDirectory, inputLogFileName)).Returns(new string[] { inputLogFilePath });
            mockFileSystem.Setup(x => x.ReadAllText(inputLogFilePath)).Returns(v2LogText);
            mockFileSystem.Setup(x => x.ReadAllText(It.IsNotIn <string>(inputLogFilePath))).Returns <string>(path => File.ReadAllText(path));
            mockFileSystem.Setup(x => x.WriteAllText(It.IsAny <string>(), It.IsAny <string>()));

            var validateCommand = new ValidateCommand(mockFileSystem.Object);

            int returnCode = validateCommand.Run(validateOptions);

            if (validateCommand.ExecutionException != null)
            {
                Console.WriteLine(validateCommand.ExecutionException.ToString());
            }

            returnCode.Should().Be(0);

            SarifLog actualLog = JsonConvert.DeserializeObject <SarifLog>(File.ReadAllText(actualLogFilePath));

            // First, we'll strip any validation results that don't originate with the rule under test
            var newResults = new List <Result>();

            foreach (Result result in actualLog.Runs[0].Results)
            {
                if (result.RuleId == ruleUnderTest)
                {
                    newResults.Add(result);
                }
            }

            // Next, we'll remove non-deterministic information, most notably, timestamps emitted for the invocation data.
            var removeTimestampsVisitor = new RemoveOptionalDataVisitor(OptionallyEmittedData.NondeterministicProperties);

            removeTimestampsVisitor.Visit(actualLog);

            // Finally, we'll elide non-deterministic build root details
            var rebaseUrisVisitor = new RebaseUriVisitor("TEST_DIR", new Uri(inputLogDirectory));

            rebaseUrisVisitor.Visit(actualLog);

            // There are differences in log file output depending on whether we are invoking xunit
            // from within Visual Studio or at the command-line via xunit.exe. We elide these differences.

            ToolComponent driver = actualLog.Runs[0].Tool.Driver;

            driver.Name                  = "SARIF Functional Testing";
            driver.Version               = null;
            driver.FullName              = null;
            driver.SemanticVersion       = null;
            driver.DottedQuadFileVersion = null;
            driver.Product               = null;
            driver.Organization          = null;
            driver.Properties?.Clear();
            actualLog.Runs[0].OriginalUriBaseIds = null;

            return(JsonConvert.SerializeObject(actualLog, Formatting.Indented));
        }
Пример #4
0
        public static IActionWrapper <SarifLog> GetActionStage(SarifLogAction action, params string[] args)
        {
            switch (action)
            {
            case SarifLogAction.None:
            {
                return(new GenericMappingAction <SarifLog>(a => a));
            }

            case SarifLogAction.MakeUrisAbsolute:
            {
                return(new GenericMappingAction <SarifLog>(log =>
                    {
                        MakeUrisAbsoluteVisitor visitor = new MakeUrisAbsoluteVisitor();
                        return visitor.VisitSarifLog(log);
                    }));
            }

            case SarifLogAction.InsertOptionalData:
            {
                return(new GenericMappingAction <SarifLog>(log =>
                    {
                        bool optionalDataArgValid = Enum.TryParse(args[0], out OptionallyEmittedData optionalData);
                        Debug.Assert(optionalDataArgValid);

                        if (optionalData != 0)
                        {
                            var visitor = new InsertOptionalDataVisitor(optionalData);
                            return visitor.VisitSarifLog(log);
                        }
                        return log;
                    }));
            }

            case SarifLogAction.RemoveOptionalData:
            {
                return(new GenericMappingAction <SarifLog>(log =>
                    {
                        bool optionalDataArgValid = Enum.TryParse(args[0], out OptionallyEmittedData optionalData);
                        Debug.Assert(optionalDataArgValid);

                        if (optionalData != 0)
                        {
                            var visitor = new InsertOptionalDataVisitor(optionalData);
                            return visitor.VisitSarifLog(log);
                        }
                        return log;
                    }));
            }

            case SarifLogAction.RebaseUri:
            {
                return(new GenericMappingAction <SarifLog>(log =>
                    {
                        bool rebaseRelativeUrisValid = bool.TryParse(args[1], out bool rebaseRelativeUris);
                        Debug.Assert(rebaseRelativeUrisValid);

                        var visitor = new RebaseUriVisitor(args[0], new Uri(args[2]), rebaseRelativeUris);
                        return visitor.VisitSarifLog(log);
                    }));
            }

            case SarifLogAction.Merge:
            {
                bool mergeEmptyLogsArgValid = bool.TryParse(args.Length == 0 ? "true" : args[0], out bool mergeEmptyLogs);
                Debug.Assert(mergeEmptyLogsArgValid);

                return(new GenericFoldAction <SarifLog>((accumulator, nextLog) =>
                    {
                        if (nextLog.Runs == null)
                        {
                            return accumulator;
                        }

                        if (accumulator.Runs == null)
                        {
                            accumulator.Runs = new List <Run>();
                        }

                        foreach (Run run in nextLog.Runs)
                        {
                            if (run != null &&
                                (mergeEmptyLogs || run?.Results.Count > 0))
                            {
                                accumulator.Runs.Add(run);
                            }
                        }

                        return accumulator;
                    }));
            }

            case SarifLogAction.Sort:
            {
                throw new NotImplementedException();
            }

            case SarifLogAction.MakeDeterministic:
            {
                throw new NotImplementedException();
            }

            default:
                throw new ArgumentException($"Unknown/Not Supported Action {action}.", nameof(action));
            }
        }