Skip to content

Instantly share code, notes, and snippets.

@iricigor
Last active May 28, 2020 08:04
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 iricigor/7a3e61564853d66fc158adf7ce8ebda7 to your computer and use it in GitHub Desktop.
Save iricigor/7a3e61564853d66fc158adf7ce8ebda7 to your computer and use it in GitHub Desktop.
Passing values from Discovery to Run when generating tests
# original gist by Jakub
Describe "a" {
$Sources = @(
[PSCustomObject]@{
Advanced = @{
Enabled = $true
}
}
[PSCustomObject]@{
Advanced = @{
Enabled = $true
}
}
)
foreach ($Source in $Sources) {
It "not happy" -Skip {
# $Source is null, because variables are not transferred
# from discovery - this test fails
$Source.Advanced | Should -BeTrue
}
It "happy" -TestCases @{ Source = $Source } {
# $Source is defined from the test case above where
# you saved it during discovery - this test passes
$Source.Advanced | Should -BeTrue
}
}
# same as above with inline foreach
It "more happy" -TestCases ($Sources | % {@{ Source = $_ }}) {
$Source.Advanced | Should -BeIn @($true, $false)
}
$Sources2 = @(
[HashTable]@{
Advanced = @{
Enabled = $true
}
}
[HashTable]@{
Advanced = @{
Enabled = $false
}
}
)
It "more happy 2" -TestCases $Sources2 {
$Advanced | Should -BeIn @($true, $false)
}
# convert original (any) object to dictionary array
# this loses the reference to the original object, which might or might not be a problem
It "more happy 3" -TestCases ($Sources | ConvertTo-Json | ConvertFrom-Json -AsHashtable) {
$Advanced | Should -BeIn @($true, $false)
}
# or you can declare that as filter and reuse it in the code
filter AsHash {$_ | ConvertTo-Json | ConvertFrom-Json -AsHashtable}
It "more happy 4" -TestCases ($Sources | AsHash) {
$Advanced | Should -BeIn @($true, $false)
}
}
@nohwnd
Copy link

nohwnd commented May 27, 2020

  • recommended way, without foreach <- this sounds as this is the recommended way to do this above the first approach, I would phrase it as "same as above with inline foreach"
  • [Collections.IDictionary] <- this is not really needed, hashtable is okay.
  • ($Sources | ConvertTo-Json | ConvertFrom-Json -AsHashtable) <- this loses the reference to the original object, which might or might not be a problem.

@iricigor
Copy link
Author

I will update it :)

@iricigor
Copy link
Author

Updated and added also filter example at the end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment