Pester icon indicating copy to clipboard operation
Pester copied to clipboard

v5: InModuleScope behavior

Open nohwnd opened this issue 7 years ago • 5 comments

How should InModuleScope behave during discovery? We need the module loaded and available so the discovery can run in it's scope. This also allows all the internal variables to be resolved, but slightly complicates the thinking about the Import-Module because you would place it outside of BeforeAll (otherwise it would be imported after discovery which would result in InModuleScope failing because it cannot find the module.

Possible InModuleScope could be replaced by moving the parameter on It/Context/Describe and running the code in the module, which would make for a better usability imho. But would require a lot of changes to tests and people load modules on top anyway (or just load them once).

Another option is to add another keyword like BeforeDiscovery, which would be more idiomatic.

nohwnd avatar Oct 31 '19 09:10 nohwnd

My own testing shows that InModuleScope is a requirement in some cases, let me see if i can explain. A function in a module X is being tested, the interesting part looks like this:

function Get-Something {
  [CmdletBinding()]
  Param(
    [string]$environment = $DefaultEnvironment
  )

  if ([string]::IsNullOrEmpty($environment)) { 
    throw "Environment is not set. Default environment can be set with `$DefaultEnvironment."
  }
.
.

The following test fails and triggers the Throw in the above test method:

Describe "Get-Something" {
    Context "Check environment parameter" {
        It "Throws exception when default environment is set and no data is found" {
            {
                $DefaultEnvironment = "dummy"
                Get-Something
            } | Should -Not -Throw
        }
}

As i said the above code fails when calling Get-Something as $DefaultEnvironment is not set. This test works with Pester v4 and to make it work in v5 you have to enclose the Describe block in a InModuleScope block with the module name X as argument.

Is this breaking change by design and is it mentioned anywhere if so ?

BoSorensen avatar Mar 25 '20 15:03 BoSorensen

Seems to be working fine in both versions, and as I would expect. If Get-Something is coming from a module, the $DefaultEnvironment variable you define in the test is in a different session state, so the default value in the function will NOT resolve to it. Instead it will resolve to that variable inside of the module.

# file Something.Tests.ps1
Get-Module Something | Remove-Module 

New-Module -Name Something -ScriptBlock { 
    function Get-Something {
        [CmdletBinding()]
        Param(
          [string]$environment = $DefaultEnvironment
        )
      
        if ([string]::IsNullOrEmpty($environment)) { 
          throw "Environment is not set. Default environment can be set with `$DefaultEnvironment."
        }
    }
}

Describe "Get-Something" {
    Context "Check environment parameter" {
        It "Throws exception when default environment is set and no data is found" {
            $DefaultEnvironment = "dummy"
            Get-Something
        }
    }
}
Get-Module Pester | Remove-Module 
Import-Module Pester -MaximumVersion 4.99.99
Invoke-Pester C:\Users\jajares\Desktop\Something.Tests.ps1

Get-Module Pester | Remove-Module 
Import-Module Pester -MinimumVersion 5.0.0
Invoke-Pester C:\Users\jajares\Desktop\Something.Tests.ps1 | Out-Null
Pester v4.9.0
Executing all tests in 'C:\Users\jajares\Desktop\Something.Tests.ps1'

Executing script C:\Users\jajares\Desktop\Something.Tests.ps1

  Describing Get-Something

    Context Check environment parameter
      [-] Throws exception when default environment is set and no data is found 1ms
        RuntimeException: Environment is not set. Default environment can be set with $DefaultEnvironment.
        at Get-Something, C:\Users\jajares\Desktop\Something.Tests.ps1: line 11
        at <ScriptBlock>, C:\Users\jajares\Desktop\Something.Tests.ps1: line 20
Tests completed in 371ms
Tests Passed: 0, Failed: 1, Skipped: 0, Pending: 0, Inconclusive: 0 

Starting test discovery in 1 files.
Discovering tests in C:\Users\jajares\Desktop\Something.Tests.ps1.
Found 1 tests. 24ms
Test discovery finished. 63ms


Running tests from 'C:\Users\jajares\Desktop\Something.Tests.ps1'
Describing Get-Something
 Context Check environment parameter
   [-] Throws exception when default environment is set and no data is found 3ms (1ms|2ms)
    RuntimeException: Environment is not set. Default environment can be set with $DefaultEnvironment.
    at Get-Something, C:\Users\jajares\Desktop\Something.Tests.ps1:11
    at <ScriptBlock>, C:\Users\jajares\Desktop\Something.Tests.ps1:20
Tests completed in 361ms
Tests Passed: 0, Failed: 1, Skipped: 0, Total: 1, NotRun: 0

How are you importing the module? Looks like it is loaded into your script session state in Pester v4.

nohwnd avatar Mar 25 '20 15:03 nohwnd

Great example which i can confirm fails both in v4 and v5. I examined my case in more detail and this is how it will fail in v5 but work in v4. The file Something.ps1 is usually dot-sourced from the module psm1 file and then exported with Export-ModuleMember.

### Save as Something.ps1
    function Get-Something {
        [CmdletBinding()]
        Param(
          [string]$environment = $DefaultEnvironment
        )
      
        if ([string]::IsNullOrEmpty($environment)) { 
          throw "Environment is not set. Default environment can be set with `$DefaultEnvironment."
        }
    }

### Save as Something.Tests.ps1

Get-Module Something | Remove-Module 
. $PSCommandPath.Replace(".Tests.", ".")

Describe "Get-Something" {
    Context "Check environment parameter" {
        It "Throws exception when default environment is set and no data is found" {
            $DefaultEnvironment = "dummy"
            Get-Something
        }
    }
}

That is how tests are usually constructed and has worked well in both Pester v3 and v4.

BoSorensen avatar Mar 25 '20 16:03 BoSorensen

Ah okay, so it had nothing to do with a module. :)

I see it fail in v5, if it does not run in interactive mode.

In interactive mode we dot-source (import) the file which gets the function into the top level scope and it will be available when Pester discovers, and invokes the test. You can then go to console and run the Get-Something function, or go to a different file and still have that function available. In a way this makes the tests non-repeatable.

In v5 the recommended way is to put the initialization into BeforeAll block. This has two advantages:

  • it allows pester to control when the code will run, so it only executes it when appropriate and necessary
  • it prevents it from polluting the global scope in interactive use

BeforeAll {
    . $PSCommandPath.Replace(".Tests.", ".")
}
Describe "Get-Something" {
    Context "Check environment parameter" {
        It "Throws exception when default environment is set and no data is found" {
            $DefaultEnvironment = "dummy"
            Get-Something
        }
    }
}
Starting test discovery in 1 files.
Discovering tests in C:\Users\jajares\Desktop\something\Something.Tests.ps1.
Found 1 tests. 209ms
Test discovery finished. 474ms


Running tests from 'C:\Users\jajares\Desktop\something\Something.Tests.ps1'
Describing Get-Something
 Context Check environment parameter
   [+] Throws exception when default environment is set and no data is found 141ms (76ms|65ms)
Tests completed in 1.41s
Tests Passed: 1, Failed: 0, Skipped: 0, Total: 1, NotRun: 0


PS C:\Users\jajares> Get-Something

Get-Something: The term 'Get-Something' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

nohwnd avatar Mar 25 '20 16:03 nohwnd

InModuleScope gets to live but it is not encouraged to be used, there are better patterns, like -methodName and default parameters.

nohwnd avatar Apr 04 '20 17:04 nohwnd