使用 `pester` 测试 `pester` 版本

Test for `pester` version using `pester`

我对使用 v4.0+ should 运算符 -FileContentMatch 的 PowerShell 模块进行了一组 pester 测试。当这些测试 运行 在具有早期 v3.x 版本 pester 的机器上进行时,会出现一波错误消息,其中 none 准确指出了问题。

我想编写一个简单的 pester 测试来检查最低版本并为用户/测试人员打印解释/修复。

更复杂的是 pester 可以直接 运行 作为脚本,而无需作为模块安装在机器上。

我看过使用 $(Get-Module -ListAvailable -name "Pester").version 来提取 pester 版本,但它只能看到 PowerShell-"installed" 模块,而不是当前正在执行的版本,因为注意到了,可能会有所不同。

pester 传递的一些信号会很好,但我没有看到 pester 为测试脚本提供任何元信息(即版本环境变量)。

有什么解决方案吗?

module manifest 读取 ModuleVersion

您可以像这样阅读清单的主要版本:

$PesterMajorVersion=(Get-Content path\to\Pester\Pester.psd1|sls ModuleVersion).Line -replace ".*'([\d])+\..*'",''

用于检查当前加载的 pester 模块版本的代码如下所示:

$pesterModules = @( Get-Module -Name "Pester" -ErrorAction "SilentlyContinue" );
if( ($null -eq $pesterModules) -or ($pesterModules.Length -eq 0) )
{
    throw "no pester module loaded!";
}
if( $pesterModules.Length -gt 1 )
{
    throw "multiple pester modules loaded!";
}
if( $pesterModules[0].Version -ne ([version] "4.8.0") )
{
    throw "unsupported pester version '$($pesterModules[0].Version)'";
}

但是选择 运行 的位置稍微有点棘手 - 如果你可以 运行 它在 pester 测试中,那会给你当前 运行ning 的 pester 版本测试-例如

Describe "check test suite version" {
    Context "pester version" {
        It "should be correct version" {
            ... version check code here ...
        }
    }
}

但是,无论是否加载了正确的版本,这仍然 运行 您的主要测试,因此如果加载了错误的版本,您可能会听到很多背景噪音。

可以 运行 以上测试作为主要测试的飞行前检查 - 使用 -PassThru 调用 Invoke-Pester切换以检查结果,只有在飞行前测试通过时才调用主要测试。

或者自己从已知位置加载 pester 模块,然后调用上面的代码块来验证版本。