如果代码覆盖率在TFS2012中低于阈值,则失败构建 [英] Fail a build if code coverage is below a threshold in TFS2012

查看:252
本文介绍了如果代码覆盖率在TFS2012中低于阈值,则失败构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当代码覆盖率低于阈值时,我尝试在TFS服务(托管TFS2012)中失败。

I'm trying to fail builds in TFS Service (Hosted TFS2012) when Code Coverage is below a threshold.

我一直在使用解决方案 http://scrumdod.blogspot.co.uk/ 2011/04 / fail-build-if-code-coverage-is-low.html

I've been messing around with the solution at http://scrumdod.blogspot.co.uk/2011/04/fail-build-if-code-coverage-is-low.html

但是,我使用TFS2012和很多东西似乎已经改变。特别是,测试运行的配置是完全不同的,似乎没有任何方法来获取或设置.coverage文件在构建过程模板或.runsettings文件中的位置和名称。

However, I'm using TFS2012 and a great many things appear to have changed. In particular, the configuration of the test run is completely different and there does not appear to be any way to get or set the location and name of the .coverage file in either the build process template or the .runsettings file.

如何在TFS2012或TFSService中查找(或设置).coverage文件的位置?

How would I go about finding (or setting) the location of the .coverage file in TFS2012 or TFSService?

如果代码覆盖率低于阈值,我还有另一种方法可以失败构建。

Alterntely, is there another way that I can fail the build if code coverage is below a threshold?

推荐答案

这将需要几个步骤:


  1. 创建自定义构建活动

  2. 将活动添加到构建控制器

  3. 在新构建过程中调用自定义构建活动

  4. 使用新构建过程

  1. Create a custom build activity
  2. Add the activity to the build controller
  3. Invoke that custom build activity within a new build process
  4. Use the new build process



1。创建自定义构建活动。



在VS2012中创建一个新项目(我称之为CodeCoverageLibrary,参考以下程序集:

1. Create a custom build activity.

Make a new project in VS2012 (I called mine CodeCoverageLibrary. Reference the following assemblies:


  • Microsoft.TeamFoundation.Build.Client

  • Microsoft.TeamFoundation.Client

  • Microsoft.TeamFoundation.TestManagement。客户

  • Microsoft.TeamFoundation.WorkItemTracking.Client

  • 系统

  • System.Activities

  • System.Core

  • System.Xaml

  • Microsoft.TeamFoundation.Build.Client
  • Microsoft.TeamFoundation.Client
  • Microsoft.TeamFoundation.TestManagement.Client
  • Microsoft.TeamFoundation.WorkItemTracking.Client
  • System
  • System.Activities
  • System.Core
  • System.Xaml

以下代码:

using System;
using System.Activities;
using System.Collections.Generic;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;

namespace CodeCoverageLibrary
{
    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class GetCodeCoverage : CodeActivity<double>
    {
        public InArgument<IBuildDetail> BuildDetail { get; set; }

        protected override double Execute(CodeActivityContext context)
        {
            var buildDetail = BuildDetail.Get(context);
            var buildCoverages = GetBuildCoverages(buildDetail.BuildServer.TeamProjectCollection.Uri,
                                                   buildDetail.TeamProject, buildDetail.Uri);
            return GetTotalCoverage(buildCoverages);
        }

        private static IEnumerable<IBuildCoverage> GetBuildCoverages(Uri uri, string projectName, Uri buildUri)
        {
            return TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri)
                                                  .GetService<ITestManagementService>()
                                                  .GetTeamProject(projectName)
                                                  .CoverageAnalysisManager.QueryBuildCoverage(buildUri.ToString(),
                                                                                              CoverageQueryFlags.Modules);
        }

        private static double GetTotalCoverage(IEnumerable<IBuildCoverage> buildCoverages)
        {
            int totalCoveredBlocks = 0, totalUncoveredBlocks = 0;
            foreach (var buildCoverage in buildCoverages)
            {
                foreach (var module in buildCoverage.Modules)
                {
                    totalCoveredBlocks += module.Statistics.BlocksCovered;
                    totalUncoveredBlocks += module.Statistics.BlocksNotCovered;
                }
            }

            return (totalCoveredBlocks == 0 && totalUncoveredBlocks == 0)
                                      ? 0.0
                                      : ((double) totalCoveredBlocks) /
                                        ((double) (totalCoveredBlocks + totalUncoveredBlocks));
        }
    }
}

编译项目并添加到到TFS上的版本控制路径。

Compile the project and add to to a version controlled path on TFS.

在团队资源管理器中,转到构建> 操作<构建控制器... 。然后单击构建控制器的属性... 。在自定义程序集的版本控制路径下,输入您在上面使用的路径。

In Team Explorer, go to Builds > Actions > Manage Build Controllers .... Then click on Properties... for the build controller. Under Version control path to custom assemblies, put the path you used above.

BuildProcessTemplates\DefaultTemplate.11.1.xaml 复制到新文件。

更新新的XAML文件的开头,包括以下内容:

Update the beginning of the new XAML file to include the following:

<Activity ...
          xmlns:ccl="clr-namespace:CodeCoverageLibrary;assembly=CodeCoverageLibrary"
          ...
          >
  <x:Members>
    ...
    <x:Property Name="CodeCoverageTolerance" Type="InArgument(x:Double)" />
  </x:Members>
  ...
  <this:Process.Metadata>
    <mtbw:ProcessParameterMetadataCollection>
      ...
      <mtbw:ProcessParameterMetadata BrowsableWhen="EditingDefinition" Category="#900 Misc" DisplayName="CodeCoverageTolerance" Description="If the overall code coverage drops below this threshold, then the build will fail. This is a number between 0 and 1." ParameterName="CodeCoverageTolerance" />
    </mtbw:ProcessParameterMetadataCollection>
  </this:Process.Metadata>

更新XAML文件的结尾以包括以下内容:

Update the end of the XAML file to include the following:

      <Sequence DisplayName="Code Coverage Check" mtbwt:BuildTrackingParticipant.Importance="None">
        <Sequence.Variables>
          <Variable x:TypeArguments="x:Double" Name="CodeCovered" />
        </Sequence.Variables>
        <ccl:GetCodeCoverage DisplayName="Getting Code Coverage" BuildDetail="[BuildDetail]" Result="[CodeCovered]" />
        <If Condition="[CodeCovered &lt; CodeCoverageTolerance]">
          <If.Then>
            <Sequence DisplayName="Comparing Code Coverage Against Tolerance">
              <mtbwa:SetBuildProperties DisplayName="Set TestStatus to Failed" mtbwt:BuildTrackingParticipant.Importance="Low" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Failed]" />
              <mtbwa:WriteBuildError Message="[&quot;Code Coverage of &quot; + CodeCovered.ToString(&quot;P&quot;) + &quot; is less than required &quot; + CodeCoverageTolerance.ToString(&quot;P&quot;)]" />
            </Sequence>
          </If.Then>
        </If>
      </Sequence>
    </mtbwa:AgentScope>
    <mtbwa:InvokeForReason DisplayName="Check In Gated Changes for CheckInShelveset Builds" Reason="CheckInShelveset">
      <mtbwa:CheckInGatedChanges DisplayName="Check In Gated Changes" />
    </mtbwa:InvokeForReason>
  </Sequence>
</Activity>

在TFS中检查此项。

在团队资源管理器中,转到构建,然后右键单击构建定义。转到修改构建定义... > 处理。展开构建流程模板,然后点击新建... 。点击选择现有XAML文件,然后将路径放到新的XAML文件。点击确定。您现在应该在 4下看到 CodeCoverageTolerance 。 Misc 。您可以输入介于0和1之间的数字,以表示您所需的百分比。

In Team Explorer, go to Builds and right-click on your build definition. Go to Edit Build Definition... > Process. Expand Build process template and click New.... Click Select an existing XAML file and put the path to the new XAML file. Click OK. You should now see CodeCoverageTolerance under 4. Misc. You can put in a number between 0 and 1 to indicate your desired percentage.

这篇关于如果代码覆盖率在TFS2012中低于阈值,则失败构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆