Azure DevOps Crash Course (Part 4): Your First YAML Build Pipeline for .NET
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
Azure DevOps Crash Course (Part 4): Your First YAML Build Pipeline for .NET
“It works on my machine.” I have said it. You have probably said it too. A build pipeline is basically a machine that is not yours, and it does not care how confident you are. Every time you push, it pulls your code onto a clean machine, builds it, runs the tests, and tells you the truth. The first time I set one up, I felt like I had hired a very honest assistant who never takes a day off.
“在我的机器上能运行。”我说过这句话,你可能也说过。构建流水线本质上是一台不属于你的机器,它根本不在乎你有多自信。每当你推送代码时,它都会将代码拉取到一台干净的机器上,进行构建、运行测试,并告诉你真实的结果。我第一次设置流水线时,感觉就像雇佣了一位从不请假的诚实助手。
In Part 3 we pushed the Todo API to Azure Repos and protected main. Today we add Azure Pipelines, so every push is built and tested automatically, and no pull request can be merged if the tests fail.
在第 3 部分中,我们将 Todo API 推送到了 Azure Repos 并保护了 main 分支。今天,我们将添加 Azure Pipelines,这样每次推送都会自动进行构建和测试,并且如果测试失败,任何拉取请求(Pull Request)都无法合并。
Before we start: check your free build minutes
Remember the heads-up from Part 1? New Azure DevOps organizations do not get free Microsoft-hosted build minutes automatically. If you have not done it yet, fill in the free parallelism request form now. It can take a few business days. You can check your status in Organization settings > Pipelines > Parallel jobs. If the Microsoft-hosted number for private projects is 0, your request is still waiting. You can still write the pipeline today, it just will not run until the grant comes through.
开始之前:检查你的免费构建时长
还记得第 1 部分的提醒吗?新的 Azure DevOps 组织不会自动获得免费的微软托管构建时长。如果你还没申请,现在就去填写免费并行处理(parallelism)申请表吧。这可能需要几个工作日。你可以在“组织设置 > 流水线 > 并行作业”中查看状态。如果私有项目的微软托管数量为 0,说明你的申请还在处理中。你今天仍然可以编写流水线,只是在申请获批之前它不会运行。
Step 1: Add a real test
A pipeline that runs zero tests is not very exciting. Let us test the title rule we wrote in Part 3. Delete the sample UnitTest1.cs in tests/TodoApi.Tests and create TodoItemTests.cs:
第 1 步:添加真实的测试
一个不运行任何测试的流水线没什么意思。让我们测试一下在第 3 部分中编写的标题规则。删除 tests/TodoApi.Tests 中的示例文件 UnitTest1.cs,并创建 TodoItemTests.cs:
using TodoApi.Api;
public class TodoItemTests {
[Theory]
[InlineData("Buy milk", true)]
[InlineData("", false)]
[InlineData(" ", false)]
[InlineData(null, false)]
public void IsValidTitle_checks_required_title(string? title, bool expected) {
Assert.Equal(expected, TodoItem.IsValidTitle(title));
}
[Fact]
public void IsValidTitle_rejects_titles_over_100_characters() {
var longTitle = new string('a', 101);
Assert.False(TodoItem.IsValidTitle(longTitle));
}
}
These are the acceptance criteria from Part 2, now written as tests. Run dotnet test locally and make sure everything is green.
这些是第 2 部分中的验收标准,现在已编写为测试用例。在本地运行 dotnet test,确保一切测试通过(显示为绿色)。
Step 2: Write the pipeline
Create a file called azure-pipelines.yml in the root of the repo:
第 2 步:编写流水线
在仓库根目录下创建一个名为 azure-pipelines.yml 的文件:
trigger:
branches:
include:
- main
- feature/*
pool:
vmImage: ubuntu-latest
variables:
buildConfiguration: Release
steps:
- task: UseDotNet@2
displayName: Install .NET 10 SDK
inputs:
packageType: sdk
version: 10.x
- script: dotnet restore
displayName: Restore
- script: dotnet build --configuration $(buildConfiguration) --no-restore
displayName: Build
- task: DotNetCoreCLI@2
displayName: Test
inputs:
command: test
projects: '**/*Tests.csproj'
arguments: '--configuration $(buildConfiguration) --no-build --collect "XPlat Code Coverage"'
- task: PublishCodeCoverageResults@2
displayName: Publish code coverage
inputs:
summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml'
Let me walk through it like a person, not like a spec:
- trigger: run the pipeline when someone pushes to main or any feature/ branch.
- pool: use a fresh Ubuntu machine that Microsoft hosts for us.
- UseDotNet@2: install the .NET 10 SDK, so we are not depending on whatever happens to be on the machine.
- restore, build: the same commands you run on your laptop.
- DotNetCoreCLI@2 test: runs the tests and automatically publishes the results, so you get a nice Tests tab in the pipeline run.
- XPlat Code Coverage: collects code coverage. The xUnit template already includes the coverlet.collector package that makes this work.
- PublishCodeCoverageResults@2: shows the coverage report in a Code Coverage tab.
让我像个人一样为你解读,而不是照本宣科:
- trigger:当有人推送到 main 或任何 feature/ 分支时运行流水线。
- pool:使用微软为我们托管的全新 Ubuntu 机器。
- UseDotNet@2:安装 .NET 10 SDK,这样我们就不必依赖机器上预装的任何环境。
- restore, build:与你在笔记本电脑上运行的命令相同。
- DotNetCoreCLI@2 test:运行测试并自动发布结果,这样你就能在流水线运行界面看到一个漂亮的“测试”选项卡。
- XPlat Code Coverage:收集代码覆盖率。xUnit 模板已经包含了实现此功能的 coverlet.collector 包。
- PublishCodeCoverageResults@2:在“代码覆盖率”选项卡中显示覆盖率报告。
One small habit that has saved me a lot of failed runs: YAML is very picky about spaces, and one wrong indent breaks the whole pipeline. Before I push, I read the file once more and check that every step lines up under steps. It takes five seconds and catches the silly mistakes before Azure DevOps does.
有一个小习惯帮我避免了许多运行失败:YAML 对空格非常挑剔,缩进错误会导致整个流水线崩溃。在推送之前,我会再读一遍文件,检查每个步骤是否都在 steps 下对齐。这只需要五秒钟,却能在 Azure DevOps 发现之前就拦截掉这些愚蠢的错误。
Because main is protected, commit this on a branch and open a pull request, just like we practiced in Part 3:
由于 main 分支受到保护,请在分支上提交此更改并打开拉取请求,就像我们在第 3 部分中练习的那样:
git checkout -b feature/add-pipeline
git add .
git commit -m "Add tests and build pipeline"
git push -u origin feature/add-pipeline
Step 3: Create the pipeline in Azure DevOps
Go to Pipelines > Pipelines and click New pipeline (or Create pipeline). Choose Azure Repos Git. Pick the TodoApi repository. Choose Existing Azure Pipelines YAML file, select your feature/add-pipeline branch and the /azure-pipelines.yml file. Click Run.
第 3 步:在 Azure DevOps 中创建流水线
前往 Pipelines > Pipelines,点击 New pipeline(或 Create pipeline)。选择 Azure Repos Git。选择 TodoApi 仓库。选择 Existing Azure Pipelines YAML file,选中你的 feature/add-pipeline 分支和 /azure-pipelines.yml 文件。点击 Run。
Now watch the logs scroll by. The first run takes a bit longer. When it finishes you should see a green tick, a Tests tab with 5 passing tests, and a Code Coverage tab. If it fails with “No hosted parallelism has been purchased or granted”, that is the free grant from earlier. Nothing is wrong with your YAML.
现在观察日志滚动。第一次运行会稍微慢一点。完成后,你应该会看到一个绿色的勾号、一个包含 5 个通过测试的“测试”选项卡,以及一个“代码覆盖率”选项卡。如果报错“No hosted parallelism has been purchased or granted”,那是因为之前提到的免费额度问题。你的 YAML 文件没有问题。
Step 4: Make the pipeline guard your pull requests
This is the part that made me fall in love with Azure DevOps. Here is something that surprises a lot of people: for Azure Repos, a pr: section in your YAML does not trigger builds for pull requests. You have to use a branch policy instead.
第 4 步:让流水线守护你的拉取请求
这是让我爱上 Azure DevOps 的部分。有一件事让很多人感到惊讶:对于 Azure Repos,YAML 中的 pr: 部分并不会触发拉取请求的构建。你必须改用分支策略(branch policy)。
So: Go to Repos > Branches, open the three dots on main and choose Branch policies. Under Build validation, click +. Pick your pipeline, keep Trigger: Automatic and Policy requirement: Required. Save.
所以:前往 Repos > Branches,点击 main 分支旁边的三个点,选择 Branch policies。在 Build validation 下,点击 +。选择你的流水线,保持 Trigger 为 Automatic,Policy requirement 为 Required。保存。
Now go back to your open pull request. You will see a new check: the build. The pull request cannot be completed until the build passes. Want to see it work? Change <= 100 to <= 10 in TodoItem.cs, push, and watch the build go red. Then change it back. Breaking things on purpose is a great way to trust your safety net. Once it is green, complete the pull request.
现在回到你打开的拉取请求。你会看到一个新的检查项:构建。在构建通过之前,拉取请求无法完成。想看看效果吗?将 TodoItem.cs 中的 <= 100 改为 <= 10,推送代码,然后看着构建变红。然后再改回来。故意破坏代码是验证安全网是否可靠的好方法。一旦变绿,就可以完成拉取请求了。
Step 5: Add a status badge
Everyone loves a green badge. Open your pipeline, click the three dots in the top right and choose Status badge. Copy the Markdown. Add a README.md to the repo and paste it at the top. Now anyone who opens your repo can see if the build is healthy.
第 5 步:添加状态徽章
每个人都喜欢绿色的徽章。打开你的流水线,点击右上角的三个点,选择 Status badge。复制 Markdown 代码。在仓库中添加一个 README.md 文件,并将代码粘贴在顶部。现在,任何打开你仓库的人都能看到构建是否健康。