연습 - 테스트 도구 키트를 사용하여 사용자 지정 테스트 작성 및 실행

완료됨

제품 팀의 멤버로서 일부 팀 또는 도메인 특정 규칙을 구현하는 것이 중요합니다. 구현하는 방법은 규칙을 테스트로 구현하는 것입니다. 그런 다음 테스트 도구 키트를 사용하여 이러한 테스트를 실행할 수 있습니다.

사용자 지정 테스트 작성 및 실행

사용자 지정 테스트를 작성하고 테스트 도구 키트 도구를 사용하여 실행합니다. 또한 테스트에 통과하도록 배포 템플릿을 수정합니다. 사용자 지정 테스트는 모든 매개 변수가 명명 규칙을 따르는지 확인하려고 합니다. 이 규칙은 작업 중인 제품 팀의 도메인 관련 요구 사항입니다.

이 연습에서는 두 개의 텍스트 편집기를 열어 두는 것이 좋습니다.

  • 사용자 지정 테스트 작성. 테스트 도구 키트 설치 디렉터리의 하위 디렉터리 arm-ttk/testcases/deploymentTemplate/의 경로를 찾습니다. 여기에서 Visual Studio Code를 실행하여 사용자 지정 테스트를 만들고 편집합니다.
  • 템플릿 파일을 작성하고 테스트를 실행합니다. 이 경로에 대해 원하는 위치를 선택합니다. 메시지가 표시되면 azuredeploy.json 파일을 쉽게 편집할 수 있도록 Visual Studio Code의 인스턴스를 이 경로에서 시작하는 것이 좋습니다. 테스트를 쉽게 실행하려면 이 Visual Studio Code 인스턴스를 사용하여 통합 터미널을 시작합니다.

템플릿 파일 만들기

디렉터리를 선택하고 azuredeploy.json이라는 파일을 만듭니다.

경고

선택한 디렉터리가 하위 디렉터리 없이 비어 있는지 확인합니다.

다음 콘텐츠를 제공합니다.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {},
  "resources": []
}

사용자 지정 테스트 만들기

  1. Visual Studio Code를 열고 테스트 도구 키트의 설치 디렉터리로 이동합니다. 하위 디렉터리 arm-ttk/testcases/deploymentTemplate으로 이동합니다. 다음 명령을 실행합니다.

    code .
    

    참고

    Visual Studio Code가 해당 경로에 없는 경우 Visual Studio Code를 수동으로 열고 디렉터리를 엽니다.

  2. Custom-ParameterNaming.test.ps1이라는 사용자 지정 테스트 파일을 만듭니다. 다음 콘텐츠를 파일에 포함시킵니다.

    param(
    [Parameter(Mandatory=$false,Position=0)] #not mandatory for case of an empty resource array
    [PSObject]
    $MainTemplateResources
    )
    
    Write-Error "To be implemented"
    

    텍스트 편집기를 열어 둡니다. 나중에 이 파일을 편집할 것입니다.

사용자 지정 테스트 실행

다음 단계를 수행하여 사용자 지정 테스트를 실행합니다.

  1. 새 터미널 창을 열거나 이전 창을 다시 사용합니다.

  2. azuredeploy.json을 만든 디렉터리로 이동합니다. 다음 명령을 실행하여 Visual Studio Code를 시작합니다.

    code .
    

    참고

    Visual Studio Code가 해당 경로에 없는 경우 Visual Studio Code를 수동으로 열고 템플릿 디렉터리를 엽니다.

  3. Visual Studio Code의 위쪽 메뉴에서 터미널>새 터미널을 선택하여 통합 터미널을 엽니다. 터미널에서 다음 명령을 실행하여 PowerShell 셸을 시작합니다.

    pwsh
    

    다음과 유사한 출력이 표시됩니다.

    PowerShell 7.0.3
    Copyright (c) Microsoft Corporation. All rights reserved.
    
    https://aka.ms/powershell
    Type 'help' to get help.
    
  4. 터미널에서 Import-Module을 실행합니다.

    참고

    모듈을 가져오기 전에 path/to/arm-ttk/arm-ttk.psd1을 다운로드한 테스트 도구 키트의 경로로 바꿉니다.

    Import-Module path/to/arm-ttk/arm-ttk.psd1
    

    Downloads 디렉터리에 도구를 다운로드했거나 복제한 경우 경로는 /Users/<user>/Downloads/arm-ttk/arm-ttk/arm-ttk.psd1과 같이 표시됩니다.

    이제 도구를 사용할 준비가 되었습니다. 동일한 PowerShell 세션에서는 가져오기 명령을 다시 실행하지 않아도 됩니다.

  5. 터미널에서 Test-AzTemplate을 실행하여 테스트 실행을 시작합니다.

    Test-AzTemplate -TemplatePath .
    

    출력은 다음과 유사합니다. 강조 표시된 선은 다음 테스트를 나타냅니다.

    Validating custom\azuredeploy.json
      JSONFiles Should Be Valid
        [+] JSONFiles Should Be Valid (56 ms)
    Pass  : 1
    Fail  : 0
    Total : 1
    
    
    
      adminUsername Should Not Be A Literal
        [+] adminUsername Should Not Be A Literal (68 ms)
      apiVersions Should Be Recent In Reference Functions
        [+] apiVersions Should Be Recent In Reference Functions (203 ms)
      apiVersions Should Be Recent
        [+] apiVersions Should Be Recent (137 ms)
      artifacts parameter
        [+] artifacts parameter (145 ms)
      CommandToExecute Must Use ProtectedSettings For Secrets
        [+] CommandToExecute Must Use ProtectedSettings For Secrets (171 ms)
      deploymentTemplate
        [-] Custom ParameterNaming (354 ms)
            To be implemented
    
      DependsOn Best Practices
        [+] DependsOn Best Practices (152 ms)
      Deployment Resources Must Not Be Debug
        [+] Deployment Resources Must Not Be Debug (152 ms)
      DeploymentTemplate Must Not Contain Hardcoded Uri
        [+] DeploymentTemplate Must Not Contain Hardcoded Uri (185 ms)
      DeploymentTemplate Schema Is Correct
        [+] DeploymentTemplate Schema Is Correct (197 ms)
      Dynamic Variable References Should Not Use Concat
        [+] Dynamic Variable References Should Not Use Concat (157 ms)
      IDs Should Be Derived From ResourceIDs
        [+] IDs Should Be Derived From ResourceIDs (69 ms)
      Location Should Not Be Hardcoded
        [+] Location Should Not Be Hardcoded (260 ms)
      ManagedIdentityExtension must not be used
        [+] ManagedIdentityExtension must not be used (70 ms)
      Min And Max Value Are Numbers
        [+] Min And Max Value Are Numbers (213 ms)
      Outputs Must Not Contain Secrets
        [+] Outputs Must Not Contain Secrets (76 ms)
      Parameter Types Should Be Consistent
        [+] Parameter Types Should Be Consistent (68 ms)
      Parameters Must Be Referenced
        [+] Parameters Must Be Referenced (93 ms)
      Password params must be secure
        [+] Password params must be secure (111 ms)
      providers apiVersions Is Not Permitted
        [+] providers apiVersions Is Not Permitted (68 ms)
      ResourceIds should not contain
        [+] ResourceIds should not contain (210 ms)
      Resources Should Have Location
        [+] Resources Should Have Location (113 ms)
      Resources Should Not Be Ambiguous
        [+] Resources Should Not Be Ambiguous (147 ms)
      Secure Params In Nested Deployments
        [+] Secure Params In Nested Deployments (242 ms)
      Secure String Parameters Cannot Have Default
        [+] Secure String Parameters Cannot Have Default (129 ms)
      Template Should Not Contain Blanks
        [+] Template Should Not Contain Blanks (201 ms)
      URIs Should Be Properly Constructed
        [+] URIs Should Be Properly Constructed (180 ms)
      Variables Must Be Referenced
        [+] Variables Must Be Referenced (132 ms)
      Virtual Machines Should Not Be Preview
        [+] Virtual Machines Should Not Be Preview (91 ms)
      VM Images Should Use Latest Version
        [+] VM Images Should Use Latest Version (114 ms)
      VM Size Should Be A Parameter
        [+] VM Size Should Be A Parameter (130 ms)
    Pass  : 31
    Fail  : 1
    Total : 32
    

    이제 테스트를 찾았으므로 이 터미널 창을 열어 둡니다. 나중에 다시 사용하게 됩니다.

사용자 지정 테스트 리팩터링

이제 사용자 지정 테스트에 적절한 구현을 제공합니다.

  1. Custom-ParameterNaming.test.ps1 파일이 있는 텍스트 편집기로 돌아갑니다.

    참고

    실수로 Visual Studio Code를 닫은 경우에는 하위 디렉터리 arm-ttk/testcases/deploymentTemplate으로 이동하고 Custom-ParameterNaming.test.ps1 파일을 엽니다.

  2. 파일의 콘텐츠를 다음 코드로 바꿉니다.

    <#
    .Synopsis
     Ensures that all parameters adheres to a naming standard
    .Description
     All parameters should start with the company specific prefix 'tailwind'
    #>
    param(
       # The Template Object
       [Parameter(Mandatory = $true, Position = 0)]
       [PSObject]
       $TemplateObject,
    
       # The Template JSON Text
       [Parameter(Mandatory = $true, Position = 0)]
       [PSObject]
       $TemplateText
    )
    
    foreach ($parameter in $TemplateObject.parameters.psobject.properties) {
      # If the parameter name starts with tailwind, then the parameter is correctly named
      if ($parameter.Name -notmatch 'tailwind*') {
         Write-Error "Parameter '$($parameter.Name)' must start with prefix 'tailwind'" -TargetObject $parameter
      }
    }
    

    앞의 코드는 모든 매개 변수를 반복합니다. 이는 name 특성을 검사하고 이름이 tailwind 접두사로 시작하는지 확인합니다. 검사된 매개 변수가 명명 규칙과 일치하지 않는 경우 코드는 적합한 오류 메시지와 함께 Write-Error cmdlet을 호출합니다.

템플릿 파일 업데이트

이제 템플릿 파일에 매개 변수를 추가합니다.

  1. azuredeploy.json을 포함하는 텍스트 편집기를 선택하고 파일의 콘텐츠를 다음 콘텐츠로 변경합니다.

    {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "location": {
          "type": "string",
          "metadata": {
            "description": "a deployment location"
          }
        }
      },
      "resources": []
    }
    

    이전 템플릿 콘텐츠는 이름에 tailwind 접두사가 없으므로 명명 규칙을 충족하지 않는 매개 변수 location을 정의합니다.

테스트 도구 키트 다시 실행

이제 사용자 지정 테스트가 작성되었습니다. 그러나 템플릿 파일의 이름 지정이 요구 사항을 충족하지 않습니다. 따라서 예정된 테스트 실행이 실패할 것으로 예상됩니다. 다음 단계를 수행하여 이 경우에 해당하는지 확인합니다.

PowerShell이 시작되고 테스트 도구 키트를 가져온 기존 Visual Studio Code 통합 터미널 창을 사용합니다.

Visual Studio Code의 통합 터미널에서 Test-AzTemplate을 실행합니다.

Test-AzTemplate -TemplatePath . -Test Custom-ParameterNaming

이전 명령은 테스트 이름을 입력으로 사용하는 -Test 매개 변수를 사용하여 실행됩니다. Custom-ParameterNaming을 매개 변수로 제공했으므로 새로 개발된 테스트‘만’ 실행될 것입니다.

-Test 매개 변수는 실행되는 항목 및 터미널 출력의 크기를 제한하므로 테스트를 개발할 때 이 매개 변수를 사용하는 것이 좋습니다.

이 명령을 수행하면 다음 출력이 표시됩니다.

Validating custom\azuredeploy.json
 deploymentTemplate
   [-] Custom ParameterNaming (2ms)
       Parameter 'location' must start with prefix 'tailwind'

결과는 테스트가 작동함을 나타냅니다. 배포 파일을 변경하여 이 경우에 해당하는지 확인해 보겠습니다.

템플릿 파일 수정

이제 사용자 지정 테스트에 제시된 규칙을 준수하도록 템플릿 파일을 변경하여 사용자 지정 테스트의 정확성을 확인합니다.

  1. azuredeploy.json 파일이 표시된 동일한 Visual Studio Code 인스턴스에서 파일의 콘텐츠를 다음 콘텐츠로 변경합니다.

    {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "tailwindLocation": {
          "type": "string",
          "metadata": {
            "description": "a deployment location"
          }
        }
      },
      "resources": []
    }
    

    location 매개 변수의 이름이 tailwindLocation으로 바뀌었습니다. 이론적으로 이 매개 변수는 테스트를 통과해야 합니다. 확인해 보겠습니다.

  2. 계속해서 동일한 Visual Studio Code 인스턴스의 통합 터미널에서 Test-AzTemplate을 실행합니다.

    Test-AzTemplate -TemplatePath . -Test Custom-ParameterNaming
    

    이제 출력이 다음과 같이 표시됩니다.

    Validating custom\azuredeploy.json
      deploymentTemplate
        [+] Custom ParameterNaming (2 ms)
    

성공! 사용자 지정 테스트를 구현하고 실행했습니다. 또한 테스트의 조건과 일치하도록 배포 템플릿을 수정했습니다.

사용자 지정 테스트 작성 및 실행

사용자 지정 테스트를 작성하고 테스트 도구 키트 도구를 사용하여 실행합니다. 또한 테스트에 통과하도록 배포 템플릿을 수정합니다. 사용자 지정 테스트는 모든 매개 변수가 명명 규칙을 따르는지 확인하려고 합니다. 이 규칙은 작업 중인 제품 팀의 도메인 관련 요구 사항입니다.

이 연습에서는 두 개의 텍스트 편집기를 열어 두는 것이 좋습니다.

  • 사용자 지정 테스트 작성. 테스트 도구 키트 설치 디렉터리의 하위 디렉터리 arm-ttk/testcases/deploymentTemplate/의 경로를 찾습니다. 여기에서 Visual Studio Code를 실행하여 사용자 지정 테스트를 만들고 편집합니다.
  • 템플릿 파일을 작성하고 테스트를 실행합니다. 이 경로에 대해 원하는 위치를 선택합니다. 메시지가 표시되면 azuredeploy.json 파일을 쉽게 편집할 수 있도록 Visual Studio Code의 인스턴스를 이 경로에서 시작하는 것이 좋습니다. 테스트를 쉽게 실행하려면 이 Visual Studio Code 인스턴스를 사용하여 통합 터미널을 시작합니다.

템플릿 파일 만들기

디렉터리를 선택하고 azuredeploy.json이라는 파일을 만듭니다.

경고

선택한 디렉터리가 하위 디렉터리 없이 비어 있는지 확인합니다.

다음 콘텐츠를 제공합니다.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {},
  "resources": []
}

사용자 지정 테스트 만들기

  1. 터미널을 엽니다. 테스트 도구 키트의 설치 디렉터리로 이동합니다. 하위 디렉터리 arm-ttk/testcases/deploymentTemplate으로 이동합니다. 다음 명령을 실행합니다.

    code .
    

    참고

    Visual Studio Code가 해당 경로에 없는 경우 Visual Studio Code를 수동으로 열고 디렉터리를 엽니다.

  2. Custom-ParameterNaming.test.ps1이라는 사용자 지정 파일을 만듭니다. 다음 콘텐츠를 파일에 포함시킵니다.

    param(
    [Parameter(Mandatory=$false,Position=0)] #not mandatory for case of an empty resource array
    [PSObject]
    $MainTemplateResources
    )
    
    Write-Error "To be implemented"
    

    텍스트 편집기를 열어 둡니다. 나중에 이 파일을 편집할 것입니다.

사용자 지정 테스트 실행

다음 단계를 수행하여 사용자 지정 테스트를 실행합니다.

  1. 새 터미널 창을 열거나 이전 창을 다시 사용합니다.

  2. azuredeploy.json을 만든 디렉터리로 이동합니다. 다음 명령을 실행하여 Visual Studio Code를 시작합니다.

    code .
    

    참고

    Visual Studio Code가 해당 경로에 없는 경우 Visual Studio Code를 수동으로 열고 템플릿 디렉터리를 엽니다.

  3. Visual Code의 위쪽 메뉴에서 터미널>새 터미널을 선택하여 통합 터미널을 엽니다. 터미널에서 다음 명령을 실행하여 PowerShell 셸을 시작합니다.

    pwsh
    

    다음과 유사한 출력이 표시됩니다.

    PowerShell 7.0.3
    Copyright (c) Microsoft Corporation. All rights reserved.
    
    https://aka.ms/powershell
    Type 'help' to get help.
    
  4. 터미널에서 Import-Module을 실행합니다.

    참고

    모듈을 가져오기 전에 path/to/arm-ttk/arm-ttk.psd1을 다운로드한 테스트 도구 키트의 경로로 바꿉니다.

    Import-Module path/to/arm-ttk/arm-ttk.psd1
    

    Downloads 디렉터리에 도구를 다운로드했거나 복제한 경우 경로는 /Users/<user>/Downloads/arm-ttk/arm-ttk/arm-ttk.psd1과 같이 표시됩니다.

    이제 도구를 사용할 준비가 되었습니다. 동일한 PowerShell 세션에서는 가져오기 명령을 다시 실행하지 않아도 됩니다.

  5. 터미널에서 Test-AzTemplate을 실행합니다.

    Test-AzTemplate -TemplatePath .
    

    출력은 다음과 유사합니다. 강조 표시된 선은 다음 테스트를 나타냅니다.

    Validating custom\azuredeploy.json
      JSONFiles Should Be Valid
        [+] JSONFiles Should Be Valid (56 ms)
    Pass  : 1
    Fail  : 0
    Total : 1
    
    
    
      adminUsername Should Not Be A Literal
        [+] adminUsername Should Not Be A Literal (68 ms)
      apiVersions Should Be Recent In Reference Functions
        [+] apiVersions Should Be Recent In Reference Functions (203 ms)
      apiVersions Should Be Recent
        [+] apiVersions Should Be Recent (137 ms)
      artifacts parameter
        [+] artifacts parameter (145 ms)
      CommandToExecute Must Use ProtectedSettings For Secrets
        [+] CommandToExecute Must Use ProtectedSettings For Secrets (171 ms)
      deploymentTemplate
        [-] Custom ParameterNaming (354 ms)
            To be implemented
    
      DependsOn Best Practices
        [+] DependsOn Best Practices (152 ms)
      Deployment Resources Must Not Be Debug
        [+] Deployment Resources Must Not Be Debug (152 ms)
      DeploymentTemplate Must Not Contain Hardcoded Uri
        [+] DeploymentTemplate Must Not Contain Hardcoded Uri (185 ms)
      DeploymentTemplate Schema Is Correct
        [+] DeploymentTemplate Schema Is Correct (197 ms)
      Dynamic Variable References Should Not Use Concat
        [+] Dynamic Variable References Should Not Use Concat (157 ms)
      IDs Should Be Derived From ResourceIDs
        [+] IDs Should Be Derived From ResourceIDs (69 ms)
      Location Should Not Be Hardcoded
        [+] Location Should Not Be Hardcoded (260 ms)
      ManagedIdentityExtension must not be used
        [+] ManagedIdentityExtension must not be used (70 ms)
      Min And Max Value Are Numbers
        [+] Min And Max Value Are Numbers (213 ms)
      Outputs Must Not Contain Secrets
        [+] Outputs Must Not Contain Secrets (76 ms)
      Parameter Types Should Be Consistent
        [+] Parameter Types Should Be Consistent (68 ms)
      Parameters Must Be Referenced
        [+] Parameters Must Be Referenced (93 ms)
      Password params must be secure
        [+] Password params must be secure (111 ms)
      providers apiVersions Is Not Permitted
        [+] providers apiVersions Is Not Permitted (68 ms)
      ResourceIds should not contain
        [+] ResourceIds should not contain (210 ms)
      Resources Should Have Location
        [+] Resources Should Have Location (113 ms)
      Resources Should Not Be Ambiguous
        [+] Resources Should Not Be Ambiguous (147 ms)
      Secure Params In Nested Deployments
        [+] Secure Params In Nested Deployments (242 ms)
      Secure String Parameters Cannot Have Default
        [+] Secure String Parameters Cannot Have Default (129 ms)
      Template Should Not Contain Blanks
        [+] Template Should Not Contain Blanks (201 ms)
      URIs Should Be Properly Constructed
        [+] URIs Should Be Properly Constructed (180 ms)
      Variables Must Be Referenced
        [+] Variables Must Be Referenced (132 ms)
      Virtual Machines Should Not Be Preview
        [+] Virtual Machines Should Not Be Preview (91 ms)
      VM Images Should Use Latest Version
        [+] VM Images Should Use Latest Version (114 ms)
      VM Size Should Be A Parameter
        [+] VM Size Should Be A Parameter (130 ms)
    Pass  : 31
    Fail  : 1
    Total : 32
    

    이제 테스트를 찾았으므로 이 터미널 창을 열어 둡니다. 나중에 다시 사용하게 됩니다.

사용자 지정 테스트 리팩터링

이제 사용자 지정 테스트에 적절한 구현을 제공합니다.

  1. Custom-ParameterNaming.test.ps1 파일이 있는 텍스트 편집기로 돌아갑니다.

    참고

    실수로 Visual Studio Code를 닫은 경우에는 하위 디렉터리 arm-ttk/testcases/deploymentTemplate으로 이동하고 Custom-ParameterNaming.test.ps1 파일을 엽니다.

  2. 파일의 콘텐츠를 다음 코드로 바꿉니다.

    <#
    .Synopsis
     Ensures that all parameters adheres to a naming standard
    .Description
     All parameters should start with the company specific prefix 'tailwind'
    #>
    param(
       # The Template Object
       [Parameter(Mandatory = $true, Position = 0)]
       [PSObject]
       $TemplateObject,
    
       # The Template JSON Text
       [Parameter(Mandatory = $true, Position = 0)]
       [PSObject]
       $TemplateText
    )
    
    foreach ($parameter in $TemplateObject.parameters.psobject.properties) {
      # If the parameter name starts with tailwind, then the parameter is correctly named
      if ($parameter.Name -notmatch 'tailwind*') {
         Write-Error "Parameter '$($parameter.Name)' must start with prefix 'tailwind'" -TargetObject $parameter
      }
    }
    

    앞의 코드는 모든 매개 변수를 반복합니다. 이는 name 특성을 검사하고 이름이 tailwind 접두사로 시작하는지 확인합니다. 검사된 매개 변수가 명명 규칙과 일치하지 않는 경우 코드는 적합한 오류 메시지와 함께 Write-Error cmdlet을 호출합니다.

템플릿 파일 업데이트

이제 템플릿 파일에 매개 변수를 추가합니다.

  1. azuredeploy.json을 포함하는 텍스트 편집기를 선택하고 파일의 콘텐츠를 다음 콘텐츠로 변경합니다.

    {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "location": {
          "type": "string",
          "metadata": {
            "description": "a deployment location"
          }
        }
      },
      "resources": []
    }
    

    이전 템플릿 콘텐츠는 이름에 tailwind 접두사가 없으므로 명명 규칙을 충족하지 않는 매개 변수 location을 정의합니다.

테스트 도구 키트 다시 실행

이제 사용자 지정 테스트가 작성되었습니다. 그러나 템플릿 파일의 이름 지정이 요구 사항을 충족하지 않습니다. 따라서 예정된 테스트 실행이 실패할 것으로 예상됩니다. 다음 단계를 수행하여 이 경우에 해당하는지 확인합니다.

참고

PowerShell이 시작되고 테스트 도구 키트를 가져온 기존 Visual Studio Code 통합 터미널 창을 사용합니다.

Visual Studio Code의 통합 터미널에서 Test-AzTemplate을 실행합니다.

Test-AzTemplate -TemplatePath . -Test Custom-ParameterNaming

이전 명령은 테스트 이름을 입력으로 사용하는 -Test 매개 변수를 사용하여 실행됩니다. Custom-ParameterNaming을 매개 변수로 제공했으므로 새로 개발된 테스트만 실행될 것입니다.

이 매개 변수는 실행되는 항목 및 터미널 출력의 크기를 제한하므로 테스트를 개발할 때 이 매개 변수를 사용하는 것이 좋습니다.

이 명령을 수행하면 다음 출력이 표시됩니다.

Validating custom\azuredeploy.json
 deploymentTemplate
   [-] Custom ParameterNaming (2ms)
       Parameter 'location' must start with prefix 'tailwind'

결과는 테스트가 작동함을 나타냅니다. 배포 파일을 변경하여 이 경우에 해당하는지 확인해 보겠습니다.

템플릿 파일 수정

이제 사용자 지정 테스트에 제시된 규칙을 준수하도록 템플릿 파일을 변경하여 사용자 지정 테스트의 정확성을 확인합니다.

  1. azuredeploy.json 파일이 표시된 동일한 Visual Studio Code 인스턴스에서 파일의 콘텐츠를 다음 콘텐츠로 변경합니다.

    {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "tailwindLocation": {
          "type": "string",
          "metadata": {
            "description": "a deployment location"
          }
        }
      },
      "resources": []
    }
    

    location 매개 변수의 이름이 tailwindLocation으로 바뀌었습니다. 이론적으로 이 매개 변수는 테스트를 통과해야 합니다. 확인해 보겠습니다.

  2. 계속해서 동일한 Visual Studio Code 인스턴스의 통합 터미널에서 Test-AzTemplate을 실행합니다.

    Test-AzTemplate -TemplatePath . -Test Custom-ParameterNaming
    

    이제 출력이 다음과 같이 표시됩니다.

    Validating custom\azuredeploy.json
      deploymentTemplate
        [+] Custom ParameterNaming (2 ms)
    

성공! 사용자 지정 테스트를 구현하고 실행했습니다. 또한 테스트의 조건과 일치하도록 배포 템플릿을 수정했습니다.

사용자 지정 테스트 작성 및 실행

사용자 지정 테스트를 작성하고 테스트 도구 키트 도구를 사용하여 실행합니다. 또한 테스트에 통과하도록 배포 템플릿을 수정합니다. 사용자 지정 테스트는 모든 매개 변수가 명명 규칙을 따르는지 확인하려고 합니다. 이 규칙은 작업 중인 제품 팀의 도메인 관련 요구 사항입니다.

이 연습에서는 두 개의 텍스트 편집기를 열어 두는 것이 좋습니다.

  • 사용자 지정 테스트 작성. 테스트 도구 키트 설치 디렉터리의 하위 디렉터리 arm-ttk\testcases\deploymentTemplate\의 경로를 찾습니다. 여기에서 Visual Studio Code를 실행하여 사용자 지정 테스트를 만들고 편집합니다.
  • 템플릿 파일을 작성하고 테스트를 실행합니다. 이 경로에 대해 원하는 위치를 선택합니다. 메시지가 표시되면 azuredeploy.json 파일을 쉽게 편집할 수 있도록 Visual Studio Code의 인스턴스를 이 경로에서 시작하는 것이 좋습니다. 테스트를 쉽게 실행하려면 이 Visual Studio Code 인스턴스를 사용하여 통합 터미널을 시작합니다.

템플릿 파일 만들기

디렉터리를 선택하고 azuredeploy.json이라는 파일을 만듭니다.

경고

선택한 디렉터리가 하위 디렉터리 없이 비어 있는지 확인합니다.

다음 콘텐츠를 제공합니다.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {},
  "resources": []
}

사용자 지정 테스트 만들기

  1. 터미널을 엽니다.

  2. 테스트 도구 키트의 설치 디렉터리로 이동합니다.

  3. 하위 디렉터리 arm-ttk\testcases\deploymentTemplate으로 이동합니다.

  4. 다음 명령을 실행합니다.

    code .
    

    참고

    Visual Studio Code가 해당 경로에 없는 경우 Visual Studio Code를 수동으로 열고 디렉터리를 엽니다.

  5. Custom-ParameterNaming.test.ps1이라는 파일을 만들고 파일에 다음 콘텐츠를 제공합니다.

    param(
    [Parameter(Mandatory=$false,Position=0)] #not mandatory for case of an empty resource array
    [PSObject]
    $MainTemplateResources
    )
    
    Write-Error "To be implemented"
    

    텍스트 편집기를 열어 둡니다. 나중에 이 파일을 편집할 것입니다.

사용자 지정 테스트 실행

다음 단계를 수행하여 사용자 지정 테스트를 실행합니다.

  1. 새 터미널 창을 열거나 이전 창을 다시 사용합니다.

  2. azuredeploy.json을 만든 디렉터리로 이동합니다.

  3. 다음 명령을 실행하여 Visual Studio Code를 시작합니다.

    code .
    

    참고

    Visual Studio Code가 해당 경로에 없는 경우 Visual Studio Code를 수동으로 열고 템플릿 디렉터리를 엽니다.

  4. Visual Studio Code에서 통합 터미널을 엽니다. 명령 팔레트를 표시하고 PowerShell을 입력한 다음 통합 터미널 표시를 선택합니다.

  5. 터미널에서 다음 명령을 실행합니다.

    참고

    모듈을 가져오기 전에 path\to\arm-ttk\arm-ttk.psd1을 다운로드한 테스트 도구 키트의 경로로 바꿉니다.

    Import-Module path\to\arm-ttk\arm-ttk.psd1
    

    Downloads 디렉터리에 도구를 다운로드했거나 복제한 경우 경로는 \Users\<user>\Downloads\arm-ttk\arm-ttk\arm-ttk.psd1과 같이 표시됩니다.

    이제 도구를 사용할 준비가 되었습니다. 동일한 PowerShell 세션에서는 가져오기 명령을 다시 실행하지 않아도 됩니다.

  6. 터미널에서 Test-AzTemplate을 실행합니다.

    Test-AzTemplate -TemplatePath .
    

    출력은 다음과 유사합니다. 강조 표시된 선은 다음 테스트를 나타냅니다.

    Validating custom\azuredeploy.json
      JSONFiles Should Be Valid
        [+] JSONFiles Should Be Valid (56 ms)
    Pass  : 1
    Fail  : 0
    Total : 1
    
    
    
      adminUsername Should Not Be A Literal
        [+] adminUsername Should Not Be A Literal (68 ms)
      apiVersions Should Be Recent In Reference Functions
        [+] apiVersions Should Be Recent In Reference Functions (203 ms)
      apiVersions Should Be Recent
        [+] apiVersions Should Be Recent (137 ms)
      artifacts parameter
        [+] artifacts parameter (145 ms)
      CommandToExecute Must Use ProtectedSettings For Secrets
        [+] CommandToExecute Must Use ProtectedSettings For Secrets (171 ms)
      deploymentTemplate
        [-] Custom ParameterNaming (354 ms)
            To be implemented
    
      DependsOn Best Practices
        [+] DependsOn Best Practices (152 ms)
      Deployment Resources Must Not Be Debug
        [+] Deployment Resources Must Not Be Debug (152 ms)
      DeploymentTemplate Must Not Contain Hardcoded Uri
        [+] DeploymentTemplate Must Not Contain Hardcoded Uri (185 ms)
      DeploymentTemplate Schema Is Correct
        [+] DeploymentTemplate Schema Is Correct (197 ms)
      Dynamic Variable References Should Not Use Concat
        [+] Dynamic Variable References Should Not Use Concat (157 ms)
      IDs Should Be Derived From ResourceIDs
        [+] IDs Should Be Derived From ResourceIDs (69 ms)
      Location Should Not Be Hardcoded
        [+] Location Should Not Be Hardcoded (260 ms)
      ManagedIdentityExtension must not be used
        [+] ManagedIdentityExtension must not be used (70 ms)
      Min And Max Value Are Numbers
        [+] Min And Max Value Are Numbers (213 ms)
      Outputs Must Not Contain Secrets
        [+] Outputs Must Not Contain Secrets (76 ms)
      Parameter Types Should Be Consistent
        [+] Parameter Types Should Be Consistent (68 ms)
      Parameters Must Be Referenced
        [+] Parameters Must Be Referenced (93 ms)
      Password params must be secure
        [+] Password params must be secure (111 ms)
      providers apiVersions Is Not Permitted
        [+] providers apiVersions Is Not Permitted (68 ms)
      ResourceIds should not contain
        [+] ResourceIds should not contain (210 ms)
      Resources Should Have Location
        [+] Resources Should Have Location (113 ms)
      Resources Should Not Be Ambiguous
        [+] Resources Should Not Be Ambiguous (147 ms)
      Secure Params In Nested Deployments
        [+] Secure Params In Nested Deployments (242 ms)
      Secure String Parameters Cannot Have Default
        [+] Secure String Parameters Cannot Have Default (129 ms)
      Template Should Not Contain Blanks
        [+] Template Should Not Contain Blanks (201 ms)
      URIs Should Be Properly Constructed
        [+] URIs Should Be Properly Constructed (180 ms)
      Variables Must Be Referenced
        [+] Variables Must Be Referenced (132 ms)
      Virtual Machines Should Not Be Preview
        [+] Virtual Machines Should Not Be Preview (91 ms)
      VM Images Should Use Latest Version
        [+] VM Images Should Use Latest Version (114 ms)
      VM Size Should Be A Parameter
        [+] VM Size Should Be A Parameter (130 ms)
    Pass  : 31
    Fail  : 1
    Total : 32
    

    이제 테스트를 찾았으므로 이 터미널 창을 열어 둡니다. 나중에 다시 사용하게 됩니다.

사용자 지정 테스트 리팩터링

이제 사용자 지정 테스트에 적절한 구현을 제공합니다.

  1. Custom-ParameterNaming.test.ps1 파일이 있는 텍스트 편집기로 돌아갑니다.

    참고

    실수로 Visual Studio Code를 닫은 경우에는 하위 디렉터리 testcases/deploymentTemplate으로 이동하고 Custom-ParameterNaming.test.ps1 파일을 엽니다.

  2. 파일의 콘텐츠를 다음 코드로 바꿉니다.

    <#
    .Synopsis
     Ensures that all parameters adheres to a naming standard
    .Description
     All parameters should start with the company specific prefix 'tailwind'
    #>
    param(
       # The Template Object
       [Parameter(Mandatory = $true, Position = 0)]
       [PSObject]
       $TemplateObject,
    
       # The Template JSON Text
       [Parameter(Mandatory = $true, Position = 0)]
       [PSObject]
       $TemplateText
    )
    
    foreach ($parameter in $TemplateObject.parameters.psobject.properties) {
      # If the parameter name starts with tailwind, then the parameter is correctly named
      if ($parameter.Name -notmatch 'tailwind*') {
         Write-Error "Parameter '$($parameter.Name)' must start with prefix 'tailwind'" -TargetObject $parameter
      }
    }
    

    앞의 코드는 모든 매개 변수를 반복합니다. 이는 name 특성을 검사하고 이름이 tailwind 접두사로 시작하는지 확인합니다. 검사된 매개 변수가 명명 규칙과 일치하지 않는 경우 코드는 적합한 오류 메시지와 함께 Write-Error cmdlet을 호출합니다.

템플릿 파일 업데이트

이제 템플릿 파일에 매개 변수를 추가합니다.

  1. azuredeploy.json을 포함하는 텍스트 편집기를 선택하고 파일의 콘텐츠를 다음 콘텐츠로 변경합니다.

    {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "location": {
          "type": "string",
          "metadata": {
            "description": "a deployment location"
          }
        }
      },
      "resources": []
    }
    

    이전 템플릿 콘텐츠는 이름에 tailwind 접두사가 없으므로 명명 규칙을 충족하지 않는 매개 변수 location을 정의합니다.

테스트 도구 키트 다시 실행

이제 사용자 지정 테스트가 작성되었습니다. 그러나 템플릿 파일의 이름 지정이 요구 사항을 충족하지 않습니다. 따라서 예정된 테스트 실행이 실패할 것으로 예상됩니다. 다음 단계를 수행하여 이 경우에 해당하는지 확인합니다.

PowerShell이 시작되고 테스트 도구 키트를 가져온 기존 Visual Studio Code 통합 터미널 창을 사용합니다.

Visual Studio Code의 통합 터미널에서 Test-AzTemplate을 실행합니다.

Test-AzTemplate -TemplatePath . -Test Custom-ParameterNaming

이전 명령은 테스트 이름을 입력으로 사용하는 -Test 매개 변수를 사용하여 실행됩니다. Custom-ParameterNaming을 매개 변수로 제공했으므로 새로 개발된 테스트만 실행될 것입니다.

이 매개 변수는 실행되는 항목 및 터미널 출력의 크기를 제한하므로 테스트를 개발할 때 이 매개 변수를 사용하는 것이 좋습니다.

이 명령을 수행하면 다음 출력이 표시됩니다.

Validating custom\azuredeploy.json
 deploymentTemplate
   [-] Custom ParameterNaming (2ms)
       Parameter 'location' must start with prefix 'tailwind'

결과는 테스트가 작동함을 나타냅니다. 배포 파일을 변경하여 이 경우에 해당하는지 확인해 보겠습니다.

템플릿 파일 수정

이제 사용자 지정 테스트에 제시된 규칙을 준수하도록 템플릿 파일을 변경하여 사용자 지정 테스트의 정확성을 확인합니다.

  1. azuredeploy.json 파일이 표시된 동일한 Visual Studio Code 인스턴스에서 파일의 콘텐츠를 다음 콘텐츠로 변경합니다.

    {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "tailwindLocation": {
          "type": "string",
          "metadata": {
            "description": "a deployment location"
          }
        }
      },
      "resources": []
    }
    

    location 매개 변수의 이름이 tailwindLocation으로 바뀌었습니다. 이론적으로 이 매개 변수는 테스트를 통과해야 합니다. 확인해 보겠습니다.

  2. 계속해서 동일한 Visual Studio Code 인스턴스의 통합 터미널에서 Test-AzTemplate을 실행합니다.

    Test-AzTemplate -TemplatePath . -Test Custom-ParameterNaming
    

    이제 출력이 다음과 같이 표시됩니다.

    Validating custom\azuredeploy.json
      Custom ParameterNaming
        [+] Custom ParameterNaming (9 ms)
    

성공! 사용자 지정 테스트를 구현하고 실행했습니다. 또한 테스트의 조건과 일치하도록 배포 템플릿을 수정했습니다.