Pester icon indicating copy to clipboard operation
Pester copied to clipboard

Pester creating mock in module scope when -ModuleName is not provided

Open efie45 opened this issue 4 years ago • 5 comments

General summary of the issue

Pester is placing mock inside of module scope even when -ModuleName isn't specified. Diagnostic output incorrectly assets that ModuleName was specified.

Describe your environment

Pester version : 5.2.2 /User/powershell/Modules/Pester/5.2.2/Pester.psm1
PowerShell version : 7.1.3
OS version : Unix 11.0.0

Step to reproduce

ExampleModule.psm1 - the function I am attempting to mock

function Invoke-MyExampleFunction {
    [Cmdletbinding()]
    param()
    Write-Error "Mock failed. Original function was called."
}

MockInjection.psm1 - I call the function in this module to insert the mock into my test file. This allows me to easily reuse my common mocks

function Invoke-MockInjection {
    Mock Invoke-MyExampleFunction {
        Write-Host 'Mocked from MockInjection module'
    }
}

MyScript.ps1

Import-Module ExampleModule

Invoke-MyExampleFunction

MyScript.Tests.ps1


$PesterPreference = New-PesterConfiguration @{
    Output = @{
        Verbosity = 'Diagnostic'
    }
}

Describe "Example Tests" {

    BeforeAll {

        Import-Module ExampleModule
        Import-Module MockInjection

        # The mock works as expected if defined inside of the BeforeAll block in the test script
        # Mock Invoke-MyExampleFunction {
        #     Write-Host "Mocked from inside BeforeAll block. Works as expected."
        # }

        # This does not work. See below diagnostic output. 
        Invoke-MockInjection

        $scriptPath = $PSCommandPath -replace '.Tests.ps1', '.ps1'
    }
    
    It "Mocks correctly" {
        { . $scriptPath } | Should -Not -Throw
    }
}

The mock works as expected when it is created inside of the test script itself. If it is injected from another module for the purposes of reusing some mock behavior, it fails. Diagnostic output makes it appear as though moduleName is being specified when it is not.

diagnostic output. Note line 4 and 5 that ModuleName was specified when it was not.

Mock: Setting up default mock for MockInjection - Invoke-MyExampleFunction. 
Mock: We are in a block, one time setup or similar. Returning mock table from test block. 
Mock: Resolving command Invoke-MyExampleFunction. 
Mock: ModuleName was specified searching for the command in module MockInjection. 
Mock: We are already running in MockInjection. Using that. 
Mock: Found the command Invoke-MyExampleFunction in a different module. 
Mock: Mock does not have a hook yet, creating a new one. 
Mock: Defined new hook with bootstrap function PesterMock_MockInjection_Invoke-MyExampleFunction_8683fddf-5380-43a6-a489-ab324f65a01b and aliases Invoke-MyExampleFunction, ExampleModule\Invoke-MyExampleFunction. 
Mock: Adding a new default behavior to MockInjection - Invoke-MyExampleFunction. 

efie45 avatar Jul 08 '21 15:07 efie45

This changed in the 5.2.0 and it is correct. You are running in the scope of the module, Mock sees that and specifies the ModuleName for you. This is to keep it work the same with -ModuleName abc as with InModuleScope { Mock <no ModuleName here> }.

You would have to invoke the code in the caller session state to make this work.

nohwnd avatar Jul 08 '21 15:07 nohwnd

This makes it very difficult to reuse mocks. Would there be any consideration to have an explicit switch or value for ModuleName to specify that you do not want a moduleName provided? For example, passing in -Modulename $false explicitly will avoid adding a module context for the Mock like below:

in Pester.psm1 line 12994 in 5.2.2

    # use the caller module name as ModuleName, so calling the mock in InModuleScope uses the ModuleName as target module
    if (-not $PSBoundParameters.ContainsKey('ModuleName') -and $null -ne $SessionState.Module -and $ModuleName -ne 'False' ) {
        $ModuleName = $SessionState.Module.Name
    }

efie45 avatar Jul 08 '21 15:07 efie45

I was wrong. This did not change in 5.2.0 at least not the part that defines in which session state the mock will run. Did this started to happen after an upgrade, or did you just try to implement this for the first time?

Because what happens is that the mock is inserted into the module MockInjection, and won't be resolvable from your script. This happens even if we don't force it to be defined in a module explicitly. You can try running this in 5.1.0, or you can specify -ModuleName $null explicitly (an edge case we don't test for). It will say it is defining the mock in the script but in reality it is defining it in the current session state, which is the module.

To achieve this you would have to pass along the caller session state to Mock, and tell it to define the mock there. This is what Mock normally does for you, and the API that takes the session state is not external.

https://github.com/pester/Pester/blob/main/src/functions/Pester.SessionState.Mock.ps1#L241

nohwnd avatar Jul 08 '21 16:07 nohwnd

Isn't it easier to just rename to MockInjection.ps1 and dot-sourcing?

BeforeAll {
    Import-Module ExampleModule
    . MockInjection.ps1

    Invoke-MockInjection
}

Any reason you need MockInjection as a module?

fflaten avatar Jul 08 '21 17:07 fflaten

@fflaten This is a simple example but I have a bunch of mocks that change based on the situation. Right now they all resides among some other test utility functions inside of a module that rely on module scoped variables to inject the correct mocks.

Dot sourcing is a good idea though. I could probably refactor without too much hassle and import those functions that way.

Also, I don't quite understand how I would pass the session state along if it's not parameterized as $PSCmdlet.SessionState.Module is empty when the Mock function is called. Is there a way to override the session state from the calling function?

efie45 avatar Jul 08 '21 17:07 efie45