public void AnalysisConfig_Serialization_SaveAndReload()
        {
            // 0. Setup
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            AnalysisConfig originalConfig = new AnalysisConfig();
            originalConfig.SonarConfigDir = @"c:\config";
            originalConfig.SonarOutputDir = @"c:\output";
            originalConfig.SonarProjectKey = @"key.1.2";
            originalConfig.SonarProjectName = @"My project";
            originalConfig.SonarProjectVersion = @"1.0";


            originalConfig.LocalSettings = new AnalysisProperties();
            originalConfig.LocalSettings.Add(new Property() { Id = "local.key", Value = "local.value" });

            originalConfig.ServerSettings = new AnalysisProperties();
            originalConfig.ServerSettings.Add(new Property() { Id = "server.key", Value = "server.value" });

            originalConfig.AnalyzerSettings = new AnalyzerSettings();
            originalConfig.AnalyzerSettings.RuleSetFilePath = "ruleset path";

            originalConfig.AnalyzerSettings.AdditionalFilePaths = new List<string>();
            originalConfig.AnalyzerSettings.AdditionalFilePaths.Add("additional path1");
            originalConfig.AnalyzerSettings.AdditionalFilePaths.Add("additional path2");

            originalConfig.AnalyzerSettings.AnalyzerAssemblyPaths = new List<string>();
            originalConfig.AnalyzerSettings.AnalyzerAssemblyPaths.Add("analyzer path1");
            originalConfig.AnalyzerSettings.AnalyzerAssemblyPaths.Add("analyzer path2");


            string fileName = Path.Combine(testFolder, "config1.xml");

            SaveAndReloadConfig(originalConfig, fileName);
        }
        public void ConfigExt_GetAnalysisSettings_ServerOnly()
        {
            // Check that local settings are only retrieved by GetAnalysisSettings
            // if includeServerSettings is true

            // 0. Setup
            AnalysisConfig config = new AnalysisConfig();

            config.ServerSettings = new AnalysisProperties();
            config.ServerSettings.Add(new Property() { Id = "server.1", Value = "server.value.1" });
            config.ServerSettings.Add(new Property() { Id = "server.2", Value = "server.value.2" });

            // 1. Local only
            IAnalysisPropertyProvider localProperties = config.GetAnalysisSettings(false);
            localProperties.AssertExpectedPropertyCount(0);

            localProperties.AssertPropertyDoesNotExist("server.1");
            localProperties.AssertPropertyDoesNotExist("server.2");

            // 2. Local and server
            IAnalysisPropertyProvider allProperties = config.GetAnalysisSettings(true);
            allProperties.AssertExpectedPropertyCount(2);
            allProperties.AssertExpectedPropertyValue("server.1", "server.value.1");
            allProperties.AssertExpectedPropertyValue("server.2", "server.value.2");
        }
        public void AnalysisConfig_Serialization_SaveAndReload_EmptySettings()
        {
            // Arrange
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            AnalysisConfig originalConfig = new AnalysisConfig();
            string fileName = Path.Combine(testFolder, "empty_config.xml");

            // Act and assert
            SaveAndReloadConfig(originalConfig, fileName);
        }
        public void AnalysisConfig_Serialization_InvalidFileName()
        {
            // 0. Setup
            AnalysisConfig config = new AnalysisConfig();

            // 1a. Missing file name - save
            AssertException.Expects<ArgumentNullException>(() => config.Save(null));
            AssertException.Expects<ArgumentNullException>(() => config.Save(string.Empty));
            AssertException.Expects<ArgumentNullException>(() => config.Save("\r\t "));

            // 1b. Missing file name - load
            AssertException.Expects<ArgumentNullException>(() => ProjectInfo.Load(null));
            AssertException.Expects<ArgumentNullException>(() => ProjectInfo.Load(string.Empty));
            AssertException.Expects<ArgumentNullException>(() => ProjectInfo.Load("\r\t "));
        }
        public void ConfigExt_GetAndSet()
        {
            // 0. Setup
            AnalysisConfig config = new AnalysisConfig();

            string result;

            // 1. Get missing setting -> default returned
            result = config.GetConfigValue("missing", "123");
            Assert.AreEqual("123", result, "Unexpected config value returned");

            // 2. Set and get a new setting
            config.SetConfigValue("id1", "value1");
            Assert.AreEqual("value1", config.GetConfigValue("id1", "XXX"), "Unexpected config value returned");

            // 3. Update an existing setting
            config.SetConfigValue("id1", "value2");
            Assert.AreEqual("value2", config.GetConfigValue("id1", "XXX"), "Unexpected config value returned");
        }
        public void AnalysisConfig_Serialization_AdditionalConfig()
        {
            // 0. Setup
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            AnalysisConfig originalConfig = new AnalysisConfig();

            // 1. Null list
            SaveAndReloadConfig(originalConfig, Path.Combine(testFolder, "AnalysisConfig_NullAdditionalSettings.xml"));

            // 2. Empty list
            originalConfig.AdditionalConfig = new List<ConfigSetting>();
            SaveAndReloadConfig(originalConfig, Path.Combine(testFolder, "AnalysisConfig_EmptyAdditionalSettings.xml"));

            // 3. Non-empty list
            originalConfig.AdditionalConfig.Add(new ConfigSetting() { Id = string.Empty, Value = string.Empty }); // empty item
            originalConfig.AdditionalConfig.Add(new ConfigSetting() { Id = "Id1", Value = "http://www.foo.xxx" });
            originalConfig.AdditionalConfig.Add(new ConfigSetting() { Id = "Id2", Value = "value 2" });
            SaveAndReloadConfig(originalConfig, Path.Combine(testFolder, "AnalysisConfig_NonEmptyList.xml"));
        }
        public void ConfigExt_GetAnalysisSettings_LocalOnly()
        {
            // Check that local settings are always retrieved by GetAnalysisSettings

            // 0. Setup
            AnalysisConfig config = new AnalysisConfig();

            config.LocalSettings = new AnalysisProperties();
            config.LocalSettings.Add(new Property() { Id = "local.1", Value = "local.value.1" });
            config.LocalSettings.Add(new Property() { Id = "local.2", Value = "local.value.2" });

            // 1. Local only
            IAnalysisPropertyProvider localProperties = config.GetAnalysisSettings(false);
            localProperties.AssertExpectedPropertyCount(2);
            localProperties.AssertExpectedPropertyValue("local.1", "local.value.1");
            localProperties.AssertExpectedPropertyValue("local.2", "local.value.2");

            // 2. Local and server
            IAnalysisPropertyProvider allProperties = config.GetAnalysisSettings(true);
            allProperties.AssertExpectedPropertyCount(2);
            allProperties.AssertExpectedPropertyValue("local.1", "local.value.1");
            allProperties.AssertExpectedPropertyValue("local.2", "local.value.2");
        }
        public void AnalysisConfig_Serialization_SaveAndReload()
        {
            // 0. Setup
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            Guid projectGuid = Guid.NewGuid();

            AnalysisConfig originalConfig = new AnalysisConfig();
            originalConfig.SonarConfigDir = @"c:\config";
            originalConfig.SonarOutputDir = @"c:\output";
            originalConfig.SonarProjectKey = @"key.1.2";
            originalConfig.SonarProjectName = @"My project";
            originalConfig.SonarProjectVersion = @"1.0";

            originalConfig.LocalSettings = new AnalysisProperties();
            originalConfig.LocalSettings.Add(new Property() { Id = "local.key", Value = "local.value" });

            originalConfig.ServerSettings = new AnalysisProperties();
            originalConfig.ServerSettings.Add(new Property() { Id = "server.key", Value = "server.value" });

            string fileName = Path.Combine(testFolder, "config1.xml");

            SaveAndReloadConfig(originalConfig, fileName);
        }
Ejemplo n.º 9
0
        public void FileGen_AdditionalProperties()
        {
            // 0. Arrange
            string     analysisRootDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            TestLogger logger          = new TestLogger();

            CreateProjectWithFiles("project1", analysisRootDir);
            AnalysisConfig config = CreateValidConfig(analysisRootDir);

            // Add additional properties
            config.LocalSettings = new AnalysisProperties();
            config.LocalSettings.Add(new Property()
            {
                Id = "key1", Value = "value1"
            });
            config.LocalSettings.Add(new Property()
            {
                Id = "key.2", Value = "value two"
            });
            config.LocalSettings.Add(new Property()
            {
                Id = "key.3", Value = " "
            });

            // Sensitive data should not be written
            config.LocalSettings.Add(new Property()
            {
                Id = SonarProperties.DbPassword, Value = "secret db pwd"
            });
            config.LocalSettings.Add(new Property()
            {
                Id = SonarProperties.SonarPassword, Value = "secret pwd"
            });

            // Server properties should not be added
            config.ServerSettings = new AnalysisProperties();
            config.ServerSettings.Add(new Property()
            {
                Id = "server.key", Value = "should not be added"
            });

            // Act
            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);

            // Assert
            AssertExpectedProjectCount(1, result);

            // One valid project info file -> file created
            AssertPropertiesFilesCreated(result, logger);

            SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath);

            provider.AssertSettingExists("key1", "value1");
            provider.AssertSettingExists("key.2", "value two");
            provider.AssertSettingExists("key.3", " ");

            provider.AssertSettingDoesNotExist("server.key");

            provider.AssertSettingDoesNotExist(SonarProperties.DbPassword);
            provider.AssertSettingDoesNotExist(SonarProperties.SonarPassword);
        }
        public void ConfigExt_GetAnalysisSettings_FileSettings()
        {
            // Check that file settings are always retrieved by GetAnalysisSettings
            // and that the file name config property is set and retrieved correctly

            // 0. Setup
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            AnalysisConfig config = new AnalysisConfig();

            // File settings
            AnalysisProperties fileSettings = new AnalysisProperties();
            fileSettings.Add(new Property() { Id = "file.1", Value = "file.value.1" });
            fileSettings.Add(new Property() { Id = "file.2", Value = "file.value.2" });
            string settingsFilePath = Path.Combine(testDir, "settings.txt");
            fileSettings.Save(settingsFilePath);

            // 1. Get path when not set -> null
            Assert.IsNull(config.GetSettingsFilePath(), "Expecting the settings file path to be null");

            // 2. Set and get
            config.SetSettingsFilePath(settingsFilePath);
            Assert.AreEqual(settingsFilePath, config.GetSettingsFilePath(), "Unexpected settings file path value returned");

            // 3. Check file properties are retrieved
            IAnalysisPropertyProvider provider = config.GetAnalysisSettings(false);
            provider.AssertExpectedPropertyCount(2);
            provider.AssertExpectedPropertyValue("file.1", "file.value.1");
            provider.AssertExpectedPropertyValue("file.2", "file.value.2");
        }
 public PropertiesWriter(AnalysisConfig config)
 {
     this.config = config ?? throw new ArgumentNullException("config");
     sb          = new StringBuilder();
     projects    = new List <ProjectInfo>();
 }
        public void ConfigExt_GetAnalysisSettings_NoSettings()
        {
            // 0. Setup
            AnalysisConfig config = new AnalysisConfig();

            // 1. No server settings
            IAnalysisPropertyProvider provider = config.GetAnalysisSettings(false);
            Assert.IsNotNull(provider, "Returned provider should not be null");
            provider.AssertExpectedPropertyCount(0);

            // 2. With server settings
            provider = config.GetAnalysisSettings(true);
            Assert.IsNotNull(provider, "Returned provider should not be null");
            provider.AssertExpectedPropertyCount(0);
        }
Ejemplo n.º 13
0
 public PropertiesFileGenerator(AnalysisConfig analysisConfig, ILogger logger)
     : this(analysisConfig, logger, new RoslynV1SarifFixer(logger), new RuntimeInformationWrapper())
 {
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Returns all of the command line arguments to pass to sonar-scanner
        /// </summary>
        private static IEnumerable <string> GetAllCmdLineArgs(string projectSettingsFilePath,
                                                              IEnumerable <string> userCmdLineArguments, AnalysisConfig config, ILogger logger)
        {
            // We don't know what all of the valid command line arguments are so we'll
            // just pass them on for the sonar-scanner to validate.
            var args = new List <string>(userCmdLineArguments);

            // Add any sensitive arguments supplied in the config should be passed on the command line
            args.AddRange(GetSensitiveFileSettings(config, userCmdLineArguments));

            // Add the project settings file and the standard options.
            // Experimentation suggests that the sonar-scanner won't error if duplicate arguments
            // are supplied - it will just use the last argument.
            // So we'll set our additional properties last to make sure they take precedence.
            args.Add(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}={2}", CmdLineArgPrefix,
                                   ProjectSettingsFileArgName, projectSettingsFilePath));

            // Let the scanner cli know it has been ran from this MSBuild Scanner. (allows to tweak the behavior)
            // See https://jira.sonarsource.com/browse/SQSCANNER-65
            args.Add("--from=ScannerMSBuild/" + Utilities.ScannerVersion);

            // For debug mode, we need to pass the debug option to the scanner cli in order to see correctly stack traces.
            // Note that in addition to this change, the sonar.verbose=true was removed from the config file.
            // See: https://github.com/SonarSource/sonar-scanner-msbuild/issues/543
            if (logger.Verbosity == LoggerVerbosity.Debug)
            {
                args.Add("--debug");
            }

            return(args);
        }
Ejemplo n.º 15
0
        public /* for test */ static ProjectInfoAnalysisResult GenerateFile(AnalysisConfig config, ILogger logger, IRoslynV1SarifFixer fixer)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string fileName = Path.Combine(config.SonarOutputDir, ProjectPropertiesFileName);

            logger.LogDebug(Resources.MSG_GeneratingProjectProperties, fileName);

            IEnumerable <ProjectInfo> projects = ProjectLoader.LoadFrom(config.SonarOutputDir).ToArray();

            if (projects == null || !projects.Any())
            {
                logger.LogError(Resources.ERR_NoProjectInfoFilesFound);
                return(new ProjectInfoAnalysisResult());
            }

            TryFixSarifReports(logger, projects, fixer);

            string rootProjectBaseDir = ComputeRootProjectBaseDir(config, projects);

            PropertiesWriter   writer     = new PropertiesWriter(config);
            AnalysisProperties properties = GetAnalysisProperties(config);
            var globalSourceEncoding      = GetSourceEncoding(properties, new EncodingProvider());

            ProjectInfoAnalysisResult result = ProcessProjectInfoFiles(projects, writer, logger, rootProjectBaseDir, globalSourceEncoding);

            writer.WriteSonarProjectInfo(rootProjectBaseDir, result.SharedFiles);

            IEnumerable <ProjectInfo> validProjects = result.GetProjectsByStatus(ProjectInfoValidity.Valid);

            if (validProjects.Any() || result.SharedFiles.Any())
            {
                // Handle global settings
                properties = GetAnalysisPropertiesToWrite(properties, logger);
                writer.WriteGlobalSettings(properties);

                string contents = writer.Flush();

                result.FullPropertiesFilePath = fileName;
                File.WriteAllText(result.FullPropertiesFilePath, contents, Encoding.ASCII);
            }
            else
            {
                // if the user tries to build multiple configurations at once there will be duplicate projects
                if (result.GetProjectsByStatus(ProjectInfoValidity.DuplicateGuid).Any())
                {
                    logger.LogError(Resources.ERR_NoValidButDuplicateProjects);
                }
                else
                {
                    logger.LogError(Resources.ERR_NoValidProjectInfoFiles);
                }
            }
            return(result);
        }
Ejemplo n.º 16
0
 public BinaryToXmlCoverageReportConverter(ILogger logger, AnalysisConfig config)
     : this(new VisualStudioSetupConfigurationFactory(), logger, config)
 {
 }
 protected abstract bool TryGetBinaryReportFile(AnalysisConfig config, ITeamBuildSettings settings, ILogger logger, out string binaryFilePath);
        private static void AssertExpectedServerSetting(string key, string expectedValue, AnalysisConfig actualConfig)
        {
            var found = Property.TryGetProperty(key, actualConfig.ServerSettings, out Property actualProperty);

            Assert.IsTrue(found, "Failed to find the expected server setting: {0}", key);
            Assert.AreEqual(expectedValue, actualProperty.Value, "Unexpected property value. Key: {0}", key);
        }
Ejemplo n.º 19
0
        public static AnalysisConfig GenerateFile(ProcessedArgs args, TeamBuildSettings settings, IDictionary <string, string> serverProperties, ILogger logger)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (serverProperties == null)
            {
                throw new ArgumentNullException("serverProperties");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            AnalysisConfig config = new AnalysisConfig();

            config.SonarProjectKey     = args.ProjectKey;
            config.SonarProjectName    = args.ProjectName;
            config.SonarProjectVersion = args.ProjectVersion;
            config.SonarQubeHostUrl    = args.GetSetting(SonarProperties.HostUrl);

            config.SetBuildUri(settings.BuildUri);
            config.SetTfsUri(settings.TfsUri);
            config.SonarConfigDir = settings.SonarConfigDirectory;
            config.SonarOutputDir = settings.SonarOutputDirectory;
            config.SonarBinDir    = settings.SonarBinDirectory;
            config.SonarRunnerWorkingDirectory = settings.SonarRunnerWorkingDirectory;

            // Add the server properties to the config
            config.ServerSettings = new AnalysisProperties();

            foreach (var property in serverProperties)
            {
                if (!IsSecuredServerProperty(property.Key))
                {
                    AddSetting(config.ServerSettings, property.Key, property.Value);
                }
            }

            // Add command line arguments
            config.LocalSettings = new AnalysisProperties();
            foreach (var property in args.LocalProperties.GetAllProperties())
            {
                AddSetting(config.LocalSettings, property.Id, property.Value);
            }

            // Set the pointer to the properties file
            if (args.PropertiesFileName != null)
            {
                config.SetSettingsFilePath(args.PropertiesFileName);
            }

            config.Save(settings.AnalysisConfigFilePath);

            return(config);
        }
Ejemplo n.º 20
0
 protected abstract bool TryGetTrxFiles(AnalysisConfig config, ITeamBuildSettings settings, out IEnumerable <string> trxFilePaths);
Ejemplo n.º 21
0
 protected abstract bool TryGetVsCoverageFiles(AnalysisConfig config, ITeamBuildSettings settings, out IEnumerable <string> binaryFilePaths);
        protected override bool TryGetBinaryReportFile(AnalysisConfig config, TeamBuildSettings settings, ILogger logger, out string binaryFilePath)
        {
            binaryFilePath = TrxFileReader.LocateCodeCoverageFile(settings.BuildDirectory, logger);

            return(true); // there aren't currently any conditions under which we'd want to stop processing
        }
Ejemplo n.º 23
0
        public void Roslyn_Settings_ValidSetup()
        {
            // Arrange

            // Set the config directory so the targets know where to look for the analysis config file
            var confDir = TestUtils.CreateTestSpecificFolder(TestContext, "config");

            // Create a valid config file containing analyzer settings
            var expectedAssemblies      = new string[] { "c:\\data\\config.analyzer1.dll", "c:\\config2.dll" };
            var analyzerAdditionalFiles = new string[] { "c:\\config.1.txt", "c:\\config.2.txt" };

            var config = new AnalysisConfig();

            var analyzerSettings = new AnalyzerSettings
            {
                Language              = "cs",
                RuleSetFilePath       = "d:\\my.ruleset",
                AnalyzerAssemblyPaths = expectedAssemblies.ToList(),
                AdditionalFilePaths   = analyzerAdditionalFiles.ToList()
            };

            config.AnalyzersSettings = new List <AnalyzerSettings>
            {
                analyzerSettings
            };

            var configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);

            config.Save(configFilePath);

            // Create the project
            var properties = new WellKnownProjectProperties
            {
                SonarQubeConfigPath         = confDir,
                ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset"
            };

            var projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "should.be.removed.analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\should.be.removed.analyzer2.dll");

            var notRemovedAdditionalFiles = new string[] { "should.not.be.removed.additional1.txt", "should.not.be.removed.additional2.txt" };

            foreach (var notRemovedAdditionalFile in notRemovedAdditionalFiles)
            {
                projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, notRemovedAdditionalFile);
            }

            projectRoot.Save(); // re-save the modified project

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.OverrideRoslynAnalysisTarget);

            var projectSpecificConfFilePath   = result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath);
            var expectedRoslynAdditionalFiles = new string[] { projectSpecificConfFilePath }
            .Concat(analyzerAdditionalFiles)
            .Concat(notRemovedAdditionalFiles)
            .ToArray();

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, "d:\\my.ruleset");
            AssertExpectedItemValuesExists(result, TargetProperties.AdditionalFilesItemType, expectedRoslynAdditionalFiles);
            AssertExpectedItemValuesExists(result, TargetProperties.AnalyzerItemType, expectedAssemblies);

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
Ejemplo n.º 24
0
 public bool Initialise(AnalysisConfig context, ITeamBuildSettings settings, ILogger logger)
 {
     Assert.IsFalse(this.initalisedCalled, "Expecting Initialise to be called only once");
     this.initalisedCalled = true;
     return(InitialiseValueToReturn);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Returns all of the command line arguments to pass to sonar-scanner
        /// </summary>
        private static IEnumerable <string> GetAllCmdLineArgs(string projectSettingsFilePath, IEnumerable <string> userCmdLineArguments, AnalysisConfig config)
        {
            // We don't know what all of the valid command line arguments are so we'll
            // just pass them on for the sonar-scanner to validate.
            List <string> args = new List <string>(userCmdLineArguments);

            // Add any sensitive arguments supplied in the config should be passed on the command line
            args.AddRange(GetSensitiveFileSettings(config, userCmdLineArguments));

            // Add the project settings file and the standard options.
            // Experimentation suggests that the sonar-scanner won't error if duplicate arguments
            // are supplied - it will just use the last argument.
            // So we'll set our additional properties last to make sure they take precedence.
            args.Add(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}={2}", CmdLineArgPrefix, ProjectSettingsFileArgName, projectSettingsFilePath));

            return(args);
        }
        [WorkItem(127)] // Do not store the db and server credentials in the config files: http://jira.sonarsource.com/browse/SONARMSBRU-127
        public void AnalysisConfGen_AnalysisConfigDoesNotContainSensitiveData()
        {
            // Arrange
            string analysisDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            TestLogger logger = new TestLogger();

            ListPropertiesProvider cmdLineArgs = new ListPropertiesProvider();

            // Public args - should be written to the config file
            cmdLineArgs.AddProperty("sonar.host.url", "http://host");
            cmdLineArgs.AddProperty("public.key", "public value");

            // Sensitive values - should not be written to the config file
            cmdLineArgs.AddProperty(SonarProperties.DbPassword, "secret db password");
            cmdLineArgs.AddProperty(SonarProperties.DbUserName, "secret db user");

            // Create a settings file with public and sensitive data
            AnalysisProperties fileSettings = new AnalysisProperties();

            fileSettings.Add(new Property()
            {
                Id = "file.public.key", Value = "file public value"
            });
            fileSettings.Add(new Property()
            {
                Id = SonarProperties.DbUserName, Value = "secret db user"
            });
            fileSettings.Add(new Property()
            {
                Id = SonarProperties.DbPassword, Value = "secret db password"
            });
            string fileSettingsPath = Path.Combine(analysisDir, "fileSettings.txt");

            fileSettings.Save(fileSettingsPath);
            FilePropertyProvider fileProvider = FilePropertyProvider.Load(fileSettingsPath);

            ProcessedArgs args = new ProcessedArgs("key", "name", "1.0", false, cmdLineArgs, fileProvider);

            IDictionary <string, string> serverProperties = new Dictionary <string, string>();

            // Public server settings
            serverProperties.Add("server.key.1", "server value 1");
            // Sensitive server settings
            serverProperties.Add(SonarProperties.SonarUserName, "secret user");
            serverProperties.Add(SonarProperties.SonarPassword, "secret pwd");


            TeamBuildSettings settings = TeamBuildSettings.CreateNonTeamBuildSettings(analysisDir);

            Directory.CreateDirectory(settings.SonarConfigDirectory); // config directory needs to exist


            // Act
            AnalysisConfig config = AnalysisConfigGenerator.GenerateFile(args, settings, serverProperties, logger);

            // Assert
            AssertConfigFileExists(config);
            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(0);

            // Check the config

            // "Public" arguments should be in the file
            Assert.AreEqual("key", config.SonarProjectKey, "Unexpected project key");
            Assert.AreEqual("name", config.SonarProjectName, "Unexpected project name");
            Assert.AreEqual("1.0", config.SonarProjectVersion, "Unexpected project version");

            AssertExpectedLocalSetting(SonarProperties.HostUrl, "http://host", config);
            AssertExpectedServerSetting("server.key.1", "server value 1", config);

            AssertFileDoesNotContainText(config.FileName, "file.public.key"); // file settings values should not be in the config

            // SONARMSBRU-136: TODO - uncomment the following code:
            //AssertFileDoesNotContainText(config.FileName, "secret"); // sensitive data should not be in config

            // SONARMSBRU-136: TODO - delete the following code:
            // v1.0.1 back-compat: check sensitive data is written to the config file
            AssertExpectedLocalSetting(SonarProperties.DbPassword, "secret db password", config);
            AssertExpectedLocalSetting(SonarProperties.DbUserName, "secret db user", config);
            AssertExpectedServerSetting(SonarProperties.SonarUserName, "secret user", config);
            AssertExpectedServerSetting(SonarProperties.SonarPassword, "secret pwd", config);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Locates the ProjectInfo.xml files and uses the information in them to generate
 /// a sonar-scanner properties file
 /// </summary>
 /// <returns>Information about each of the project info files that was processed, together with
 /// the full path to generated file.
 /// Note: the path to the generated file will be null if the file could not be generated.</returns>
 public static ProjectInfoAnalysisResult GenerateFile(AnalysisConfig config, ILogger logger)
 {
     return(GenerateFile(config, logger, new RoslynV1SarifFixer()));
 }
        public void AnalysisConfig_ExpectedXmlFormat()
        {
            // Arrange
            string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<AnalysisConfig xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://www.sonarsource.com/msbuild/integration/2015/1"">
  <SonarConfigDir>c:\config</SonarConfigDir>
  <SonarOutputDir>c:\output</SonarOutputDir>
  <SonarProjectKey>key.1.2</SonarProjectKey>
  <SonarProjectVersion>1.0</SonarProjectVersion>
  <SonarProjectName>My project</SonarProjectName>
  <ServerSettings>
    <Property Name=""server.key"">server.value</Property>
  </ServerSettings>

  <!-- Unexpected additional elements should be silently ignored -->
  <UnexpectedElement1 />

  <LocalSettings>
    <Property Name=""local.key"">local.value</Property>
  </LocalSettings>
  <AnalyzerSettings>
    <RuleSetFilePath>d:\ruleset path.ruleset</RuleSetFilePath>
    <AnalyzerAssemblyPaths>
      <Path>c:\analyzer1.dll</Path>
    </AnalyzerAssemblyPaths>
    <AdditionalFilePaths>

      <MoreUnexpectedData><Foo /></MoreUnexpectedData>

      <Path>c:\additional1.txt</Path>
    </AdditionalFilePaths>
  </AnalyzerSettings>
</AnalysisConfig>";

            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string fullPath = TestUtils.CreateTextFile(testDir, "input.txt", xml);

            // Act
            AnalysisConfig actual = AnalysisConfig.Load(fullPath);

            // Assert
            AnalysisConfig expected = new AnalysisConfig();
            expected.SonarConfigDir = "c:\\config";
            expected.SonarOutputDir = "c:\\output";
            expected.SonarProjectKey = "key.1.2";
            expected.SonarProjectVersion = "1.0";
            expected.SonarProjectName = "My project";
            expected.ServerSettings = new AnalysisProperties();
            expected.ServerSettings.Add(new Property() { Id = "server.key", Value = "server.value" });
            expected.LocalSettings = new AnalysisProperties();
            expected.LocalSettings.Add(new Property() { Id = "local.key", Value = "local.value" });
            expected.AnalyzerSettings = new AnalyzerSettings();
            expected.AnalyzerSettings.RuleSetFilePath = "d:\\ruleset path.ruleset";
            expected.AnalyzerSettings.AdditionalFilePaths = new List<string>();
            expected.AnalyzerSettings.AdditionalFilePaths.Add("c:\\additional1.txt");
            expected.AnalyzerSettings.AnalyzerAssemblyPaths = new List<string>();
            expected.AnalyzerSettings.AnalyzerAssemblyPaths.Add("c:\\analyzer1.dll");

            AssertExpectedValues(expected, actual);
        }
        public void ConfigExt_GetAnalysisSettings_Precedence()
        {
            // Expected precedence: local -> file -> server

            // 0. Setup
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            AnalysisConfig config = new AnalysisConfig();

            // File settings
            AnalysisProperties fileSettings = new AnalysisProperties();
            fileSettings.Add(new Property() { Id = "file.1", Value = "file.value.1" });
            fileSettings.Add(new Property() { Id = "shared.property", Value = "shared value from file - should never be returned" });
            fileSettings.Add(new Property() { Id = "shared.property2", Value = "shared value 2 from file" });
            string settingsFilePath = Path.Combine(testDir, "settings.txt");
            fileSettings.Save(settingsFilePath);
            config.SetSettingsFilePath(settingsFilePath);

            // Local settings
            config.LocalSettings = new AnalysisProperties();
            config.LocalSettings.Add(new Property() { Id = "local.1", Value = "local.value.1" });
            config.LocalSettings.Add(new Property() { Id = "local.2", Value = "local.value.2" });
            config.LocalSettings.Add(new Property() { Id = "shared.property", Value = "shared value from local" });

            // Server settings
            config.ServerSettings = new AnalysisProperties();
            config.ServerSettings.Add(new Property() { Id = "server.1", Value = "server.value.1" });
            config.ServerSettings.Add(new Property() { Id = "server.2", Value = "server.value.2" });
            config.ServerSettings.Add(new Property() { Id = "shared.property", Value = "shared value from server - should never be returned" });
            config.ServerSettings.Add(new Property() { Id = "shared.property2", Value = "shared value 2 from server - should never be returned" });


            // 1. Precedence - local should win over file
            IAnalysisPropertyProvider provider = config.GetAnalysisSettings(false);
            provider.AssertExpectedPropertyCount(5);
            provider.AssertExpectedPropertyValue("local.1", "local.value.1");
            provider.AssertExpectedPropertyValue("local.2", "local.value.2");
            provider.AssertExpectedPropertyValue("file.1", "file.value.1");
            provider.AssertExpectedPropertyValue("shared.property", "shared value from local");
            provider.AssertExpectedPropertyValue("shared.property2", "shared value 2 from file");

            provider.AssertPropertyDoesNotExist("server.1");
            provider.AssertPropertyDoesNotExist("server.2");

            // 2. Server and non-server
            provider = config.GetAnalysisSettings(true);
            provider.AssertExpectedPropertyCount(7);
            provider.AssertExpectedPropertyValue("local.1", "local.value.1");
            provider.AssertExpectedPropertyValue("local.2", "local.value.2");
            provider.AssertExpectedPropertyValue("file.1", "file.value.1");
            provider.AssertExpectedPropertyValue("shared.property", "shared value from local");
            provider.AssertExpectedPropertyValue("shared.property2", "shared value 2 from file");
            provider.AssertExpectedPropertyValue("server.1", "server.value.1");
            provider.AssertExpectedPropertyValue("server.2", "server.value.2");
        }
        private static void AssertExpectedValues(AnalysisConfig expected, AnalysisConfig actual)
        {
            Assert.AreEqual(expected.SonarProjectKey, actual.SonarProjectKey, "Unexpected project key");
            Assert.AreEqual(expected.SonarProjectName, actual.SonarProjectName, "Unexpected project name");
            Assert.AreEqual(expected.SonarProjectVersion, actual.SonarProjectVersion, "Unexpected project version");

            Assert.AreEqual(expected.SonarConfigDir, actual.SonarConfigDir, "Unexpected config directory");
            Assert.AreEqual(expected.SonarOutputDir, actual.SonarOutputDir, "Unexpected output directory");

            CompareAdditionalSettings(expected, actual);

            CompareAnalyzerSettings(expected.AnalyzerSettings, actual.AnalyzerSettings);
        }
        /// <summary>
        /// Combines the various configuration options into the AnalysisConfig file
        /// used by the build and post-processor. Saves the file and returns the config instance.
        /// </summary>
        /// <param name="localSettings">Processed local settings, including command line arguments supplied the user</param>
        /// <param name="buildSettings">Build environment settings</param>
        /// <param name="serverProperties">Analysis properties downloaded from the SonarQube server</param>
        /// <param name="analyzerSettings">Specifies the Roslyn analyzers to use. Can be empty</param>
        public static AnalysisConfig GenerateFile(ProcessedArgs localSettings,
                                                  TeamBuildSettings buildSettings,
                                                  IDictionary <string, string> serverProperties,
                                                  List <AnalyzerSettings> analyzersSettings,
                                                  ISonarQubeServer sonarQubeServer,
                                                  ILogger logger)
        {
            if (localSettings == null)
            {
                throw new ArgumentNullException(nameof(localSettings));
            }
            if (buildSettings == null)
            {
                throw new ArgumentNullException(nameof(buildSettings));
            }
            if (serverProperties == null)
            {
                throw new ArgumentNullException(nameof(serverProperties));
            }
            if (sonarQubeServer == null)
            {
                throw new ArgumentNullException(nameof(sonarQubeServer));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            var config = new AnalysisConfig
            {
                SonarProjectKey     = localSettings.ProjectKey,
                SonarProjectName    = localSettings.ProjectName,
                SonarProjectVersion = localSettings.ProjectVersion,
                SonarQubeHostUrl    = localSettings.SonarQubeUrl,
                HasBeginStepCommandLineCredentials = localSettings.CmdLineProperties.HasProperty(SonarProperties.SonarUserName),
                SonarQubeVersion = sonarQubeServer.GetServerVersion().Result.ToString()
            };

            config.SetBuildUri(buildSettings.BuildUri);
            config.SetTfsUri(buildSettings.TfsUri);
            config.SetVsCoverageConverterToolPath(buildSettings.CoverageToolUserSuppliedPath);

            config.SonarConfigDir = buildSettings.SonarConfigDirectory;
            config.SonarOutputDir = buildSettings.SonarOutputDirectory;
            config.SonarBinDir    = buildSettings.SonarBinDirectory;
            config.SonarScannerWorkingDirectory = buildSettings.SonarScannerWorkingDirectory;
            config.SourcesDirectory             = buildSettings.SourcesDirectory;

            // Add the server properties to the config
            config.ServerSettings = new AnalysisProperties();

            foreach (var property in serverProperties)
            {
                if (!Utilities.IsSecuredServerProperty(property.Key))
                {
                    AddSetting(config.ServerSettings, property.Key, property.Value);
                }
            }

            config.LocalSettings = new AnalysisProperties();
            // From the local settings, we only write the ones coming from the cmd line
            foreach (var property in localSettings.CmdLineProperties.GetAllProperties())
            {
                AddSetting(config.LocalSettings, property.Id, property.Value);
            }

            if (!string.IsNullOrEmpty(localSettings.Organization))
            {
                AddSetting(config.LocalSettings, SonarProperties.Organization, localSettings.Organization);
            }

            // Set the pointer to the properties file
            if (localSettings.PropertiesFileName != null)
            {
                config.SetSettingsFilePath(localSettings.PropertiesFileName);
            }

            config.AnalyzersSettings = analyzersSettings ?? throw new ArgumentNullException(nameof(analyzersSettings));
            config.Save(buildSettings.AnalysisConfigFilePath);

            return(config);
        }
        private static void AssertExpectedLocalSetting(string key, string expectedValue, AnalysisConfig acutalConfig)
        {
            Property property;
            bool     found = Property.TryGetProperty(key, acutalConfig.LocalSettings, out property);

            Assert.IsTrue(found, "Expected local property was not found. Key: {0}", key);
            Assert.AreEqual(expectedValue, property.Value, "Unexpected local value. Key: {0}", key);
        }
Ejemplo n.º 33
0
        private static bool InternalExecute(AnalysisConfig config, ILogger logger, IEnumerable <string> userCmdLineArguments, String fullPropertiesFilePath)
        {
            var exeFileName = FindProcessorExe();

            return(ExecuteProcessorRunner(config, logger, exeFileName, userCmdLineArguments, fullPropertiesFilePath, new ProcessRunner(logger)));
        }
        private string CreateProjectFile(AnalysisConfig analysisConfig, string testSpecificProjectXml, string sonarQubeOutputPath)
        {
            var projectDirectory = TestUtils.CreateTestSpecificFolder(TestContext);

            if (analysisConfig != null)
            {
                var configFilePath = Path.Combine(projectDirectory, FileConstants.ConfigFileName);
                analysisConfig.Save(configFilePath);
            }

            var sqTargetFile = TestUtils.EnsureAnalysisTargetsExists(TestContext);

            File.Exists(sqTargetFile).Should().BeTrue("Test error: the SonarQube analysis targets file could not be found. Full path: {0}", sqTargetFile);
            TestContext.AddResultFile(sqTargetFile);


            var template    = @"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='Current' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <!-- Boilerplate -->
  <!-- All of these boilerplate properties can be overridden by setting the value again in the test-specific XML snippet -->
  <PropertyGroup>
    <ImportByWildcardBeforeMicrosoftCommonTargets>false</ImportByWildcardBeforeMicrosoftCommonTargets>
    <ImportByWildcardAfterMicrosoftCommonTargets>false</ImportByWildcardAfterMicrosoftCommonTargets>
    <ImportUserLocationsByWildcardBeforeMicrosoftCommonTargets>false</ImportUserLocationsByWildcardBeforeMicrosoftCommonTargets>
    <ImportUserLocationsByWildcardAfterMicrosoftCommonTargets>false</ImportUserLocationsByWildcardAfterMicrosoftCommonTargets>
    <OutputPath>bin\</OutputPath>
    <OutputType>library</OutputType>
    <ProjectGuid>ffdb93c0-2880-44c7-89a6-bbd4ddab034a</ProjectGuid>
    <Language>C#</Language>
  </PropertyGroup>

  <PropertyGroup>
    <!-- Standard values that need to be set for each/most tests -->
    <SonarQubeBuildTasksAssemblyFile>SONARSCANNER_MSBUILD_TASKS_DLL</SonarQubeBuildTasksAssemblyFile>
    <SonarQubeConfigPath>PROJECT_DIRECTORY_PATH</SonarQubeConfigPath>
    <SonarQubeTempPath>PROJECT_DIRECTORY_PATH</SonarQubeTempPath>
    <SonarQubeOutputPath>SQ_OUTPUT_PATH</SonarQubeOutputPath>

    <!-- Ensure the project is isolated from environment variables that could be picked up when running on a TeamBuild build agent-->
    <TF_BUILD_BUILDDIRECTORY />
    <AGENT_BUILDDIRECTORY />
  </PropertyGroup>

  <!-- Test-specific data -->
  TEST_SPECIFIC_XML

  <!-- Standard boilerplate closing imports -->
  <Import Project='$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), SonarQube.Integration.targets))SonarQube.Integration.targets' />
  <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' />
</Project>
";
            var projectData = template.Replace("PROJECT_DIRECTORY_PATH", projectDirectory)
                              .Replace("SONARSCANNER_MSBUILD_TASKS_DLL", typeof(WriteProjectInfoFile).Assembly.Location)
                              .Replace("TEST_SPECIFIC_XML", testSpecificProjectXml ?? "<!-- none -->")
                              .Replace("SQ_OUTPUT_PATH", sonarQubeOutputPath);

            var projectFilePath = Path.Combine(projectDirectory, TestContext.TestName + ".proj.txt");

            File.WriteAllText(projectFilePath, projectData);
            TestContext.AddResultFile(projectFilePath);

            return(projectFilePath);
        }
 public TfsLegacyCoverageReportProcessor(ILogger logger, AnalysisConfig config)
     : this(new CoverageReportUrlProvider(logger), new CoverageReportDownloader(logger),
            new BinaryToXmlCoverageReportConverter(logger, config), logger)
 {
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Combines the various configuration options into the AnalysisConfig file
        /// used by the build and post-processor. Saves the file and returns the config instance.
        /// </summary>
        /// <param name="localSettings">Processed local settings, including command line arguments supplied the user</param>
        /// <param name="buildSettings">Build environment settings</param>
        /// <param name="serverProperties">Analysis properties downloaded from the SonarQube server</param>
        /// <param name="analyzerSettings">Specifies the Roslyn analyzers to use</param>
        public static AnalysisConfig GenerateFile(ProcessedArgs localSettings,
                                                  TeamBuildSettings buildSettings,
                                                  IDictionary <string, string> serverProperties,
                                                  List <AnalyzerSettings> analyzersSettings,
                                                  ILogger logger)
        {
            if (localSettings == null)
            {
                throw new ArgumentNullException(nameof(localSettings));
            }
            if (buildSettings == null)
            {
                throw new ArgumentNullException(nameof(buildSettings));
            }
            if (serverProperties == null)
            {
                throw new ArgumentNullException(nameof(serverProperties));
            }
            if (analyzersSettings == null)
            {
                throw new ArgumentNullException(nameof(analyzersSettings));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            AnalysisConfig config = new AnalysisConfig();

            config.SonarProjectKey     = localSettings.ProjectKey;
            config.SonarProjectName    = localSettings.ProjectName;
            config.SonarProjectVersion = localSettings.ProjectVersion;
            config.SonarQubeHostUrl    = localSettings.SonarQubeUrl;

            config.SetBuildUri(buildSettings.BuildUri);
            config.SetTfsUri(buildSettings.TfsUri);

            config.SonarConfigDir = buildSettings.SonarConfigDirectory;
            config.SonarOutputDir = buildSettings.SonarOutputDirectory;
            config.SonarBinDir    = buildSettings.SonarBinDirectory;
            config.SonarScannerWorkingDirectory = buildSettings.SonarScannerWorkingDirectory;
            config.SourcesDirectory             = buildSettings.SourcesDirectory;

            // Add the server properties to the config
            config.ServerSettings = new AnalysisProperties();

            foreach (var property in serverProperties)
            {
                if (!Utilities.IsSecuredServerProperty(property.Key))
                {
                    AddSetting(config.ServerSettings, property.Key, property.Value);
                }
            }

            config.LocalSettings = new AnalysisProperties();
            // From the local settings, we only write the ones coming from the cmd line
            foreach (var property in localSettings.CmdLineProperties.GetAllProperties())
            {
                AddSetting(config.LocalSettings, property.Id, property.Value);
            }

            // Set the pointer to the properties file
            if (localSettings.PropertiesFileName != null)
            {
                config.SetSettingsFilePath(localSettings.PropertiesFileName);
            }

            config.AnalyzersSettings = analyzersSettings;
            config.Save(buildSettings.AnalysisConfigFilePath);

            return(config);
        }
        [WorkItem(120)] // Regression test for http://jira.sonarsource.com/browse/SONARMSBRU-120
        public void AnalysisConfig_SharedReadAllowed()
        {
            // 0. Setup
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string filePath = Path.Combine(testFolder, "config.txt");

            AnalysisConfig config = new AnalysisConfig();
            config.Save(filePath);

            using (FileStream lockingStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                AnalysisConfig.Load(filePath);
            }
        }
 protected override bool TryGetTrxFiles(AnalysisConfig config, ITeamBuildSettings settings, out IEnumerable <string> trxFilePaths)
 {
     trxFilePaths = Enumerable.Empty <string>();
     return(false);
 }
        private AnalysisConfig SaveAndReloadConfig(AnalysisConfig original, string outputFileName)
        {
            Assert.IsFalse(File.Exists(outputFileName), "Test error: file should not exist at the start of the test. File: {0}", outputFileName);
            original.Save(outputFileName);
            Assert.IsTrue(File.Exists(outputFileName), "Failed to create the output file. File: {0}", outputFileName);
            this.TestContext.AddResultFile(outputFileName);

            AnalysisConfig reloaded = AnalysisConfig.Load(outputFileName);
            Assert.IsNotNull(reloaded, "Reloaded analysis config should not be null");

            AssertExpectedValues(original, reloaded);
            return reloaded;
        }
Ejemplo n.º 40
0
        public void PropertiesWriterToString()
        {
            var productBaseDir     = TestUtils.CreateTestSpecificFolder(TestContext, "PropertiesWriterTest_ProductBaseDir");
            var productProject     = CreateEmptyFile(productBaseDir, "MyProduct.csproj");
            var productFile        = CreateEmptyFile(productBaseDir, "File.cs");
            var productChineseFile = CreateEmptyFile(productBaseDir, "你好.cs");

            var productCoverageFilePath = CreateEmptyFile(productBaseDir, "productCoverageReport.txt");
            var productFileListFilePath = Path.Combine(productBaseDir, "productManagedFiles.txt");

            var otherDir = TestUtils.CreateTestSpecificFolder(TestContext, "PropertiesWriterTest_OtherDir");
            var missingFileOutsideProjectDir = Path.Combine(otherDir, "missing.cs");

            var productFiles = new List <string>
            {
                productFile,
                productChineseFile,
                missingFileOutsideProjectDir
            };
            var productCS = new ProjectData(CreateProjectInfo("你好", "DB2E5521-3172-47B9-BA50-864F12E6DFFF", productProject, false, productFiles, productFileListFilePath, productCoverageFilePath, ProjectLanguages.CSharp, "UTF-8"));

            productCS.SonarQubeModuleFiles.Add(productFile);
            productCS.SonarQubeModuleFiles.Add(productChineseFile);
            productCS.SonarQubeModuleFiles.Add(missingFileOutsideProjectDir);

            var productVB = new ProjectData(CreateProjectInfo("vbProject", "B51622CF-82F4-48C9-9F38-FB981FAFAF3A", productProject, false, productFiles, productFileListFilePath, productCoverageFilePath, ProjectLanguages.VisualBasic, "UTF-8"));

            productVB.SonarQubeModuleFiles.Add(productFile);

            var testBaseDir          = TestUtils.CreateTestSpecificFolder(TestContext, "PropertiesWriterTest_TestBaseDir");
            var testProject          = CreateEmptyFile(testBaseDir, "MyTest.csproj");
            var testFile             = CreateEmptyFile(testBaseDir, "File.cs");
            var testFileListFilePath = Path.Combine(testBaseDir, "testManagedFiles.txt");

            var testFiles = new List <string>
            {
                testFile
            };
            var test = new ProjectData(CreateProjectInfo("my_test_project", "DA0FCD82-9C5C-4666-9370-C7388281D49B", testProject, true, testFiles, testFileListFilePath, null, ProjectLanguages.VisualBasic, "UTF-8"));

            test.SonarQubeModuleFiles.Add(testFile);

            var config = new AnalysisConfig()
            {
                SonarProjectKey     = "my_project_key",
                SonarProjectName    = "my_project_name",
                SonarProjectVersion = "1.0",
                SonarOutputDir      = @"C:\my_folder",
                SourcesDirectory    = @"d:\source_files\"
            };

            string actual = null;

            using (new AssertIgnoreScope()) // expecting the property writer to complain about the missing file
            {
                var writer = new PropertiesWriter(config);
                writer.WriteSettingsForProject(productCS, productCoverageFilePath);
                writer.WriteSettingsForProject(productVB, null);
                writer.WriteSettingsForProject(test, null);

                actual = writer.Flush();
            }

            var expected = string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                         @"DB2E5521-3172-47B9-BA50-864F12E6DFFF.sonar.projectKey=my_project_key:DB2E5521-3172-47B9-BA50-864F12E6DFFF
DB2E5521-3172-47B9-BA50-864F12E6DFFF.sonar.projectName=\u4F60\u597D
DB2E5521-3172-47B9-BA50-864F12E6DFFF.sonar.projectBaseDir={0}
DB2E5521-3172-47B9-BA50-864F12E6DFFF.sonar.sourceEncoding=utf-8
DB2E5521-3172-47B9-BA50-864F12E6DFFF.sonar.cs.vscoveragexml.reportsPaths={1}
DB2E5521-3172-47B9-BA50-864F12E6DFFF.sonar.sources=\
{0}\\File.cs,\
{0}\\\u4F60\u597D.cs,\
{3}

B51622CF-82F4-48C9-9F38-FB981FAFAF3A.sonar.projectKey=my_project_key:B51622CF-82F4-48C9-9F38-FB981FAFAF3A
B51622CF-82F4-48C9-9F38-FB981FAFAF3A.sonar.projectName=vbProject
B51622CF-82F4-48C9-9F38-FB981FAFAF3A.sonar.projectBaseDir={0}
B51622CF-82F4-48C9-9F38-FB981FAFAF3A.sonar.sourceEncoding=utf-8
B51622CF-82F4-48C9-9F38-FB981FAFAF3A.sonar.sources=\
{0}\\File.cs

DA0FCD82-9C5C-4666-9370-C7388281D49B.sonar.projectKey=my_project_key:DA0FCD82-9C5C-4666-9370-C7388281D49B
DA0FCD82-9C5C-4666-9370-C7388281D49B.sonar.projectName=my_test_project
DA0FCD82-9C5C-4666-9370-C7388281D49B.sonar.projectBaseDir={2}
DA0FCD82-9C5C-4666-9370-C7388281D49B.sonar.sourceEncoding=utf-8
DA0FCD82-9C5C-4666-9370-C7388281D49B.sonar.sources=
DA0FCD82-9C5C-4666-9370-C7388281D49B.sonar.tests=\
{2}\\File.cs

sonar.modules=DB2E5521-3172-47B9-BA50-864F12E6DFFF,B51622CF-82F4-48C9-9F38-FB981FAFAF3A,DA0FCD82-9C5C-4666-9370-C7388281D49B

",
                                         PropertiesWriter.Escape(productBaseDir),
                                         PropertiesWriter.Escape(productCoverageFilePath),
                                         PropertiesWriter.Escape(testBaseDir),
                                         PropertiesWriter.Escape(missingFileOutsideProjectDir),
                                         PropertiesWriter.Escape(config.SourcesDirectory));

            SaveToResultFile(productBaseDir, "Expected.txt", expected.ToString());
            SaveToResultFile(productBaseDir, "Actual.txt", actual);

            Assert.AreEqual(expected, actual);
        }
        private static void CompareAdditionalSettings(AnalysisConfig expected, AnalysisConfig actual)
        {
            // The XmlSerializer should create an empty list
            Assert.IsNotNull(actual.AdditionalConfig, "Not expecting the AdditionalSettings to be null for a reloaded file");

            if (expected.AdditionalConfig == null || expected.AdditionalConfig.Count == 0)
            {
                Assert.AreEqual(0, actual.AdditionalConfig.Count, "Not expecting any additional items. Count: {0}", actual.AdditionalConfig.Count);
                return;
            }

            foreach(ConfigSetting expectedSetting in expected.AdditionalConfig)
            {
                AssertSettingExists(expectedSetting.Id, expectedSetting.Value, actual);
            }
            Assert.AreEqual(expected.AdditionalConfig.Count, actual.AdditionalConfig.Count, "Unexpected number of additional settings");
        }
        public void GenerateReports(ITeamBuildSettings settings, AnalysisConfig config, ProjectInfoAnalysisResult result, ILogger logger)
        {
            Assert.IsFalse(methodCalled, "Generate reports has already been called");

            methodCalled = true;
        }
        private static void AssertSettingExists(string settingId, string expectedValue, AnalysisConfig actual)
        {
            Assert.IsNotNull(actual.AdditionalConfig, "Not expecting the additional settings to be null");

            ConfigSetting actualSetting = actual.AdditionalConfig.FirstOrDefault(s => string.Equals(settingId, s.Id, StringComparison.InvariantCultureIgnoreCase));
            Assert.IsNotNull(actualSetting, "Expected setting not found: {0}", settingId);
            Assert.AreEqual(expectedValue, actualSetting.Value, "Setting does not have the expected value. SettingId: {0}", settingId);
        }
Ejemplo n.º 44
0
        public void Roslyn_Settings_ValidSetup_LegacyServer_Override_Analyzers()
        {
            // Arrange

            // Create a valid config containing analyzer settings
            var config = new AnalysisConfig
            {
                SonarQubeVersion  = "6.7", // legacy version
                AnalyzersSettings = new List <AnalyzerSettings>
                {
                    new AnalyzerSettings
                    {
                        Language              = "cs",
                        RuleSetFilePath       = "d:\\my.ruleset",
                        AnalyzerAssemblyPaths = new List <string> {
                            "c:\\data\\new.analyzer1.dll", "c:\\new.analyzer2.dll"
                        },
                        AdditionalFilePaths = new List <string> {
                            "c:\\config.1.txt", "c:\\config.2.txt"
                        }
                    }
                }
            };

            var testSpecificProjectXml = @"
  <PropertyGroup>
    <ResolvedCodeAnalysisRuleSet>c:\should.be.overridden.ruleset</ResolvedCodeAnalysisRuleSet>
    <Language>C#</Language>
  </PropertyGroup>

  <ItemGroup>
    <!-- all analyzers specified in the project file should be removed -->
    <Analyzer Include='c:\should.be.removed.analyzer2.dll' />
    <Analyzer Include='should.be.removed.analyzer1.dll' />
  </ItemGroup>
  <ItemGroup>
    <!-- These additional files don't match ones in the config and should be preserved -->
    <AdditionalFiles Include='should.not.be.removed.additional1.txt' />
    <AdditionalFiles Include='should.not.be.removed.additional2.txt' />

    <!-- This additional file matches one in the config and should be replaced -->
    <AdditionalFiles Include='should.be.removed/CONFIG.1.TXT' />
    <AdditionalFiles Include='should.be.removed\CONFIG.2.TXT' />

  </ItemGroup>
";
            var projectFilePath        = CreateProjectFile(config, testSpecificProjectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.CreateProjectSpecificDirs);
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, "d:\\my.ruleset");

            AssertExpectedAdditionalFiles(result,
                                          result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath),
                                          "should.not.be.removed.additional1.txt",
                                          "should.not.be.removed.additional2.txt",
                                          "c:\\config.1.txt",
                                          "c:\\config.2.txt");

            AssertExpectedAnalyzers(result,
                                    "c:\\data\\new.analyzer1.dll",
                                    "c:\\new.analyzer2.dll");

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
Ejemplo n.º 45
0
        public void Roslyn_Settings_ValidSetup_NonLegacyServer_MergeSettings()
        {
            // Arrange

            var dir = TestUtils.CreateTestSpecificFolder(TestContext);
            var dummyQpRulesetPath = TestUtils.CreateValidEmptyRuleset(dir, "dummyQp");

            // Create a valid config containing analyzer settings
            var config = new AnalysisConfig
            {
                SonarQubeVersion = "7.5", // non-legacy version
                ServerSettings   = new AnalysisProperties
                {
                    new Property {
                        Id = "sonar.cs.roslyn.ignoreIssues", Value = "false"
                    }
                },
                AnalyzersSettings = new List <AnalyzerSettings>
                {
                    new AnalyzerSettings
                    {
                        Language              = "cs",
                        RuleSetFilePath       = dummyQpRulesetPath,
                        AnalyzerAssemblyPaths = new List <string> {
                            "c:\\data\\new\\analyzer1.dll", "c:\\new.analyzer2.dll"
                        },
                        AdditionalFilePaths = new List <string> {
                            "c:\\config\\duplicate.1.txt", "c:\\duplicate.2.txt"
                        }
                    }
                }
            };

            var testSpecificProjectXml = @"
  <PropertyGroup>
    <ResolvedCodeAnalysisRuleSet>c:\original.ruleset</ResolvedCodeAnalysisRuleSet>
    <Language>C#</Language>
  </PropertyGroup>

  <ItemGroup>
    <!-- all analyzers specified in the project file should be preserved -->
    <Analyzer Include='c:\original\should.be.removed\analyzer1.dll' />
    <Analyzer Include='original\should.be.preserved\analyzer3.dll' />
  </ItemGroup>
  <ItemGroup>
    <!-- These additional files don't match ones in the config and should be preserved -->
    <AdditionalFiles Include='should.not.be.removed.additional1.txt' />
    <AdditionalFiles Include='should.not.be.removed.additional2.txt' />

    <!-- This additional file matches one in the config and should be replaced -->
    <AdditionalFiles Include='d:/should.be.removed/DUPLICATE.1.TXT' />
    <AdditionalFiles Include='d:\should.be.removed\duplicate.2.TXT' />

  </ItemGroup>
";
            var projectFilePath        = CreateProjectFile(config, testSpecificProjectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.CreateProjectSpecificDirs);
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);

            var actualProjectSpecificConfFolder = result.GetCapturedPropertyValue(TargetProperties.ProjectSpecificConfDir);

            Directory.Exists(actualProjectSpecificConfFolder).Should().BeTrue();

            var expectedMergedRuleSetFilePath = Path.Combine(actualProjectSpecificConfFolder, "merged.ruleset");

            AssertExpectedResolvedRuleset(result, expectedMergedRuleSetFilePath);
            RuleSetAssertions.CheckMergedRulesetFile(actualProjectSpecificConfFolder,
                                                     @"c:\original.ruleset");

            AssertExpectedAdditionalFiles(result,
                                          result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath),
                                          "should.not.be.removed.additional1.txt",
                                          "should.not.be.removed.additional2.txt",
                                          "c:\\config\\duplicate.1.txt",
                                          "c:\\duplicate.2.txt");

            AssertExpectedAnalyzers(result,
                                    "c:\\data\\new\\analyzer1.dll",
                                    "c:\\new.analyzer2.dll",
                                    "original\\should.be.preserved\\analyzer3.dll");

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
Ejemplo n.º 46
0
        [TestMethod] //https://jira.codehaus.org/browse/SONARMSBRU-13: Analysis fails if a content file referenced in the MSBuild project does not exist
        public void FileGen_MissingFilesAreSkipped()
        {
            // Create project info with a managed file list and a content file list.
            // Each list refers to a file that does not exist on disk.
            // The missing files should not appear in the generated properties file.

            // Arrange
            string testDir         = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string projectBaseDir  = TestUtils.CreateTestSpecificFolder(TestContext, "Project1");
            string projectFullPath = CreateEmptyFile(projectBaseDir, "project1.proj");


            string existingManagedFile = CreateEmptyFile(projectBaseDir, "File1.cs");
            string existingContentFile = CreateEmptyFile(projectBaseDir, "Content1.txt");

            string missingManagedFile = Path.Combine(projectBaseDir, "MissingFile1.cs");
            string missingContentFile = Path.Combine(projectBaseDir, "MissingContent1.txt");

            ProjectInfo projectInfo = new ProjectInfo()
            {
                FullPath        = projectFullPath,
                AnalysisResults = new List <AnalysisResult>(),
                IsExcluded      = false,
                ProjectGuid     = Guid.NewGuid(),
                ProjectName     = "project1.proj",
                ProjectType     = ProjectType.Product
            };

            string analysisFileList = CreateFileList(projectBaseDir, "filesToAnalyze.txt", existingManagedFile, missingManagedFile, existingContentFile, missingContentFile);

            projectInfo.AddAnalyzerResult(AnalysisType.FilesToAnalyze, analysisFileList);

            string projectInfoDir      = TestUtils.CreateTestSpecificFolder(this.TestContext, "ProjectInfo1Dir");
            string projectInfoFilePath = Path.Combine(projectInfoDir, FileConstants.ProjectInfoFileName);

            projectInfo.Save(projectInfoFilePath);

            TestLogger     logger = new TestLogger();
            AnalysisConfig config = new AnalysisConfig()
            {
                SonarProjectKey     = "my_project_key",
                SonarProjectName    = "my_project_name",
                SonarProjectVersion = "1.0",
                SonarOutputDir      = testDir
            };

            // Act
            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);

            string actual = File.ReadAllText(result.FullPropertiesFilePath);

            // Assert
            AssertFileIsReferenced(existingContentFile, actual);
            AssertFileIsReferenced(existingManagedFile, actual);

            AssertFileIsNotReferenced(missingContentFile, actual);
            AssertFileIsNotReferenced(missingManagedFile, actual);

            logger.AssertSingleWarningExists(missingManagedFile);
            logger.AssertSingleWarningExists(missingContentFile);
        }