Reputation: 1630
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?
Upvotes: 4
Views: 8037
Reputation: 10075
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- e.g.
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.
Upvotes: 2
Reputation: 10821
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'
Upvotes: 0