Pester icon indicating copy to clipboard operation
Pester copied to clipboard

TestDrive Cleaning Early with Nested Invoke-Pester

Open wethreetrees opened this issue 3 years ago • 1 comments

General summary of the issue

When Invoke-Pester is run inside of an existing Pester context, the "parent" TestDrive appears to be cleaned up early.

Hopefully I am understanding the TestDrive docs correctly and this is not intended behavior.

Describe your environment

Pester version     : 5.3.1
PowerShell version : 7.2.1
OS version         : Microsoft Windows NT 10.0.19042.0

Steps to reproduce

Describe "Entry point" {

    BeforeAll {
        $tempFilePath = Join-Path -Path $TestDrive -ChildPath testing.txt
        "Hello" | Set-Content -Path $tempFilePath
    }

    It "Should see the file we created" {
        Get-Item -Path $tempFilePath | Should -Not -BeNullOrEmpty
        Get-Content -Path $tempFilePath | Should -Be "Hello"
    }

    It "Should run Invoke-Pester without cleaning up TestDrive" {
        $testScript = {
            param (
                $Path
            )

            Describe "Nested" {
                It "Should still see the file we created in the entry tests" {
                    Get-Item -Path $Path | Should -Not -BeNullOrEmpty
                    Get-Content -Path $Path | Should -Be "Hello"
                }
            }
        }

        $container = New-PesterContainer -ScriptBlock $testScript -Data @{ Path = $tempFilePath }
        $result = Invoke-Pester -Container $container -PassThru
        $result.Result | Should -Be 'Passed'
    }

    It "Should still have the file here too" {
        Get-Item -Path $tempFilePath | Should -Not -BeNullOrEmpty
        Get-Content -Path $tempFilePath | Should -Be "Hello"
    }

}

Expected Behavior

The TestDrive from the first Describe block should persist until the block is exited, making testing.txt available until we exit the Describe "Entry point".

Current Behavior

The Describe "Entry point" TestDrive is cleaned up when we enter the nested Invoke-Pester context.

wethreetrees avatar Mar 21 '22 14:03 wethreetrees

You understand it correctly. But when you Invoke-Pester the first thing that happens is that test drive is cleaned up if it is still defined. PSDrive is global, so when we re-map test drive to new directory we clean up everything that was there to not leak test files.

https://github.com/pester/Pester/blob/84e14c836707c21ba442b6a7312f46150ce9b4ea/src/functions/TestDrive.ps1#L5-L7

This might be also worked around in some clever way. But right now this is one of the limitations of running Pester in Pester. TestDrive works well only in the inner Pester instance.

nohwnd avatar Apr 12 '22 18:04 nohwnd

A fix should also be applied to TestRegistry

fflaten avatar Apr 12 '23 21:04 fflaten