简体   繁体   English

使用 Pester 模拟 azure cli 命令

[英]Mock azure cli commands with Pester

I have a buch of Azure Cli scripts that I have put inside a powershell function, for example:我有一堆 Azure Cli 脚本,我将它们放在 powershell function 中,例如:

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.而且我想模拟az ad app create但我不知道如何继续,我也没有找到任何如何做到这一点的例子。 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?当然,我最终可以为每个az命令创建我自己的 powershell function 并且我可以模拟这些功能,但我想知道它是否不能变得更容易?

I don't think it's possible to mock functions that aren't written in PowerShell unless you wrap those commands in a PowerShell function.我认为不可能模拟不是用 PowerShell 编写的函数,除非您将这些命令包装在 PowerShell function 中。 However, there is a native Microsoft-written PowerShell module that might suit your needs.但是,有一个本地 Microsoft 编写的 PowerShell 模块可能适合您的需求。 You could easily mock these functions without creating wrapper functions.您可以轻松地模拟这些函数,而无需创建包装函数。

https://docs.microsoft.com/en-us/powershell/azure/new-azureps-module-az?view=azps-5.7.0 https://docs.microsoft.com/en-us/powershell/azure/new-azureps-module-az?view=azps-5.7.0

To mock a bash command like az or any other kind is:要模拟像az或任何其他类型的 bash 命令是:

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 Pester 没有记录这一点,此解决方案基于此 github 问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM