简体   繁体   中英

Test for `pester` version using `pester`

I have a set of pester tests for a PowerShell module which use the v4.0+ should operator -FileContentMatch . When these tests are run on a machine with an earlier v3.x version of pester , there is a wave of error messages, none of which exactly point out the problem.

I'd like to write a simple pester test to check for a minimum version and print an explanation / fix for the user / tester.

The extra complication is that pester can be run directly as a script without being installed as a module on the machine.

I've looked at using $(Get-Module -ListAvailable -name "Pester").version to pull out the pester version, but it only sees the PowerShell-"installed" module, not the currently executing version, which, as noted, could be different.

Some signal passed from pester would be fine, but I don't see that pester provides any meta-information to the test scripts (ie, a version environment variable).

Any thoughts on a solution?

Read the ModuleVersion from the module manifest .

You can read the major version of the manifest like so:

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

The code you want for checking the version of the currently loaded pester module is something like this:

$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)'";
}

but choosing where to run it is slightly more tricky - if you can run it inside a pester test, that would give you the version of pester currently running the tests- eg

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

but, that will still run your main tests regardless of whether the right version is loaded so you could get a lot of background noise if the wrong version is loaded.

You could run the tests above as a pre-flight check for your main tests though - call Invoke-Pester with the -PassThru switch to check the result and only call your main tests if the pre-flight tests pass.

Or just load the pester module yourself from a known location and then call the above code block to validate the version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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