如何模拟具有不同参数和不同结果的两次调用命令

时间:2019-06-25 05:47:12

标签: powershell pester

我有一个要与Pester一起测试的PowerShell函数:

function Install-RequiredModule (
    [string]$ModuleName,
    [string]$RepositoryName,
    [string]$ProxyUrl
    )
{
    # Errors from Install-Module are non-terminating.  They won't be caught using  
    # try - catch.  So check $Error instead.
    # Clear errors so we know if one shows up it must have been due to Install-Module.
    $Error.Clear()

    # Want to fail silently, without displaying anything in console to scare the user, 
    # because it's valid for Install-Module to fail for a user behind a proxy server.
    Install-Module -Name $ModuleName -Repository $RepositoryName `
        -ErrorAction SilentlyContinue -WarningAction SilentlyContinue

    if ($Error.Count -eq 0)
    {
        # throw 'NO error'
        return
    }

    # There was an error so try again, this time with proxy details.

    $proxyCredential = Get-Credential -Message 'Please enter credentials for proxy server'

    # No need to Silently Continue this time.  We want to see the error details.
    $Error.Clear()

    Install-Module -Name $ModuleName -Repository $RepositoryName `
        -Proxy $ProxyUrl -ProxyCredential $proxyCredential

    if ($Error.Count -gt 0)
    {
        throw $Error[0]
    }

    if (-not (Get-InstalledModule -Name $ModuleName -ErrorAction SilentlyContinue))
    {
        throw "Unknown error installing module '$ModuleName' from repository '$RepositoryName'."
    }

    Write-Output "Module '$ModuleName' successfully installed from repository '$RepositoryName'."
}

此函数可以调用两次Install-Module。它首先尝试不使用代理凭据,就好像它可以直接访问Internet。如果失败,则再次尝试,这次使用代理凭据。

如何使用Pester测试此功能?

我在PowerShell论坛here中读到,我应该能够使用不同的参数过滤器两次模拟同一命令。所以这就是我尝试过的:

function ExecuteInstallRequiredModule ()
{
    Install-RequiredModule -ModuleName 'TestModule' -RepositoryName 'TestRepo' `
        -ProxyUrl 'http://myproxy'
}

Describe 'Install-RequiredModule' {

    $securePassword = "mypassword" | 
        ConvertTo-SecureString -asPlainText -Force
    $psCredential = New-Object System.Management.Automation.PSCredential  ('MyUserName', $securePassword)
    Mock Get-Credential { return $psCredential }

    # Want to add an error to $Error without it being written to the host.
    Mock Install-Module { Write-Error "Some error" -ErrorAction SilentlyContinue } `
        -ParameterFilter { $Name -eq  'TestModule' -and $Repository -eq 'TestRepo' -and $ErrorAction -eq 'SilentlyContinue' -and $WarningAction -eq 'SilentlyContinue'}
    Mock Install-Module { return $Null } `
        -ParameterFilter { $Name -eq  'TestModule' -and $Repository -eq 'TestRepo' -and $Proxy -eq 'http://myproxy' -and $ProxyCredential -eq $psCredential }

    Mock Get-InstalledModule { return @('Non-null text') }

    It 'attempts to install module a second time if first attempt fails' {
        ExecuteInstallRequiredModule
        #Assert-VerifiableMock
        #Assert-MockCalled Install-Module -Scope It -Times 2
    }
}

在待测函数中取消注释# throw 'NO error'的行的注释,我发现在第一次调用Install-Module之后,$ Error.Count为0。因此,不会调用正在创建非终止错误的模拟程序,并且该函数将在第二次调用Install-Module之前返回。

3 个答案:

答案 0 :(得分:1)

您可以在try catch循环内用install-module调用-ErrorAction Stop命令。

try
{
    #run with no credentials
    Install-Module -Name $ModuleName -Repository $RepositoryName -ErrorAction stop -WarningAction SilentlyContinue
}
catch
{
    #when fails, run with proxy credentials
    Install-Module -Name $ModuleName -Repository $RepositoryName -Proxy $ProxyUrl -ProxyCredential $proxyCredential
}

对于同一try命令,您可以有多个catch{}块,以捕获不同类型的故障并执行您选择的脚本块。

答案 1 :(得分:1)

问题似乎是Pester阻止了对常用参数的过滤,因此您对'ErrorAction'等的使用会导致过滤器失败。

您可以在Pester模拟代码Mock.ps1

中的第232行看到从模拟函数中删除的参数。

此外,对此删除进行的测试是Pester自己的单元测试之一(第283行):Mock.tests.ps1

答案 2 :(得分:0)

对于处于类似情况的任何人,以下是该测试的最终版本:

function Install-RequiredModule (
    [string]$ModuleName,
    [string]$RepositoryName,
    [string]$ProxyUrl
    )
{
    try
    {
        Install-Module -Name $ModuleName -Repository $RepositoryName `
            -ErrorAction Stop

        return
    }
    catch {}

    # There was an error so try again, this time with proxy details.

    $proxyCredential = Get-Credential -Message 'Please enter credentials for proxy server'

    # No need to Silently Continue this time.  We want to see the error details.
    $Error.Clear()

    Install-Module -Name $ModuleName -Repository $RepositoryName `
        -Proxy $ProxyUrl -ProxyCredential $proxyCredential

    if ($Error.Count -gt 0)
    {
        throw $Error[0]
    }

    if (-not (Get-InstalledModule -Name $ModuleName -ErrorAction SilentlyContinue))
    {
        throw "Unknown error installing module '$ModuleName' from repository '$RepositoryName'."
    }

    Write-Output "Module '$ModuleName' successfully installed from repository '$RepositoryName'."
}

#region Tests *************************************************************************************

function ExecuteInstallRequiredModule ()
{
    Install-RequiredModule -ModuleName 'TestModule' -RepositoryName 'TestRepo' `
        -ProxyUrl 'http://myproxy'
}

Describe 'Install-RequiredModule' {

    $securePassword = "mypassword" | 
        ConvertTo-SecureString -asPlainText -Force
    $psCredential = New-Object System.Management.Automation.PSCredential  ('MyUserName', $securePassword)
    Mock Get-Credential { return $psCredential }

    Mock Install-Module { Write-Error "Some error" }
    Mock Install-Module { return $Null } -ParameterFilter { $Proxy -ne $Null -and $ProxyCredential -ne $Null }

    Mock Get-InstalledModule { return @('Non-null text') }

    It 'attempts to install module a second time, with proxy, if first attempt fails' {
        ExecuteInstallRequiredModule  
        Assert-MockCalled Install-Module -Scope It -Times 2 -Exactly
    }
}

#endregion