使用 ARM 模板测试工具包Use ARM template test toolkit

ARM 模板测试工具包检查模板是否使用建议的做法。The ARM template test toolkit checks whether your template uses recommended practices. 如果模板不符合建议的做法,它将返回包含建议的更改的警告列表。When your template isn't compliant with recommended practices, it returns a list of warnings with the suggested changes. 通过使用测试工具包,可以了解如何避免模板开发中的常见问题。By using the test toolkit, you can learn how to avoid common problems in template development.

测试工具包提供一组默认测试The test toolkit provides a set of default tests. 这些测试是建议,而不是要求。These tests are recommendations but not requirements. 你可以确定哪些测试与目标相关,并自定义要运行哪些测试。You can decide which tests are relevant to your goals and customize which tests are run.

本文介绍如何运行测试工具包以及如何添加或删除测试。This article describes how to run the test toolkit and how to add or remove tests. 有关默认测试的说明,请参阅工具包测试用例For descriptions of the default tests, see toolkit test cases.

工具包是一组可从 PowerShell 或 CLI 中的命令运行的 PowerShell 脚本。The toolkit is a set of PowerShell scripts that can be run from a command in PowerShell or CLI.

下载测试工具包Download test toolkit

若要使用测试工具包,可以分叉并克隆包含脚本的存储库,或下载最新的 .zip 文件To use the test toolkit, you can either fork and clone the repository containing the scripts or download the latest .zip file.

根据运行脚本的计算机的执行策略,你可能会收到有关从 Internet 运行脚本的错误消息。Depending on the execution policy of the computer where you run the script, you may get an error about running scripts from the Internet. 必须更改执行策略取消阻止脚本文件You have to either change the execution policy or unblock the script files.

在 PowerShell 上运行Run on PowerShell

在运行测试之前,导入模块。Before running the tests, import the module.

Import-Module .\arm-ttk.psd1 # from the same directory as .\arm-ttk.psd1

若要在“PowerShell”中运行测试,请使用以下命令:To run the tests in PowerShell, use the following command:

Test-AzTemplate -TemplatePath $TemplateFolder

在 Linux 上运行Run on Linux

在运行测试之前,安装 PowerShell CoreBefore running the tests, install PowerShell Core.

若要在 Bash 的“Linux”上运行测试,请使用以下命令:To run the tests on Linux in Bash, use the following command:

Test-AzTemplate.sh -TemplatePath $TemplateFolder

还可以在 pwsh.exe 上运行测试。You can also run the test on pwsh.exe.

在 macOS 上运行Run on macOS

在运行测试之前,安装 PowerShell CoreBefore running the tests, install PowerShell Core.

安装 coreutilsInstall coreutils:

brew install coreutils

若要在“macOS”上运行测试,请使用以下命令:To run the tests on macOS, use the following command:

Test-AzTemplate.sh -TemplatePath $TemplateFolder

结果格式Result format

顺利通过的测试显示为“绿色”,并以“[+]”开头 。Tests that pass are displayed in green and prefaced with [+].

失败的测试显示为“红色”,并以“[-]”开头 。Tests that fail are displayed in red and prefaced with [-].

查看测试结果

文本结果为:The text results are:

[+] adminUsername Should Not Be A Literal (24 ms)
[+] apiVersions Should Be Recent (18 ms)
[+] artifacts parameter (16 ms)
[+] DeploymentTemplate Schema Is Correct (17 ms)
[+] IDs Should Be Derived From ResourceIDs (15 ms)
[-] Location Should Not Be Hardcoded (41 ms)
     azuredeploy.json must use the location parameter, not resourceGroup().location (except when used as a default value in the main template)

测试参数Test parameters

提供“-TemplatePath”参数时,工具箱将在该文件夹中查找名为 azuredeploy.json 或 maintemplate.json 的模板。When you provide the -TemplatePath parameter, the toolkit looks in that folder for a template named azuredeploy.json or maintemplate.json. 它首先测试此模板,然后测试该文件夹及其子文件夹中的所有其他模板。It tests this template first and then tests all other templates in the folder and its subfolders. 其他模板将作为链接模板进行测试。The other templates are tested as linked templates. 如果路径包含名为 CreateUiDefinition.json 的文件,则它将运行与 UI 定义相关的测试。If your path includes a file named CreateUiDefinition.json, it runs tests that are relevant to UI definition.

Test-AzTemplate -TemplatePath $TemplateFolder

若要测试该文件夹中的某个文件,请添加“-File”参数。To test one file in that folder, add the -File parameter. 但是,该文件夹仍然必须具有名为 azuredeploy.json 或 maintemplate.json 的主模板。However, the folder must still have a main template named azuredeploy.json or maintemplate.json.

Test-AzTemplate -TemplatePath $TemplateFolder -File cdn.json

默认情况下,会运行所有测试。By default, all tests are run. 若要指定要运行的各个测试,请使用“-Test”参数。To specify individual tests to run, use the -Test parameter. 提供测试的名称。Provide the name of the test. 有关名称,请参阅工具包的测试用例For the names, see Test cases for toolkit.

Test-AzTemplate -TemplatePath $TemplateFolder -Test "Resources Should Have Location"

自定义测试Customize tests

对于 ARM 模板,工具包将运行“\arm-ttk\testcases\deploymentTemplate”文件夹中的所有测试。For ARM templates, the toolkit runs all of the tests in the folder \arm-ttk\testcases\deploymentTemplate. 如果要永久删除测试,请从文件夹中删除该文件。If you want to permanently remove a test, delete that file from the folder.

对于 CreateUiDefinition 文件,工具包将运行“\arm-ttk\testcases\CreateUiDefinition”文件夹中的所有测试。For CreateUiDefinition files, it runs all of the tests in the folder \arm-ttk\testcases\CreateUiDefinition.

若要添加自己的测试,请使用以下命名约定创建文件:Your-Custom-Test-Name.test.ps1。To add your own test, create a file with the naming convention: Your-Custom-Test-Name.test.ps1.

测试可以获取模板作为对象参数或字符串参数。The test can get the template as an object parameter or a string parameter. 通常使用其中一种参数,但也可以同时使用两种。Typically, you use one or the other, but you can use both.

需要获取模板的一部分并循环访问其属性时,请使用 object 参数。Use the object parameter when you need to get a section of the template and iterate through its properties. 使用 object 参数的测试采用以下格式:A test that uses the object parameter has the following format:

param(
    [Parameter(Mandatory=$true,Position=0)]
    [PSObject]
    $TemplateObject
)

# Implement test logic that evaluates parts of the template.
# Output error with: Write-Error -Message

模板对象具有以下属性:The template object has the following properties:

  • $schema$schema
  • contentVersioncontentVersion
  • parametersparameters
  • variablesvariables
  • resourcesresources
  • outputsoutputs

例如,可以通过 $TemplateObject.parameters 获取参数的集合。For example, you can get the collection of parameters with $TemplateObject.parameters.

如果需要对整个模板执行字符串操作,请使用 string 参数。Use the string parameter when you need to do a string operation on the whole template. 使用 string 参数的测试采用以下格式:A test that uses the string parameter has the following format:

param(
    [Parameter(Mandatory)]
    [string]
    $TemplateText
)

# Implement test logic that performs string operations.
# Output error with: Write-Error -Message

例如,可以运行字符串参数的正则表达式,以查看是否使用了特定语法。For example, you can run a regular expression of the string parameter to see if a specific syntax is used.

若要了解有关实施测试的更多信息,请查看该文件夹中的其他测试。To learn more about implementing the test, look at the other tests in that folder.

与 Azure Pipelines 集成Integrate with Azure Pipelines

可以将测试工具包添加到 Azure Pipelines。You can add the test toolkit to your Azure Pipeline. 使用管道,可以在每次更新模板时运行测试,也可以在部署过程中运行测试。With a pipeline, you can run the test every time the template is updated, or run it as part of your deployment process.

将测试工具包添加到管道的最简单的方法是利用第三方扩展。The easiest way to add the test toolkit to your pipeline is with third-party extensions. 提供以下两个扩展:The following two extensions are available:

或者,你可以执行自己的任务。Or, you can implement your own tasks. 以下示例演示如何下载测试工具包。The following example shows how to download the test toolkit.

{
    "environment": {},
    "enabled": true,
    "continueOnError": false,
    "alwaysRun": false,
    "displayName": "Download TTK",
    "timeoutInMinutes": 0,
    "condition": "succeeded()",
    "task": {
        "id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1",
        "versionSpec": "2.*",
        "definitionType": "task"
    },
    "inputs": {
        "targetType": "inline",
        "filePath": "",
        "arguments": "",
        "script": "New-Item '$(ttk.folder)' -ItemType Directory\nInvoke-WebRequest -uri '$(ttk.uri)' -OutFile \"$(ttk.folder)/$(ttk.asset.filename)\" -Verbose\nGet-ChildItem '$(ttk.folder)' -Recurse\n\nWrite-Host \"Expanding files...\"\nExpand-Archive -Path '$(ttk.folder)/*.zip' -DestinationPath '$(ttk.folder)' -Verbose\n\nWrite-Host \"Expanded files found:\"\nGet-ChildItem '$(ttk.folder)' -Recurse",
        "errorActionPreference": "stop",
        "failOnStderr": "false",
        "ignoreLASTEXITCODE": "false",
        "pwsh": "true",
        "workingDirectory": ""
    }
}

下一个示例演示如何运行测试。The next example shows how to run the tests.

{
    "environment": {},
    "enabled": true,
    "continueOnError": true,
    "alwaysRun": false,
    "displayName": "Run Best Practices Tests",
    "timeoutInMinutes": 0,
    "condition": "succeeded()",
    "task": {
        "id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1",
        "versionSpec": "2.*",
        "definitionType": "task"
    },
    "inputs": {
        "targetType": "inline",
        "filePath": "",
        "arguments": "",
        "script": "Import-Module $(ttk.folder)/arm-ttk/arm-ttk.psd1 -Verbose\n$testOutput = @(Test-AzTemplate -TemplatePath \"$(sample.folder)\")\n$testOutput\n\nif ($testOutput | ? {$_.Errors }) {\n   exit 1 \n} else {\n    Write-Host \"##vso[task.setvariable variable=result.best.practice]$true\"\n    exit 0\n} \n",
        "errorActionPreference": "continue",
        "failOnStderr": "true",
        "ignoreLASTEXITCODE": "false",
        "pwsh": "true",
        "workingDirectory": ""
    }
}

后续步骤Next steps

若要了解默认测试,请参阅工具包的测试用例To learn about the default tests, see Test cases for toolkit.