public void WhenRunningTaskShouldComputeMetrics()
        {
            ITaskItem[] providers = new TaskItemMock[1];
            providers[0] = new TaskItemMock("MSBuildCodeMetrics.Core.UnitTests.Mock.CodeMetricsProviderSingleFileMock, MSBuildCodeMetrics.Core.UnitTests").
                AddMetadata("Data", "<Metric Name=\"LinesOfCode\"><Measure " +
                    "Name=\"Method1\" Value=\"1\" /><Measure Name=\"Method2\" Value=\"2\" /><Measure " +
                    "Name=\"Method3\" Value=\"5\" /></Metric>").
                AddMetadata("ProviderName", "CodeMetricsProviderMock");

            ITaskItem[] metrics = new TaskItemMock[1];
            metrics[0] = new TaskItemMock("LinesOfCode").
                AddMetadata("ProviderName", "CodeMetricsProviderMock").
                AddMetadata("Ranges", "2;3").
                AddMetadata("Files", "C:\\foo.txt");

            FileStreamFactoryMock streamFactory = new FileStreamFactoryMock();

            CodeMetrics task = new CodeMetrics(streamFactory);
            task.BuildEngine = new BuildEngineMock();
            task.Providers = providers;
            task.OutputFileName = "report.xml";
            task.ShowDetailsReport = true;
            task.ShowSummaryReport = true;
            task.Metrics = metrics;
            task.FileOutput = true;
            Assert.AreEqual(true, task.Execute());

            streamFactory.OutputStream.Seek(0, SeekOrigin.Begin);
            MSBuildCodeMetricsReport report = MSBuildCodeMetricsReport.Deserialize(streamFactory.OutputStream);
            Assert.AreEqual(1, report.Details.Metrics.Count);
            Assert.AreEqual("LinesOfCode", report.Details.Metrics[0].MetricName);
            Assert.AreEqual("Method3", report.Details.Metrics[0].Measures[0].MeasureName);
            Assert.AreEqual(5, report.Details.Metrics[0].Measures[0].Value);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MethodMetricsThresholds"/> class
 /// Thresholds for methods in a class
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 internal MethodMetricsThresholds(CodeMetrics activity)
 {
     this.maintainabilityindexThresholds = new MetricThresholds(activity.MaintainabilityIndexWarningThreshold.Get(activity.Context), activity.MaintainabilityIndexErrorThreshold.Get(activity.Context));
     this.cyclomaticComplexityThresholds = new MetricThresholds(activity.CyclomaticComplexityWarningThreshold.Get(activity.Context), activity.CyclomaticComplexityErrorThreshold.Get(activity.Context));
     this.couplingThresholds             = new MetricThresholds(activity.CouplingWarningThreshold.Get(activity.Context), activity.CouplingErrorThreshold.Get(activity.Context));
     this.linesOfCodeThresholds          = new MetricThresholds(activity.LinesOfCodeWarningThreshold.Get(activity.Context), activity.LinesOfCodeErrorThreshold.Get(activity.Context));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TypeMetricsThresholds"/> class
 /// Thresholds for Types (Classes)
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 /// <param name="methodMetricsThresholds">The class thresholds depends on the method thresholds, so we need this first</param>
 internal TypeMetricsThresholds(CodeMetrics activity, MethodMetricsThresholds methodMetricsThresholds)
 {
     this.methodMetricsThresholds      = methodMetricsThresholds;
     this.depthOfInheritanceThresholds = new MetricThresholds(activity.DepthOfInheritanceWarningThreshold.Get(activity.Context), activity.DepthOfInheritanceErrorThreshold.Get(activity.Context));
     this.couplingThresholds           = new MetricThresholds(methodMetricsThresholds.CouplingThresholds);
     this.couplingThresholds          *= CouplingFactor;
     this.linesOfCodeThresholds        = new MetricThresholds(methodMetricsThresholds.LinesOfCodeThresholds);
     this.linesOfCodeThresholds       *= LinesOfCodeFactor;
 }
Exemplo n.º 4
0
        public async Task SendCode(string group, string user, string code)
        {
            // get the group
            if (ConnectionDetails.TryGetGroup(group, out GroupDetails groupdetails))
            {
                // get the user
                if (groupdetails.TryGetUser(Context.ConnectionId, out UserDetails userdetails))
                {
                    // run code analysis
                    CodeMetrics metrics = default(CodeMetrics);
                    userdetails.Rating = Single.MaxValue;

                    try
                    {
                        metrics = ClrCodingGolf.Analysis.CodeAnalysis.Analyze(code, injectIntrigue: true);
                        System.Diagnostics.Debug.WriteLine($"{metrics.Bytes} {metrics.Lines} {metrics.CCM} {metrics.Characters}");
                        userdetails.Rating = (metrics.Bytes * 0.35f) + (metrics.Lines * 0.05f) + (metrics.CCM * 0.5f) + (metrics.Characters * 0.1f);
                        if (userdetails.Rating < 0)
                        {
                            userdetails.Rating = 0;
                        }

                        // retain the code and rating
                        userdetails.Attempts++;
                        userdetails.Code = Sanitize(code);
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e);
                    }

                    // share result back
                    await Clients.Caller.SendAsync("ReceiveMyResult", metrics.Bytes, metrics.Lines, metrics.CCM, metrics.Characters, userdetails.Rating);

                    // share with all clients
                    await Clients.All.SendAsync("ReceiveCode", Context.ConnectionId, user, userdetails.Code, userdetails.Rating);
                }
                else
                {
                    await Clients.Caller.SendAsync("ReceiveMessage", "unable to find user (please reload)");
                }
            }
            else
            {
                await Clients.Caller.SendAsync("ReceiveMessage", "unable to find group (please reload)");
            }
        }
        public void Initialize()
        {
            _buildEngine = new BuildEngineMock();
            _task = new CodeMetrics();
            _task.BuildEngine = _buildEngine;

            _metrics = new TaskItemMock[1];
            _metrics[0] = new TaskItemMock("LinesOfCode").
                AddMetadata("ProviderName", "CodeMetricsProviderMock").
                AddMetadata("Ranges", "2;3").
                AddMetadata("Files", "foo");

            _providers = new TaskItemMock[1];
            _providers[0] = new TaskItemMock(
                "MSBuildCodeMetrics.Core.UnitTests.Mock.CodeMetricsProviderSingleFileMock, MSBuildCodeMetrics.Core.UnitTests").
                AddMetadata("ProviderName", "CodeMetricsProviderMock").
                AddMetadata("Metrics", "LinesOfCode");
        }
Exemplo n.º 6
0
        public List <TrendData> AnalyzeTrend(string localFile)
        {
            var trend = new List <TrendData>();

            var svnProvider = Project.CreateProvider();

            // Svn log on this file to get all revisions
            var fileHistory = svnProvider.ExportFileHistory(localFile);

            // For each file we need to calculate the metrics
            var provider = new CodeMetrics();

            foreach (var file in fileHistory)
            {
                var fileInfo      = new FileInfo(file.CachePath);
                var loc           = provider.CalculateLinesOfCode(fileInfo);
                var invertedSpace = provider.CalculateInvertedSpaceMetric(fileInfo);
                trend.Add(new TrendData {
                    Date = file.Date, Loc = loc, InvertedSpace = invertedSpace
                });
            }

            return(trend);
        }
 public ActivityContextProxy(CodeMetrics activity, CodeActivityContext context)
 {
     this.activity = activity;
     this.context = context;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="NameSpaceMetricsThresholds"/> class
 /// Name space thresholds.  Currently blank, as we dont see usable values for this.  Placeholder for user extension code only
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 public NameSpaceMetricsThresholds(CodeMetrics activity)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssemblyMetricsThresholds"/> class
 /// Assembly thresholds.  Currently blank, as we dont see usable values for this.  Placeholder for user extension code only
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 public AssemblyMetricsThresholds(CodeMetrics activity)
 {
 }
 public ActivityContextProxy(CodeMetrics activity, CodeActivityContext context)
 {
     this.activity = activity;
     this.context  = context;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MethodMetricsThresholds"/> class
 /// Thresholds for methods in a class
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 internal MethodMetricsThresholds(CodeMetrics activity)
 {
     this.maintainabilityindexThresholds = new MetricThresholds(activity.MaintainabilityIndexWarningThreshold.Get(activity.Context), activity.MaintainabilityIndexErrorThreshold.Get(activity.Context));
     this.cyclomaticComplexityThresholds = new MetricThresholds(activity.CyclomaticComplexityWarningThreshold.Get(activity.Context), activity.CyclomaticComplexityErrorThreshold.Get(activity.Context));
     this.couplingThresholds = new MetricThresholds(activity.CouplingWarningThreshold.Get(activity.Context), activity.CouplingErrorThreshold.Get(activity.Context));
     this.linesOfCodeThresholds = new MetricThresholds(activity.LinesOfCodeWarningThreshold.Get(activity.Context), activity.LinesOfCodeErrorThreshold.Get(activity.Context));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TypeMetricsThresholds"/> class
 /// Thresholds for Types (Classes)
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 /// <param name="methodMetricsThresholds">The class thresholds depends on the method thresholds, so we need this first</param>
 internal TypeMetricsThresholds(CodeMetrics activity, MethodMetricsThresholds methodMetricsThresholds)
 {
     this.methodMetricsThresholds = methodMetricsThresholds;
     this.depthOfInheritanceThresholds = new MetricThresholds(activity.DepthOfInheritanceWarningThreshold.Get(activity.Context), activity.DepthOfInheritanceErrorThreshold.Get(activity.Context));
     this.couplingThresholds = new MetricThresholds(methodMetricsThresholds.CouplingThresholds);
     this.couplingThresholds *= CouplingFactor;
     this.linesOfCodeThresholds = new MetricThresholds(methodMetricsThresholds.LinesOfCodeThresholds);
     this.linesOfCodeThresholds *= LinesOfCodeFactor;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="NameSpaceMetricsThresholds"/> class
 /// Name space thresholds.  Currently blank, as we dont see usable values for this.  Placeholder for user extension code only
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 public NameSpaceMetricsThresholds(CodeMetrics activity)
 {
 }
 public void WhenRunningWithMetricsWithEmptyRangesShouldReturnFalseAndSetErrorMessage()
 {
     var buildEngineMock = new Mock<IBuildEngine>();
     var errorMessage = String.Empty;
     buildEngineMock.Setup(be => be.LogErrorEvent(It.IsAny<BuildErrorEventArgs>())).
         Callback<BuildErrorEventArgs>(
             e =>
             {
                 errorMessage = e.Message;
             });
     var task = new CodeMetrics()
     {
         BuildEngine = buildEngineMock.Object,
         Metrics = new ITaskItem[]
         {
             new TaskItemMock("Metric").
                 AddMetadata("ProviderName", "CodeMetricsProviderMock").
                 AddMetadata("Ranges", null).
                 AddMetadata("Files", "foo")
         }
     };
     Assert.IsFalse(task.Execute());
     Assert.IsTrue(errorMessage.StartsWith("Ranges can't be null if you need a summary report."));
 }
 internal CodeMetricsFilesToProcess(CodeMetrics activity, CodeActivityContext context) : this(new ActivityContextProxy(activity, context), new FileSystemProxy())
 {
 }
 internal CodeMetricsFilesToProcess(CodeMetrics activity, CodeActivityContext context) : this(new ActivityContextProxy(activity, context), new FileSystemProxy())
 {
 }
 public void WhenRunningWithoutMetricsShouldReturnFalseAndSetErrorMessage()
 {
     var buildEngineMock = new Mock<IBuildEngine>();
     var task = new CodeMetrics()
     {
         BuildEngine = buildEngineMock.Object
     };
     task.Execute();
 }
 public void WhenSettingRangeWithInvalidValueShouldReturnFalseAndSetError()
 {
     var buildEngineMock = new Mock<IBuildEngine>();
     var task = new CodeMetrics()
     {
         BuildEngine = buildEngineMock.Object,
         Metrics = new ITaskItem[]
         {
             _metrics[0] = new TaskItemMock("LinesOfCode").
                 AddMetadata("ProviderName", "CodeMetricsProviderMock").
                 AddMetadata("Ranges", "abc;abc").
                 AddMetadata("Files", "foo")
         }
     };
     task.Execute();
 }
        public void WhenRunningWithProcessExecutorCodeMetricsShouldSetProcessExecutor()
        {
            var buildEngineMock = new Mock<IBuildEngine>();

            var task = new CodeMetrics()
            {
                BuildEngine = buildEngineMock.Object,
                Providers = new ITaskItem[]
                {
                    new TaskItemMock("MSBuildCodeMetrics.Core.UnitTests.Mock.CodeMetricsProviderProcessExecutorMock, MSBuildCodeMetrics.Core.UnitTests").
                    AddMetadata("ProviderName", "CodeMetricsProviderProcessExecutorMock")
                },
                Metrics = new ITaskItem[]
                {
                    new TaskItemMock("Metric").
                        AddMetadata("ProviderName", "DummyProvider").
                        AddMetadata("Ranges", "1").
                        AddMetadata("Files", "foo")
                }
            };
            Assert.IsNull(CodeMetricsProviderProcessExecutorMock.LastProcessExecutorSet);
            task.Execute();
            Assert.IsNotNull(CodeMetricsProviderProcessExecutorMock.LastProcessExecutorSet);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssemblyMetricsThresholds"/> class
 /// Assembly thresholds.  Currently blank, as we dont see usable values for this.  Placeholder for user extension code only
 /// </summary>
 /// <param name="activity">Code metrics activity, from where we pick off the incoming values for thresholds</param>
 public AssemblyMetricsThresholds(CodeMetrics activity)
 {
 }
        public void WhenRunningWithLowerRangeFailMessageAndHasValueOnLowerBandShouldFail()
        {
            var buildEngineMock = new Mock<IBuildEngine>();
            var errorMessage = String.Empty;
            buildEngineMock.Setup(be => be.LogErrorEvent(It.IsAny<BuildErrorEventArgs>())).
                Callback<BuildErrorEventArgs>(
                    e =>
                    {
                        errorMessage = e.Message;
                    });

            var task = new CodeMetrics()
            {
                BuildEngine = buildEngineMock.Object,
                Providers = new ITaskItem[]
                {
                    new TaskItemMock("MSBuildCodeMetrics.Core.UnitTests.Mock.CodeMetricsProviderSingleFileMock, MSBuildCodeMetrics.Core.UnitTests").
                        AddMetadata("Data", "<Metric Name=\"CodeCoverage\"><Measure " +
                                    "Name=\"Assembly1\" Value=\"75\" /><Measure Name=\"Assembly2\" Value=\"100\" /><Measure " +
                                    "Name=\"Assembly3\" Value=\"100\" /></Metric>").
                        AddMetadata("ProviderName", "CodeMetricsProviderMock")
                },
                Metrics = new ITaskItem[]
                {
                    new TaskItemMock("CodeCoverage").
                        AddMetadata("ProviderName", "CodeMetricsProviderMock").
                        AddMetadata("Ranges", "90").
                        AddMetadata("Files", "foo").
                        AddMetadata("LowerRangeFailMessage", "There are assemblies with less than 90% of coverage")
                }
            };

            Assert.AreEqual(false, task.Execute());
            Assert.AreEqual("There are assemblies with less than 90% of coverage", errorMessage);
        }