Skip to content

Instantly share code, notes, and snippets.

@nohwnd
Created December 7, 2018 11:49
Show Gist options
  • Select an option

  • Save nohwnd/d20dddc54632e4f65af8edc5f5e63f5a to your computer and use it in GitHub Desktop.

Select an option

Save nohwnd/d20dddc54632e4f65af8edc5f5e63f5a to your computer and use it in GitHub Desktop.
Leaking parent scope fools my tests
function A {
[CmdletBinding()]
param()
if ($null -eq $Option) { throw }
}
Describe "A" {
it "works" {
$option = "abc"
# $option leaks into the function A
# that forgot to define it's parameters
# and the test passes
A
}
}
function B {
[CmdletBinding()]
param()
if ($null -eq $local:Option) { throw }
}
Describe "B" {
it "works" {
$option = "abc"
# $option leaks into the function B
# that forgot to define it's parameters
# but we only look at local variables
# so the test fails
B
}
}
@nohwnd
Copy link
Author

nohwnd commented Dec 7, 2018

A more real-life example that caused me a lot of problems:

function A { 
    [CmdletBinding()]
    param($Option) 

    C
}

function C { 
    [CmdletBinding()]
    param() 

    if ($null -eq $Option) { throw }
}

Describe "A" {
    it "works" {
        A -Option "abc"
    }
}

@nohwnd
Copy link
Author

nohwnd commented Dec 7, 2018

$tests = {
    function A { 
        [CmdletBinding()]
        param($Option) 

        C
    }

    function C { 
        [CmdletBinding()]
        param() 

        $caseSensitive = $null -eq $Option -or $Option.CaseSensitive
        # do some more stuff
    }

    Describe "A" {
        it "works" {
            A -Option @{ CaseSensitive = $true }
        }
    }



    Describe "C" {
        it "works" {
            C
        }
    }
}


Set-StrictMode -Off 
&$tests
Set-StrictMode -Version Latest
&$tests

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