public void ScanDirectory_MultipleAnalyzerAssemblies()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            DiagnosticAssemblyScanner scanner = new DiagnosticAssemblyScanner(logger);

            string testDirectoryPath = Path.Combine(TestContext.DeploymentDirectory, "twoAnalyzers");

            string exampleAnalyzer1Path = Path.Combine(testDirectoryPath, "ExampleAnalyzer1.dll");
            Assert.IsTrue(File.Exists(exampleAnalyzer1Path), "Test setup error: expected assembly does not exist: {0}", exampleAnalyzer1Path);
            string exampleAnalyzer2Path = Path.Combine(testDirectoryPath, "ExampleAnalyzer2.dll");
            Assert.IsTrue(File.Exists(exampleAnalyzer2Path), "Test setup error: expected assembly does not exist: {0}", exampleAnalyzer2Path);

            // Act
            IEnumerable<DiagnosticAnalyzer> csharpDiagnostics = scanner.InstantiateDiagnostics(testDirectoryPath, LanguageNames.CSharp);
            IEnumerable<DiagnosticAnalyzer> vbDiagnostics = scanner.InstantiateDiagnostics(testDirectoryPath, LanguageNames.VisualBasic);

            // Assert
            // ConfigurableAnalyzer is both C# and VB, so should appear in both
            Assert.AreEqual(3, csharpDiagnostics.Count(), "Expecting 3 C# analyzers");
            Assert.AreEqual(2, vbDiagnostics.Count(), "Expecting 2 VB analyzers");

            // Using name comparison because type comparison fails if the types are from assemblies with different paths (even if copied)
            // Loaded from ExampleAnalyzer1.dll
            Assert_AnalyzerIsPresent(csharpDiagnostics, "ExampleAnalyzer1.CSharpAnalyzer");
            Assert_AnalyzerIsPresent(csharpDiagnostics, "ExampleAnalyzer1.ConfigurableAnalyzer");
            Assert_AnalyzerNotPresent(csharpDiagnostics, "ExampleAnalyzer1.AbstractAnalyzer");

            Assert_AnalyzerIsPresent(vbDiagnostics, "ExampleAnalyzer1.VBAnalyzer");
            Assert_AnalyzerIsPresent(vbDiagnostics, "ExampleAnalyzer1.ConfigurableAnalyzer");
            Assert_AnalyzerNotPresent(vbDiagnostics, "ExampleAnalyzer1.AbstractAnalyzer");

            // Loaded from ExampleAnalyzer2.dll
            Assert_AnalyzerIsPresent(csharpDiagnostics, "ExampleAnalyzer2.ExampleAnalyzer2");
        }
        public void JarBuilder_Build()
        {
            // Arrange
            IJdkWrapper jdkWrapper = new JdkWrapper();

            TestLogger logger = new TestLogger();
            string inputsDir = TestUtils.CreateTestDirectory(this.TestContext, "in");
            string outputsDir = TestUtils.CreateTestDirectory(this.TestContext, "out");

            string file1 = TestUtils.CreateTextFile("file1.txt", inputsDir, "file1 content");
            string file2 = TestUtils.CreateTextFile("file2.txt", inputsDir, "file2 content");

            // Act
            JarBuilder builder = new JarBuilder(logger, jdkWrapper);
            builder.SetManifestPropety("prop1", "prop1 value");

            builder.AddFile(file1, null);
            builder.AddFile(file2, "myorg\\myapp\\f2.txt");

            string finalJarPath = Path.Combine(outputsDir, "newJar.jar");
            bool success = builder.Build(finalJarPath);

            // Assert
            Assert.IsTrue(success, "Failed to build the jar file");
            
            new JarChecker(this.TestContext, finalJarPath)
                .JarContainsFiles(
                    "META-INF\\MANIFEST.MF",
                    "file1.txt",
                    "myorg\\myapp\\f2.txt");
        }
        public void ArgProc_AnalyzerRef_Invalid()
        {
            // 0. Setup
            TestLogger logger;
            string[] rawArgs;
            ProcessedArgs actualArgs;

            // 1. No value
            logger = new TestLogger();
            rawArgs = new string [] { "/analyzer:" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsNotProcessed(actualArgs, logger);

            // 2. Id and missing version
            logger = new TestLogger();
            rawArgs = new string[] { "/analyzer:testing.id.missing.version:" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsNotProcessed(actualArgs, logger);

            // 3. Id and invalid version
            logger = new TestLogger();
            rawArgs = new string[] { "/analyzer:testing.id.invalid.version:1.0.-invalid.version.1" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsNotProcessed(actualArgs, logger);

            // 4. Missing id
            logger = new TestLogger();
            rawArgs = new string[] { "/analyzer::2.1.0" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsNotProcessed(actualArgs, logger);
        }
        public void Generate_LicenseAcceptanceNotRequired_Succeeds()
        {
            // Arrange
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(this.TestContext);

            // Multi-level dependencies: no package requires license acceptence
            IPackage grandchild = CreatePackageWithAnalyzer(remoteRepoBuilder, "grandchild.id", "1.2", License.NotRequired /* no dependencies */);
            IPackage child = CreatePackageWithAnalyzer(remoteRepoBuilder, "child.id", "1.1", License.NotRequired, grandchild);
            CreatePackageWithAnalyzer(remoteRepoBuilder, "parent.id", "1.0", License.NotRequired, child);

            TestLogger logger = new TestLogger();
            AnalyzerPluginGenerator apg = CreateTestSubjectWithFakeRemoteRepo(remoteRepoBuilder, logger);

            // 1. Acceptance not required -> succeeds if accept = false
            ProcessedArgs args = CreateArgs("parent.id", "1.0", "cs", null, false /* accept licenses */ , outputDir);
            bool result = apg.Generate(args);
            Assert.IsTrue(result, "Generator should succeed if there are no licenses to accept");

            logger.AssertErrorsLogged(0);
            logger.AssertWarningNotLogged("parent.id"); // not expecting warnings about packages that don't require acceptance
            logger.AssertWarningNotLogged("child.id");
            logger.AssertWarningNotLogged("grandchild.id");

            // 2. Acceptance not required -> succeeds if accept = true
            args = CreateArgs("parent.id", "1.0", "cs", null, true /* accept licenses */ , outputDir);
            result = apg.Generate(args);
            Assert.IsTrue(result, "Generator should succeed if there are no licenses to accept");

            logger.AssertErrorsLogged(0);
            logger.AssertWarningNotLogged("parent.id"); // not expecting warnings about packages that don't require acceptance
            logger.AssertWarningNotLogged("child.id");
            logger.AssertWarningNotLogged("grandchild.id");
        }
        public void ArgProc_AnalyzerRef_Valid()
        {
            // 0. Setup
            TestLogger logger;
            string[] rawArgs;
            ProcessedArgs actualArgs;

            // 1. Id but no version
            logger = new TestLogger();
            rawArgs = new string[] { "/a:testing.id.no.version" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsProcessed(actualArgs, logger, "testing.id.no.version", null, null, false);

            // 2. Id and version
            logger = new TestLogger();
            rawArgs = new string[] { "/analyzer:testing.id.with.version:1.0.0-rc1" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsProcessed(actualArgs, logger, "testing.id.with.version", "1.0.0-rc1", null, false);

            // 3. Id containing a colon, with version
            logger = new TestLogger();
            rawArgs = new string[] { "/analyzer:id.with:colon:2.1.0" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsProcessed(actualArgs, logger, "id.with:colon", "2.1.0", null, false);
        }
        public void ArgProc_AcceptLicensesInvalid()
        {
            // 0. Setup
            TestLogger logger;
            string[] rawArgs;
            ProcessedArgs actualArgs;

            // 1. Correct text, wrong case -> invalid
            logger = new TestLogger();
            rawArgs = new string[] { "/a:validId", "/ACCEPTLICENSES" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsNotProcessed(actualArgs, logger);

            // 2. Unrecognized argument -> invalid
            logger = new TestLogger();
            rawArgs = new string[] { "/a:validId", "/acceptLicenses=true" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsNotProcessed(actualArgs, logger);

            // 3. Unrecognized argument -> invalid
            logger = new TestLogger();
            rawArgs = new string[] { "/a:validId", "/acceptLicensesXXX" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsNotProcessed(actualArgs, logger);
        }
        public void Generate_NoAnalyzersFoundInPackage_GenerateFails()
        {
            // Arrange
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");

            TestLogger logger = new TestLogger();

            // Create a fake remote repo containing a package that does not contain analyzers
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(this.TestContext);
            remoteRepoBuilder.CreatePackage("no.analyzers.id", "0.9", TestUtils.CreateTextFile("dummy.txt", outputDir), License.NotRequired /* no dependencies */ );

            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(remoteRepoBuilder.FakeRemoteRepo, GetLocalNuGetDownloadDir(), logger);
            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);
            ProcessedArgs args = CreateArgs("no.analyzers.id", "0.9", "cs", null, false, false, outputDir);

            // Act
            bool result = apg.Generate(args);

            // Assert
            Assert.IsFalse(result, "Expecting generation to fail");
            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "no.analyzers.id"));
            logger.AssertSingleWarningExists(UIResources.APG_NoAnalyzersInTargetSuggestRecurse);
            logger.AssertWarningsLogged(2);
            AssertSqaleTemplateDoesNotExist(outputDir);
        }
        public void RoslynPlugin_GenerateForMultiLevelAnalyzers_Succeeds()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");

            // Create a valid analyzer package
            RoslynAnalyzer11.CSharpAnalyzer analyzer = new RoslynAnalyzer11.CSharpAnalyzer();

            // Parent and children all have analyzers, expecting plugins for all three
            string fakeRemoteNuGetDir = TestUtils.CreateTestDirectory(this.TestContext, ".fakeRemoteNuGet");
            IPackageManager fakeRemotePkgMgr = CreatePackageManager(fakeRemoteNuGetDir);
            IPackage child1 = AddPackage(fakeRemotePkgMgr, "Analyzer.Child1", "1.1.0", analyzer.GetType().Assembly.Location);
            IPackage child2 = AddPackage(fakeRemotePkgMgr, "Analyzer.Child2", "1.2.0", analyzer.GetType().Assembly.Location);
            IPackage targetPkg = AddPackage(fakeRemotePkgMgr, "Empty.Parent", "1.0.0", analyzer.GetType().Assembly.Location, child1, child2);

            string localPackageDestination = TestUtils.CreateTestDirectory(this.TestContext, ".localpackages");

            // Act
            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(fakeRemotePkgMgr.LocalRepository, localPackageDestination, logger);
            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);
            ProcessedArgs args = new ProcessedArgs(targetPkg.Id, targetPkg.Version, "cs", null, false,
                true /* generate plugins for dependencies with analyzers*/, outputDir);
            bool result = apg.Generate(args);

            // Assert
            Assert.IsTrue(result);

            // Expecting one plugin per dependency with analyzers
            CheckJarGeneratedForPackage(outputDir, analyzer, targetPkg);
            CheckJarGeneratedForPackage(outputDir, analyzer, child1);
            CheckJarGeneratedForPackage(outputDir, analyzer, child2);
            AssertJarsGenerated(outputDir, 3);
        }
        public void AssemblyResolver_NoImpactOnDefaultResolution()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string testFolder = TestUtils.CreateTestDirectory(this.TestContext);
            CompileSimpleAssembly("SimpleAssembly.dll", testFolder, logger);

            object simpleObject = null;

            // Act
            using (AssemblyResolver resolver = new AssemblyResolver(logger, testFolder))
            {
                // Look in every assembly under the supplied directory
                foreach (string assemblyPath in Directory.GetFiles(testFolder, "*.dll", SearchOption.AllDirectories))
                {
                    Assembly assembly = Assembly.LoadFile(assemblyPath);
                    
                    foreach (Type type in assembly.GetExportedTypes())
                    {
                        if (!type.IsAbstract)
                        {
                            simpleObject = Activator.CreateInstance(type);
                        }
                    }
                }

                // Assert
                Assert.IsNotNull(simpleObject);
                Assert.AreEqual<string>("SimpleProgram", simpleObject.GetType().ToString());
                AssertResolverCaller(resolver);

            }
        }
        public void RuleGen_SimpleRules()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            ConfigurableAnalyzer analyzer = new ConfigurableAnalyzer();
            var diagnostic1 = analyzer.RegisterDiagnostic(key: "DiagnosticID1", description: "Some description", helpLinkUri: "www.bing.com", tags: new[] { "unnecessary" });
            var diagnostic2 = analyzer.RegisterDiagnostic(key: "Diagnostic2", description: "");

            IRuleGenerator generator = new RuleGenerator(logger);

            // Act
            Rules rules = generator.GenerateRules(new[] { analyzer });

            // Assert
            AssertExpectedRuleCount(2, rules);

            Rule rule1 = rules.Single(r => r.Key == diagnostic1.Id);
            VerifyRule(diagnostic1, rule1);

            Assert.IsTrue(rule1.Description.Contains(diagnostic1.Description.ToString()), "Invalid rule description");
            Assert.IsTrue(rule1.Description.Contains(diagnostic1.HelpLinkUri), "Invalid rule description");
            Assert.IsFalse(rule1.Description.Trim().StartsWith("<![CDATA"), "Description should not be formatted as a CData section");

            Rule rule2 = rules.Single(r => r.Key == diagnostic2.Id);
            VerifyRule(diagnostic2, rule2);

            Assert.IsTrue(rule2.Description.Contains(UIResources.RuleGen_NoDescription), "Invalid rule description");
        }
        public void RepoFactory_MultipleEnabledSources_RepoCreated()
        {
            // Arrange
            TestLogger logger = new TestLogger();

            // Create a valid config settings file that specifies the package sources to use
            string configXml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageSources>
    <add key=""local1_inactive"" value=""c:\inactiveCache\should.be.ignored"" />
    <add key=""local2_active"" value=""d:\active_cache"" />
    <add key=""local3_active"" value=""c:\another\active\cache"" />
  </packageSources>
  <disabledPackageSources>
    <add key=""local1_inactive"" value=""true"" />
  </disabledPackageSources>
</configuration>";

            Settings settings = CreateSettingsFromXml(configXml);

            // Act
            IPackageRepository actualRepo = NuGetRepositoryFactory.CreateRepository(settings, logger);

            // Assert
            Assert.IsInstanceOfType(actualRepo, typeof(AggregateRepository));
            AggregateRepository actualAggregateRepo = (AggregateRepository)actualRepo;

            AssertExpectedPackageSources(actualAggregateRepo,
                "d:\\active_cache",
                "c:\\another\\active\\cache");

            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(0);
        }
        public void PluginBuilder_Simple()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            PluginBuilder builder = CreateValidBuilder(logger);

            // Act and assert
            BuildAndCheckSucceeds(builder, logger);
        }
        public void PluginBuilder_PluginNameIsRequired()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            PluginBuilder builder = CreateValidBuilder(logger);
            builder.SetProperty(WellKnownPluginProperties.PluginName, null);

            // Act and assert
            AssertException.Expect<System.InvalidOperationException>(() => builder.Build());
        }
        public void PluginBuilder_InvalidSource()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            PluginBuilder builder = CreateValidBuilder(logger);

            string invalidSource = this.CreateInputSourceFile("Program.java", "invalid java code");
            builder.AddSourceFile(invalidSource);

            // Act
            BuildAndCheckCompileFails(builder, logger);
        }
        public void ArgProc_EmptyArgs()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string[] rawArgs = { };

            // Act
            ProcessedArgs actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            // Assert
            AssertArgumentsNotProcessed(actualArgs, logger);            
        }
        public void InstantiateDiags_CSharp_NoFiles()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            DiagnosticAssemblyScanner scanner = new DiagnosticAssemblyScanner(logger);

            // Act
            IEnumerable<DiagnosticAnalyzer> result = scanner.InstantiateDiagnostics(LanguageNames.CSharp /* no files */);

            // Assert
            Assert.IsNotNull(result, "Not expecting InstantiateDiagnostics to return null");
            Assert.IsFalse(result.Any(), "Not expecting any diagnostics to have been found");
        }
        public void ArgProc_AcceptLicenses_Valid()
        {
            // 0. Setup
            TestLogger logger;
            string[] rawArgs;
            ProcessedArgs actualArgs;

            // 1. Correct argument -> valid and accept is true
            logger = new TestLogger();
            rawArgs = new string[] { "/a:validId", "/acceptLicenses" };
            actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger);

            AssertArgumentsProcessed(actualArgs, logger, "validId", null, null, true);
        }
        public void TestAssemblyNameFileNameAssociation()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            Assembly assembly = typeof(AssemblyResolver).Assembly;
            string assemblyName = assembly.FullName;
            string actualFileName = Path.GetFileName(assembly.Location);

            // Act
            string testFileName = AssemblyResolver.CreateFileNameFromAssemblyName(assemblyName);

            // Assert
            Assert.AreEqual<string>(actualFileName, testFileName);
        }
        public void AssemblyResolver_NonExistentAssembly_ResolutionFails()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string testFolder = TestUtils.CreateTestDirectory(this.TestContext);

            // Act
            using (AssemblyResolver resolver = new AssemblyResolver(logger, testFolder))
            {
                AssertAssemblyLoadFails("nonexistent library");

                // Assert
                AssertResolverCaller(resolver);
            }
        }
        public void NuGet_TestDependencyResolutionFailure()
        {
            // Arrange
            string testDir = TestUtils.CreateTestDirectory(this.TestContext);
            TestLogger logger = new TestLogger();
            NuGetPackageHandler handler = new NuGetPackageHandler(logger);

            // Act
            // Fetch a package that should fail due to pre-release dependencies
            IPackage package = handler.FetchPackage(AnalyzerPluginGenerator.NuGetPackageSource, "codeCracker", null, testDir);

            // Assert
            // No files should have been downloaded
            Assert.IsTrue(Directory.GetFiles(testDir).Length == 0);
            Assert.IsNull(package);
        }
        public void RoslynPlugin_GenerateForValidAnalyzer_Succeeds()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");
            PluginInspector inspector = CreatePluginInspector(logger);

            // Create a valid analyzer package
            ExampleAnalyzer1.CSharpAnalyzer analyzer = new ExampleAnalyzer1.CSharpAnalyzer();

            string packageId = "analyzer1.id1";
            string localNuGetDir = TestUtils.CreateTestDirectory(this.TestContext, ".localNuGet");
            IPackageManager localNuGetStore = CreatePackageManager(localNuGetDir);
            AddPackage(localNuGetStore, packageId, "1.0", analyzer.GetType().Assembly.Location);

            // Act
            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(localNuGetDir, logger);
            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);
            bool result = apg.Generate(new Roslyn.CommandLine.NuGetReference(packageId, new SemanticVersion("1.0")), "cs", null, outputDir);

            // Assert
            Assert.IsTrue(result);
            string jarFilePath = AssertPluginJarExists(outputDir);

            JarInfo jarInfo = inspector.GetPluginDescription(jarFilePath);

            if (jarInfo != null)
            {
                this.TestContext.AddResultFile(jarInfo.FileName);
            }

            Assert.IsNotNull(jarInfo, "Failed to process the generated jar successfully");

            AssertPropertyDefinitionExists(packageId + "_sarif.AnalyzerId", jarInfo);
            AssertPropertyDefinitionExists(packageId + "_sarif.RuleNamespace", jarInfo);
            AssertPropertyDefinitionExists(packageId + "_sarif.nuget.packageId", jarInfo);
            AssertPropertyDefinitionExists(packageId + "_sarif.nuget.packageVersion", jarInfo);

            JarInfo.RulesDefinition rulesDefn = AssertRulesDefinitionExists(jarInfo);
            AssertRepositoryIsValid(rulesDefn.Repository);

            AssertExpectedRulesExist(analyzer, rulesDefn.Repository);

            Assert.AreEqual(5, jarInfo.Extensions.Count, "Unexpected number of extensions");
        }
        public void InstantiateDiags_VB_AnalyzersFound()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            DiagnosticAssemblyScanner scanner = new DiagnosticAssemblyScanner(logger);

            string roslynAnalyzer11DllPath = typeof(RoslynAnalyzer11.CSharpAnalyzer).Assembly.Location;

            // Act
            IEnumerable<DiagnosticAnalyzer> result = scanner.InstantiateDiagnostics(LanguageNames.VisualBasic, roslynAnalyzer11DllPath);

            // Assert
            Assert_AnalyzerIsPresent(result, typeof(RoslynAnalyzer11.VBAnalyzer));
            Assert_AnalyzerIsPresent(result, typeof(RoslynAnalyzer11.ConfigurableAnalyzer));
            Assert_AnalyzerNotPresent(result, typeof(RoslynAnalyzer11.AbstractAnalyzer)); // not expecting abstract analyzers

            Assert.AreEqual(2, result.Count(), "Expecting 2 VB analyzers");
        }
        public void InstantiateDiags_VB_NoAnalyzers()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            DiagnosticAssemblyScanner scanner = new DiagnosticAssemblyScanner(logger);

            string corLibDllPath = typeof(object).Assembly.Location;
            string thisDllPath = this.GetType().Assembly.Location;

            // Act
            IEnumerable<DiagnosticAnalyzer> result = scanner.InstantiateDiagnostics(LanguageNames.VisualBasic,
                corLibDllPath,
                thisDllPath);

            // Assert
            Assert.IsNotNull(result, "Not expecting InstantiateDiagnostics to return null");
            Assert.IsFalse(result.Any(), "Not expecting any diagnostics to have been found");
        }
        public void ScanDirectoryWithNoAnalyzerAssemblies()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            DiagnosticAssemblyScanner scanner = new DiagnosticAssemblyScanner(logger);

            // place a single assembly in the test directory, that does not have any analyzers in it
            string noAnalyzerAssemblyPath = typeof(DiagnosticAssemblyScannerTests).Assembly.Location;
            string testDirectoryPath = TestUtils.CreateTestDirectory(this.TestContext);
            string testAssemblyPath = Path.Combine(testDirectoryPath, Path.GetFileName(noAnalyzerAssemblyPath));
            File.Copy(noAnalyzerAssemblyPath, testAssemblyPath);

            // Act
            IEnumerable<DiagnosticAnalyzer> csharpDiagnostics = scanner.InstantiateDiagnostics(testDirectoryPath, LanguageNames.CSharp);
            IEnumerable<DiagnosticAnalyzer> vbDiagnostics = scanner.InstantiateDiagnostics(testDirectoryPath, LanguageNames.VisualBasic);

            // Assert
            Assert.AreEqual(0, csharpDiagnostics.Count(), "No analyzers should have been detected");
            Assert.AreEqual(0, vbDiagnostics.Count(), "No analyzers should have been detected");
        }
        public void CheckNoTags()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            ConfigurableAnalyzer analyzer = new ConfigurableAnalyzer();
            var diagnostic1 = analyzer.RegisterDiagnostic(key: "DiagnosticID1", tags: new[] { "t1" });
            var diagnostic2 = analyzer.RegisterDiagnostic(key: "DiagnosticID2", tags: new[] { "T2" });

            IRuleGenerator generator = new RuleGenerator(logger);

            // Act
            Rules rules = generator.GenerateRules(new[] { analyzer });

            // Assert
            foreach (Rule rule in rules)
            {
                VerifyRuleValid(rule);
                
                Assert.IsNull(rule.Tags);
            }
        }
        public void InstantiateDiags_CSharp_AnalyzersFound()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            DiagnosticAssemblyScanner scanner = new DiagnosticAssemblyScanner(logger, this.TestContext.DeploymentDirectory);

            string roslynAnalyzer11DllPath = typeof(RoslynAnalyzer11.CSharpAnalyzer).Assembly.Location;

            // Act
            IEnumerable<DiagnosticAnalyzer> result = scanner.InstantiateDiagnostics(LanguageNames.CSharp, roslynAnalyzer11DllPath);

            // Assert
            Assert_AnalyzerIsPresent(result, typeof(RoslynAnalyzer11.CSharpAnalyzer));
            Assert_AnalyzerIsPresent(result, typeof(RoslynAnalyzer11.ConfigurableAnalyzer));
            Assert_AnalyzerIsPresent(result, "RoslynAnalyzer11.InternalAnalyzer");

            Assert_AnalyzerNotPresent(result, typeof(RoslynAnalyzer11.AbstractAnalyzer)); // not expecting abstract analyzers
            Assert_AnalyzerNotPresent(result, typeof(RoslynAnalyzer11.UnattributedAnalyzer)); // not expecting analyzers without attributes

            Assert.AreEqual(3, result.Count(), "Expecting 3 C# analyzers");
        }
        public void NuGet_TestPackageDownload_PreRelease_Release()
        {
            // Arrange
            string targetNuGetRoot = TestUtils.CreateTestDirectory(this.TestContext, ".nuget.target");

            // Create test NuGet payload and packages
            IPackageRepository fakeRemoteRepo = CreateTestPackageWithSingleDependency(PreReleaseVersion, ReleaseVersion);

            TestLogger logger = new TestLogger();
            NuGetPackageHandler handler = new NuGetPackageHandler(fakeRemoteRepo, targetNuGetRoot, logger);

            // Act
            // Attempt to download a package which is not released with a dependency that is released
            IPackage package = handler.FetchPackage(DependentPackageId, null);

            // Assert
            AssertExpectedPackage(package, DependentPackageId, PreReleaseVersion);
            // Packages should have been downloaded
            AssertPackageDownloaded(targetNuGetRoot, DependentPackageId, PreReleaseVersion);
            AssertPackageDownloaded(targetNuGetRoot, TestPackageId, ReleaseVersion);
        }
        public void NuGet_TestPackageDownload_PreRelease_Release()
        {
            // Arrange
            string testDir = TestUtils.CreateTestDirectory(this.TestContext);
            string testDownloadDir = Path.Combine(testDir, "download");

            // Create test NuGet payload and packages
            BuildTestPackages(false, true);

            TestLogger logger = new TestLogger();
            NuGetPackageHandler handler = new NuGetPackageHandler(testDir, logger);

            // Act
            // Attempt to download a package which is not released with a dependency that is released
            IPackage package = handler.FetchPackage(DependentPackageName, null, testDownloadDir);

            // Assert
            AssertExpectedPackage(package, DependentPackageName, PreReleaseVersion);
            // Packages should have been downloaded
            AssertPackageDownloaded(testDownloadDir, DependentPackageName, PreReleaseVersion);
            AssertPackageDownloaded(testDownloadDir, TestPackageName, ReleaseVersion);
        }
        public void JarBuilder_Layout()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string inputsDir = TestUtils.CreateTestDirectory(this.TestContext, "inputs");
            string rootTempDir = TestUtils.CreateTestDirectory(this.TestContext, "temp");
            string contentDir = Path.Combine(rootTempDir, JarBuilder.JAR_CONTENT_DIRECTORY_NAME);

            string file1 = TestUtils.CreateTextFile("file1.txt", inputsDir, "file1 content");
            string file2 = TestUtils.CreateTextFile("file2.txt", inputsDir, "file2 content");
            string file3 = TestUtils.CreateTextFile("file3.txt", inputsDir, "file3 content");

            // Act
            JarBuilder builder = new JarBuilder(logger, new MockJdkWrapper());
            builder.SetManifestPropety("prop1", "prop1 value");
            builder.SetManifestPropety("prop2", "prop2 value");
            builder.SetManifestPropety("prop3", "prop3 value");

            builder.AddFile(file1, null);
            builder.AddFile(file2, "myorg\\myapp\\f2.txt");
            builder.AddFile(file3, "resources\\f3.txt");

            builder.LayoutFiles(rootTempDir);

            // Assert
            string content = TestUtils.AssertFileExists(JdkWrapper.MANIFEST_FILE_NAME, rootTempDir);
            AssertManifestPropertyExists(content, "prop1", "prop1 value");
            AssertManifestPropertyExists(content, "prop2", "prop2 value");
            AssertManifestPropertyExists(content, "prop3", "prop3 value");

            content = TestUtils.AssertFileExists("file1.txt", contentDir);
            Assert.AreEqual("file1 content", content, "Unexpected file content");

            content = TestUtils.AssertFileExists("myorg\\myapp\\f2.txt", contentDir);
            Assert.AreEqual("file2 content", content, "Unexpected file content");

            content = TestUtils.AssertFileExists("resources\\f3.txt", contentDir);
            Assert.AreEqual("file3 content", content, "Unexpected file content");
        }
        public void RulesMustHaveDescription()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            ConfigurableAnalyzer analyzer = new ConfigurableAnalyzer();
            var diagnostic1 = analyzer.RegisterDiagnostic(key: "DiagnosticID1", description: null);
            var diagnostic2 = analyzer.RegisterDiagnostic(key: "DiagnosticID1", description: "");
            var diagnostic3 = analyzer.RegisterDiagnostic(key: "DiagnosticID2", description: " ");

            IRuleGenerator generator = new RuleGenerator(logger);

            // Act
            Rules rules = generator.GenerateRules(new[] { analyzer });

            // Assert
            foreach (Rule rule in rules)
            {
                VerifyRuleValid(rule);

                Assert.AreEqual(rule.Description, UIResources.RuleGen_NoDescription);
            }
        }