Skip to content

Instantly share code, notes, and snippets.

@nohwnd
Last active April 16, 2021 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nohwnd/86d65f48c20849482573a4d64e004894 to your computer and use it in GitHub Desktop.
Save nohwnd/86d65f48c20849482573a4d64e004894 to your computer and use it in GitHub Desktop.
Bunching expensive setup in Pester
## Run only discovery, select tests that need really expensive setup that takes
# long time to be present in the target system. E.g. 30 minutes per file to be updated
# in a remote resource. And run just the discovery, setup all tests that would run across
# all files (we use only one here but it does not matter).
# And then run the tests, communicating back which resources were created so we get failures
# in their respective tests.
Import-Module Pester -RequiredVersion 5.2.0 -Force
$configuration = [PesterConfiguration]::Default
$configuration.Run.Container = New-PesterContainer -Path $PSScriptRoot
$configuration.Run.SkipRun = $true
$configuration.Run.PassThru = $true
$configuration.Filter.ExcludeTag = "Excluded"
$configuration.Output.Verbosity = "Detailed"
# run only discovery because $configuration.Run.SkipRun = $true
$discovered = Invoke-Pester -Configuration $configuration
# get tests that need setup and are specifying the required group name in their data
# you should see two, the last one is excluded by filter
$testsThatNeedSetup = $discovered.Tests |
Where-Object { $_.ShouldRun -and $_.Data -is [Hashtable] -and $_.Data.ContainsKey("RequiredGroupName") }
# setup groups
# wait till the are done, and collect them in array as they come
$groups = "Group1", "Group12"
# enable the run again
$configuration.Run.SkipRun = $false
$configuration.Run.Container.Value[0].Data = @{ Groups = $groups }
$result = Invoke-Pester -Configuration $configuration
# don't make this mandatory, you will provide it only when you run, but not for the
# discovery only part
param ($Groups)
Describe "A" {
BeforeEach {
# in your helper module probably
function Assert-GroupExist ($Group, $RequiredGroupName) {
# whatever you need to do to ensure you have it created either by querying the resource or
# by loooking into the hashtable your provided
if ($RequiredGroupName -notin $Group) {
throw "Group $RequiredGroupName is required but it was not created."
}
}
# $RequiredGroupName comes from Foreach on the test
Assert-GroupExist -Group $Groups -RequiredGroupName $RequiredGroupName
}
It "Tests <RequiredGroupName>" -ForEach @{ RequiredGroupName = "Group1" } {
}
It "Tests <RequiredGroupName>" -ForEach @{ RequiredGroupName = "Group2" } {
}
It "Tests <RequiredGroupName>" -ForEach @{ RequiredGroupName = "Group3" } -Tag "Excluded" {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment