Search code examples
powershellunit-testingpester

Mock azure cli commands with Pester


I have a buch of Azure Cli scripts that I have put inside a powershell function, for example:

function NewAppRegistration($name, $replyUrls, $resourceAccessesFilePath) {   
    $appRegistration = az ad app create `
        --display-name $name `
        --reply-urls $replyUrls `
        --oauth2-allow-implicit-flow true `
        --available-to-other-tenants false `
        -o json | 
    ConvertFrom-Json

    if (Test-Path $resourceAccessesFilePath) {
        $appRegistration = az ad app update `
        --id $appRegistration.appId `
        --required-resource-accesses $resourceAccessesFilePath
    }

    return $appRegistration
}

And I want to mock az ad app create but I have no clue how to proceed and I also don't find any example of how to to that. Of course I could end up creating for every az command my own powershell function and I could mock these functions, but I wonder if it could not be made easier?


Solution

  • To mock a bash command like az or any other kind is:

    Mock az {}
    

    For the assertion:

    Should -Invoke -CommandName "az" -Exactly -Times 1 -ParameterFilter { 
                "$args" -match "ad app create" -and
                "$args" -match "--display-name $expectedName" -and
                "$args" -match "--reply-urls" -and (-not (Compare-Object $args[6] $expectedReplyUrls)) -and
                "$args" -match "--oauth2-allow-implicit-flow true" -and
                "$args" -match "--available-to-other-tenants false" -and
                "$args" -match "-o json"
            }
    

    This is not documented by Pester and this solution was based on this github issue