Ejemplo n.º 1
0
        public ProjectBuildHandler(ILogger logger, string projectPath, List <string> oldReferences, List <string> references, AnalyzerConfiguration analyzerConfiguration = null)
        {
            Logger = logger;
            _analyzerConfiguration = analyzerConfiguration;
            _projectPath           = projectPath;

            this.Compilation = CreateManualCompilation(projectPath, references);
            //We don't want a compilation if there are no older references, because it'll slow down the analysis
            this.PrePortCompilation = oldReferences?.Any() == true?CreateManualCompilation(projectPath, oldReferences) : null;

            Errors = new List <string>();
            MissingMetaReferences = new List <string>();

            var errors = Compilation.GetDiagnostics()
                         .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error && diagnostic.GetMessage()?.Equals(KnownErrors.NoMainMethodMessage) != true);

            if (errors.Any())
            {
                Logger.LogError($"Build Errors: {Compilation.AssemblyName}: {errors.Count()} " +
                                $"compilation errors: \n\t{string.Join("\n\t", errors.Where(e => false).Select(e => e.ToString()))}");
                Logger.LogDebug(String.Join("\n", errors));

                foreach (var error in errors)
                {
                    Errors.Add(error.ToString());
                }
            }
            else
            {
                Logger.LogInformation($"{Compilation.AssemblyName} compiled with no errors");
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of SolutionRewriter, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="analyzerConfiguration">Configuration for code analyzer to be used (AnalyzerConfiguration)</param>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionRewriter(string solutionFilePath, List <ProjectConfiguration> solutionConfiguration, IProjectRewriterFactory projectRewriterFactory = null)
        {
            DownloadResourceFiles();
            _solutionResult         = new SolutionResult();
            _projectRewriterFactory = projectRewriterFactory ?? new DefaultProjectRewriterFactory();
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                MetaDataSettings = new MetaDataSettings()
                {
                    Annotations           = true,
                    DeclarationNodes      = true,
                    MethodInvocations     = true,
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    InterfaceDeclarations = true,
                    MemberAccess          = true,
                    ElementAccess         = true
                }
            };

            _projectRewriters = new List <ProjectRewriter>();
            CodeAnalyzer analyzer        = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);
            var          analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;

            InitializeProjectRewriters(analyzerResults, solutionConfiguration);
        }
Ejemplo n.º 3
0
 public WorkspaceBuilder(ILogger logger, string workspacePath, AnalyzerConfiguration analyzerConfiguration = null)
 {
     this.ProjectResults    = new List <ProjectBuildResult>();
     this._workspacePath    = workspacePath;
     this.Logger            = logger;
     _analyzerConfiguration = analyzerConfiguration;
 }
Ejemplo n.º 4
0
        private CodeAnalyzer CreateDefaultCodeAnalyzer()
        {
            // Create a basic logger
            var loggerFactory = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug).AddConsole());
            var logger        = loggerFactory.CreateLogger("");

            // Set up analyzer config
            var configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings   = { GenerateJsonOutput = false },
                MetaDataSettings =
                {
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    GenerateBinFiles      = true,
                    LocationData          = false,
                    MethodInvocations     = false,
                    LiteralExpressions    = false,
                    LambdaMethods         = false,
                    DeclarationNodes      = false,
                    Annotations           = false,
                    InterfaceDeclarations = false,
                    EnumDeclarations      = false,
                    StructDeclarations    = false,
                    ReturnStatements      = false,
                    InvocationArguments   = false,
                    ElementAccess         = false,
                    MemberAccess          = false
                }
            };

            return(CodeAnalyzerFactory.GetAnalyzer(configuration, logger));
        }
Ejemplo n.º 5
0
        public ProjectBuildHandler(ILogger logger, AnalyzerConfiguration analyzerConfiguration = null)
        {
            Logger = logger;
            _analyzerConfiguration = analyzerConfiguration;

            Errors = new List <string>();
        }
Ejemplo n.º 6
0
        public async Task TestAnalyzer()
        {
            string projectPath = string.Concat(GetTstPath(Path.Combine(new[] { "Projects", "CodelyzerDummy", "CodelyzerDummy" })), ".csproj");

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput    = true,
                    GenerateGremlinOutput = false,
                    GenerateRDFOutput     = false,
                    OutputPath            = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = true,
                    ReferenceData      = true,
                    LoadBuildData      = true
                }
            };
            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);

            using AnalyzerResult result = await analyzer.AnalyzeProject(projectPath);

            Assert.True(result != null);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of Solution Port, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you 
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionPort(string solutionFilePath, List<PortCoreConfiguration> solutionConfiguration, ILogger logger = null)
        {
            if (logger != null)
            {
                LogHelper.Logger = logger;
            }
            _portSolutionResult = new PortSolutionResult(solutionFilePath);
            _solutionPath = solutionFilePath;
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp);
            analyzerConfiguration.MetaDataSettings = new MetaDataSettings()
            {
                Annotations = true,
                DeclarationNodes = true,
                MethodInvocations = true,
                ReferenceData = true,
                LoadBuildData = true,
                InterfaceDeclarations = true
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);
            var analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;

            _context = new MetricsContext(solutionFilePath, analyzerResults);
            InitSolutionRewriter(analyzerResults, solutionConfiguration);
        }
Ejemplo n.º 8
0
        protected List <AnalyzerResult> GenerateSolutionAnalysis(string solutionPath)
        {
            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = false,
                    ReferenceData      = true,
                    LoadBuildData      = true,
                    ElementAccess      = true,
                    MemberAccess       = true
                }
            };
            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            var          result   = analyzer.AnalyzeSolution(solutionPath).Result;

            return(result);
        }
Ejemplo n.º 9
0
        private CodeAnalyzer GetCodeAnalyzer()
        {
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp);
            ExportSettings        exportSettings        = new ExportSettings()
            {
                GenerateGremlinOutput = false, GenerateJsonOutput = false, GenerateRDFOutput = false
            };
            MetaDataSettings metaDataSettings = new MetaDataSettings()
            {
                Annotations        = false,
                DeclarationNodes   = false,
                LambdaMethods      = false,
                LiteralExpressions = false,
                LocationData       = false,
                MethodInvocations  = false,
                ReferenceData      = false
            };

            analyzerConfiguration.ExportSettings   = exportSettings;
            analyzerConfiguration.MetaDataSettings = metaDataSettings;

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);

            return(analyzer);
        }
 public WorkspaceBuilderHelper(ILogger logger, string workspacePath, AnalyzerConfiguration analyzerConfiguration = null)
 {
     this.Logger            = logger;
     this.WorkspacePath     = workspacePath;
     this.Projects          = new List <ProjectAnalysisResult>();
     this.FailedProjects    = new List <ProjectAnalysisResult>();
     _analyzerConfiguration = analyzerConfiguration;
 }
Ejemplo n.º 11
0
        public async Task TestMvcMusicStore()
        {
            string solutionPath = Directory.EnumerateFiles(tempDir, "MvcMusicStore.sln", SearchOption.AllDirectories).FirstOrDefault();

            FileAssert.Exists(solutionPath);

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = false,
                    ReferenceData      = true,
                    LoadBuildData      = true
                }
            };
            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);

            using var result = (await analyzer.AnalyzeSolution(solutionPath)).FirstOrDefault();
            Assert.True(result != null);
            Assert.False(result.ProjectBuildResult.IsSyntaxAnalysis);

            Assert.AreEqual(28, result.ProjectResult.SourceFiles.Count);

            //Project has 16 nuget references and 19 framework/dll references:
            Assert.AreEqual(29, result.ProjectResult.ExternalReferences.NugetReferences.Count);
            Assert.AreEqual(24, result.ProjectResult.ExternalReferences.SdkReferences.Count);

            var homeController = result.ProjectResult.SourceFileResults.Where(f => f.FilePath.EndsWith("HomeController.cs")).FirstOrDefault();

            Assert.NotNull(homeController);

            var classDeclarations = homeController.Children.OfType <Codelyzer.Analysis.Model.NamespaceDeclaration>().FirstOrDefault();

            Assert.Greater(classDeclarations.Children.Count, 0);

            var classDeclaration = homeController.Children.OfType <Codelyzer.Analysis.Model.NamespaceDeclaration>().FirstOrDefault().Children[0];

            Assert.NotNull(classDeclaration);

            var declarationNodes   = classDeclaration.Children.OfType <Codelyzer.Analysis.Model.DeclarationNode>();
            var methodDeclarations = classDeclaration.Children.OfType <Model.MethodDeclaration>();

            //HouseController has 3 identifiers declared within the class declaration:
            Assert.AreEqual(4, declarationNodes.Count());

            //It has 2 method declarations
            Assert.AreEqual(2, methodDeclarations.Count());
        }
Ejemplo n.º 12
0
        public ProjectBuildHandler(ILogger logger, AnalyzerConfiguration analyzerConfiguration = null, List <string> metaReferences = null)
        {
            Logger = logger;
            _analyzerConfiguration = analyzerConfiguration;
            _metaReferences        = metaReferences;

            Errors = new List <string>();
            MissingMetaReferences = new List <string>();
        }
Ejemplo n.º 13
0
        public async Task TestWebApiWithReferencesUsingGenerator(string version)
        {
            var solutionPath = CopySolutionFolderToTemp("WebApiWithReferences.sln", tempDir);

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    DeclarationNodes   = true,
                    LocationData       = false,
                    ReferenceData      = true,
                    LoadBuildData      = true,
                    ElementAccess      = true,
                    MemberAccess       = true
                }
            };

            CodeAnalyzer analyzer     = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            SolutionPort solutionPort = new SolutionPort(solutionPath);

            var resultEnumerator = analyzer.AnalyzeSolutionGeneratorAsync(solutionPath).GetAsyncEnumerator();

            while (await resultEnumerator.MoveNextAsync())
            {
                using var result = resultEnumerator.Current;
                PortCoreConfiguration projectConfiguration = new PortCoreConfiguration()
                {
                    SolutionPath    = solutionPath,
                    ProjectPath     = result.ProjectResult.ProjectFilePath,
                    IsMockRun       = false,
                    UseDefaultRules = true,
                    PortCode        = true,
                    PortProject     = true,
                    TargetVersions  = new List <string> {
                        version
                    }
                };

                solutionPort.RunProject(result, projectConfiguration);
            }
            var portSolutionResult = solutionPort.GenerateResults();
            var testSolutionResult = GenerateSolutionResult(solutionPath, solutionPort.GetAnalysisResult(), portSolutionResult);

            ValidateWebApiWithReferences(testSolutionResult);
        }
Ejemplo n.º 14
0
 public ProjectBuildHandler(ILogger logger, Project project, Compilation compilation, Compilation preportCompilation, AnalyzerConfiguration analyzerConfiguration = null)
 {
     Logger = logger;
     _analyzerConfiguration  = analyzerConfiguration;
     this.Project            = project;
     _projectPath            = project.FilePath;
     this.Compilation        = compilation;
     this.PrePortCompilation = preportCompilation;
     Errors = new List <string>();
     MissingMetaReferences = new List <string>();
 }
Ejemplo n.º 15
0
 public WorkspaceBuilderHelper(ILogger logger, string workspacePath, AnalyzerConfiguration analyzerConfiguration = null)
 {
     this.Logger             = logger;
     this.WorkspacePath      = workspacePath;
     this.Projects           = new List <ProjectAnalysisResult>();
     this.FailedProjects     = new List <ProjectAnalysisResult>();
     this.DictAnalysisResult = new Dictionary <Guid, IAnalyzerResult>();
     _analyzerConfiguration  = analyzerConfiguration;
     _workspaceIncremental   = new AdhocWorkspace();
     _sb              = new StringBuilder();
     _writer          = new StringWriter(_sb);
     _analyzerManager = GetAnalyzerManager();
     _msBuildDetector = new MSBuildDetector();
 }
Ejemplo n.º 16
0
 public CodeContext(SemanticModel semanticModel,
                    SyntaxTree syntaxTree,
                    string workspacePath,
                    string sourceFilePath,
                    AnalyzerConfiguration analyzerConfiguration,
                    ILogger logger)
 {
     SemanticModel         = semanticModel;
     SyntaxTree            = syntaxTree;
     WorkspacePath         = workspacePath;
     AnalyzerConfiguration = analyzerConfiguration;
     SourceFilePath        = sourceFilePath;
     Logger = logger;
 }
Ejemplo n.º 17
0
        public async Task TestAnalysis()
        {
            string projectPath = string.Concat(GetTstPath(Path.Combine(new string[] { "Projects", "CodelyzerDummy", "CodelyzerDummy" })), ".csproj");

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = true,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions = true,
                    MethodInvocations  = true,
                    Annotations        = true,
                    LambdaMethods      = true,
                    DeclarationNodes   = true,
                    LocationData       = true,
                    ReferenceData      = true,
                    LoadBuildData      = true
                }
            };
            CodeAnalyzer   analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            AnalyzerResult result   = await analyzer.AnalyzeProject(projectPath);

            Assert.False(result.ProjectBuildResult.IsSyntaxAnalysis);

            Assert.True(result != null);

            // Extract the subject node
            var testClassRootNode = result.ProjectResult.SourceFileResults
                                    .First(s => s.FileFullPath.EndsWith("Class2.cs"))
                                    as UstNode;

            // Nested class is found
            Assert.AreEqual(1, testClassRootNode.AllClasses().Count(c => c.Identifier == "NestedClass"));

            // Chained method is found
            Assert.AreEqual(1, testClassRootNode.AllInvocationExpressions().Count(c => c.MethodName == "ChainedMethod"));

            // Constructor is found
            Assert.AreEqual(1, testClassRootNode.AllConstructors().Count);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Initializes a new instance of Solution Port, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionPort(string solutionFilePath, List <PortCoreConfiguration> solutionConfiguration, ILogger logger = null)
        {
            if (logger != null)
            {
                LogHelper.Logger = logger;
            }
            _portSolutionResult = new PortSolutionResult(solutionFilePath);
            SkipDownloadFiles   = new ConcurrentDictionary <string, bool>();
            _solutionPath       = solutionFilePath;
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                MetaDataSettings = new MetaDataSettings()
                {
                    Annotations           = true,
                    DeclarationNodes      = true,
                    MethodInvocations     = true,
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    InterfaceDeclarations = true,
                    MemberAccess          = true,
                    ElementAccess         = true
                }
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);

            List <AnalyzerResult> analyzerResults = null;

            //We are building using references
            if (solutionConfiguration.Any(p => p.MetaReferences?.Any() == true))
            {
                var currentReferences   = solutionConfiguration.ToDictionary(s => s.ProjectPath, s => s.MetaReferences);
                var frameworkReferences = solutionConfiguration.ToDictionary(s => s.ProjectPath, s => s.FrameworkMetaReferences);
                analyzerResults = analyzer.AnalyzeSolution(solutionFilePath, frameworkReferences, currentReferences).Result;
            }
            else
            {
                analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;
            }

            _context = new MetricsContext(solutionFilePath, analyzerResults);
            InitSolutionRewriter(analyzerResults, solutionConfiguration);
        }
Ejemplo n.º 19
0
        public ProjectBuildHandler(ILogger logger, Project project, AnalyzerConfiguration analyzerConfiguration = null)
        {
            Logger = logger;
            _analyzerConfiguration = analyzerConfiguration;

            CompilationOptions options = project.CompilationOptions;

            if (project.CompilationOptions is CSharpCompilationOptions)
            {
                /*
                 * This is to fix the compilation errors related to :
                 * Compile errors for assemblies which reference to mscorlib 2.0.5.0 (LINQPad 5.00.08)
                 * https://forum.linqpad.net/discussion/856/compile-errors-for-assemblies-which-reference-to-mscorlib-2-0-5-0-linqpad-5-00-08
                 */
                options = options.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
            }

            this.Project = project.WithCompilationOptions(options);
            Errors       = new List <string>();
        }
Ejemplo n.º 20
0
        public async Task TestNopCommerce()
        {
            string solutionPath = Directory.EnumerateFiles(tempDir, "nopCommerce.sln", SearchOption.AllDirectories).FirstOrDefault();

            FileAssert.Exists(solutionPath);

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = false,
                    OutputPath         = @"/tmp/UnitTests"
                },

                MetaDataSettings =
                {
                    LiteralExpressions    = true,
                    MethodInvocations     = true,
                    Annotations           = true,
                    DeclarationNodes      = true,
                    LocationData          = false,
                    ReferenceData         = true,
                    EnumDeclarations      = true,
                    StructDeclarations    = true,
                    InterfaceDeclarations = true
                }
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            var          results  = (await analyzer.AnalyzeSolution(solutionPath)).ToList();

            var enumDeclarations      = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllEnumDeclarations().Count > 0).Sum(s => s.AllEnumDeclarations().Count));
            var structDeclarations    = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllStructDeclarations().Count > 0).Sum(s => s.AllStructDeclarations().Count));
            var arrowClauseStatements = results.Sum(r => r.ProjectResult.SourceFileResults.Where(s => s.AllArrowExpressionClauses().Count > 0).Sum(s => s.AllArrowExpressionClauses().Count));

            Assert.AreEqual(80, enumDeclarations);
            Assert.AreEqual(1, structDeclarations);
            Assert.AreEqual(2, arrowClauseStatements);

            results.ForEach(r => r.Dispose());
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of SolutionRewriter, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="analyzerConfiguration">Configuration for code analyzer to be used (AnalyzerConfiguration)</param>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionRewriter(string solutionFilePath, List <ProjectConfiguration> solutionConfiguration)
        {
            _solutionResult = new SolutionResult();
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp);

            analyzerConfiguration.MetaDataSettings = new MetaDataSettings()
            {
                Annotations           = true,
                DeclarationNodes      = true,
                MethodInvocations     = true,
                ReferenceData         = true,
                LoadBuildData         = true,
                InterfaceDeclarations = true
            };

            _rulesRewriters = new List <ProjectRewriter>();
            CodeAnalyzer analyzer        = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);
            var          analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;

            InitializeProjects(analyzerResults, solutionConfiguration);
        }
Ejemplo n.º 22
0
        private async Task RunAgainWithChangedFile(string solutionPath, string projectPath, AnalyzerConfiguration configuration, CodeAnalyzer analyzer)
        {
            string projectFileContent = File.ReadAllText(projectPath);

            //Change the target to an invalid target to replicate an invalid msbuild installation
            File.WriteAllText(projectPath, projectFileContent.Replace(@"$(MSBuildBinPath)\Microsoft.CSharp.targets", @"InvalidTarget"));

            //Try without setting the flag, result should be null:
            AnalyzerResult result = (await analyzer.AnalyzeSolution(solutionPath)).FirstOrDefault();

            Assert.Null(result);

            //Try with setting the flag, syntax tree should be returned
            configuration.AnalyzeFailedProjects = true;
            result = (await analyzer.AnalyzeSolution(solutionPath)).FirstOrDefault();
            Assert.NotNull(result);
            Assert.True(result.ProjectBuildResult.IsSyntaxAnalysis);
        }
Ejemplo n.º 23
0
        public async Task TestSampleWebApi()
        {
            string solutionPath = Directory.EnumerateFiles(tempDir, "SampleWebApi.sln", SearchOption.AllDirectories).FirstOrDefault();

            FileAssert.Exists(solutionPath);

            string solutionDir = Directory.GetParent(solutionPath).FullName;

            AnalyzerConfiguration configuration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                ExportSettings =
                {
                    GenerateJsonOutput = true,
                    OutputPath         = Path.Combine("/", "tmp", "UnitTests")
                },

                MetaDataSettings =
                {
                    LiteralExpressions    = true,
                    MethodInvocations     = true,
                    Annotations           = true,
                    DeclarationNodes      = true,
                    LocationData          = false,
                    ReferenceData         = true,
                    InterfaceDeclarations = true,
                    GenerateBinFiles      = true,
                    LoadBuildData         = true,
                    ReturnStatements      = true,
                    InvocationArguments   = true
                }
            };
            CodeAnalyzer   analyzer = CodeAnalyzerFactory.GetAnalyzer(configuration, NullLogger.Instance);
            AnalyzerResult result   = (await analyzer.AnalyzeSolution(solutionPath)).FirstOrDefault();

            Assert.True(result != null);
            Assert.False(result.ProjectBuildResult.IsSyntaxAnalysis);

            //Project has 16 nuget references and 19 framework/dll references:
            Assert.AreEqual(16, result.ProjectResult.ExternalReferences.NugetReferences.Count);
            Assert.AreEqual(19, result.ProjectResult.ExternalReferences.SdkReferences.Count);

            Assert.AreEqual(10, result.ProjectResult.SourceFiles.Count);

            var houseController = result.ProjectResult.SourceFileResults.Where(f => f.FilePath.EndsWith("HouseController.cs")).FirstOrDefault();

            Assert.NotNull(houseController);

            var ihouseRepository = result.ProjectResult.SourceFileResults.Where(f => f.FilePath.EndsWith("IHouseRepository.cs")).FirstOrDefault();

            Assert.NotNull(ihouseRepository);

            var blockStatements           = houseController.AllBlockStatements();
            var classDeclarations         = houseController.AllClasses();
            var expressionStatements      = houseController.AllExpressions();
            var invocationExpressions     = houseController.AllInvocationExpressions();
            var literalExpressions        = houseController.AllLiterals();
            var methodDeclarations        = houseController.AllMethods();
            var returnStatements          = houseController.AllReturnStatements();
            var annotations               = houseController.AllAnnotations();
            var namespaceDeclarations     = houseController.AllNamespaces();
            var objectCreationExpressions = houseController.AllObjectCreationExpressions();
            var usingDirectives           = houseController.AllUsingDirectives();
            var interfaces = ihouseRepository.AllInterfaces();
            var arguments  = houseController.AllArguments();

            Assert.AreEqual(7, blockStatements.Count);
            Assert.AreEqual(1, classDeclarations.Count);
            Assert.AreEqual(89, expressionStatements.Count);
            Assert.AreEqual(75, invocationExpressions.Count);
            Assert.AreEqual(14, literalExpressions.Count);
            Assert.AreEqual(6, methodDeclarations.Count);
            Assert.AreEqual(16, returnStatements.Count);
            Assert.AreEqual(17, annotations.Count);
            Assert.AreEqual(1, namespaceDeclarations.Count);
            Assert.AreEqual(0, objectCreationExpressions.Count);
            Assert.AreEqual(10, usingDirectives.Count);
            Assert.AreEqual(1, interfaces.Count);
            Assert.AreEqual(63, arguments.Count);

            var dllFiles = Directory.EnumerateFiles(Path.Combine(result.ProjectResult.ProjectRootPath, "bin"), "*.dll");

            Assert.AreEqual(dllFiles.Count(), 16);

            await RunAgainWithChangedFile(solutionPath, result.ProjectBuildResult.ProjectPath, configuration, analyzer);
        }