Pester icon indicating copy to clipboard operation
Pester copied to clipboard

Pester test fails with 'Cannot find drive. A drive with the name 'TestRegistry' does not exist.'

Open dbafromthecold opened this issue 7 years ago • 17 comments

1. General summary of the issue

After upgrading Pester to v4.9.0 our tests have been failing with the error:- 'Cannot find drive. A drive with the name 'TestRegistry' does not exist'

We're currently on v4.3.1 which is not affected. I've had a look at previous issues raised and this seems to be similar to https://github.com/pester/Pester/issues/1216

We do run our tests in parallel through Jenkins. The tests themselves are pretty simple, a script retrieves a value from a SQL instance and compares that value to what we expect it to be.

2. Describe Your Environment

Pester version : 4.9.0 C:\Program Files\WindowsPowerShell\Modules\Pester\4.9.0\Pester.psd1 PowerShell version : 5.1.14409.1018 OS version : Microsoft Windows NT 6.3.9600.0

3. Expected Behavior

Pester test should run as expected.

4.Current Behavior

Our tests fail intermittently with the error: -

PesterError

5. Possible Solution

Unsure I'm afraid. Does seem to be an issue with running the tests in parallel (as noted in the previous issue).

6. Context

We use Pester to check the configuration of our SQL instances, these failures are giving us false negatives.

dbafromthecold avatar Sep 09 '19 10:09 dbafromthecold

Are you doing something special or just running some tests on normally configured Windows under a normal user? There is similar issue happening when the user does not have permission to read / write registry.

nohwnd avatar Sep 10 '19 07:09 nohwnd

We're running on a Windows box as the Jenkins user (which is an admin on the server).

The tests are called in runspaces by a powershell function and the results piped to Jenkins.

dbafromthecold avatar Sep 10 '19 08:09 dbafromthecold

@dbafromthecold - I've got a bit of spare time so I can take a look into this, but could you give a code sample that shows how you're invoking the parallelism so I can try to reproduce the error?

mikeclayton avatar Sep 13 '19 10:09 mikeclayton

Apologies for the late response. Here's an example Pester test that we run: -

Describe "$($Database.name) owner"{

    Context "DbConfig"{
        It "Database owner should be $ConfigValue"{ 
            $DbOwner = $Database.owner        
            $DbOwner | Should be $ConfigValue
        }
    }
}

$Database and $ConfigValue are passed in by another function running: -

param (
    $InputObject,
    )
	
    # retrieve user databases in Sql Instance
    $Query = "SELECT d.name, p.name AS [owner] 
	FROM sys.databases d
	INNER JOIN sys.server_principals p ON d.owner_sid = p.sid"
	
    $invokeSqlCmd2Splat = @{
		ServerInstance = $InputObject
        Query = $Query
        ErrorAction = 'Stop'
    }
    $Databases = Invoke-SqlCmd2 @invokeSqlCmd2Splat
    
    # create PesterTests array to store Pester results
    $PesterTests = @()

    # loop through each database in Sql Instance
    foreach($Database in $Databases){

        # run Pester test
        $ConfigTest = Invoke-Pester -Script @{Path = "C:\PesterTests\Test-DbConfig.ps1"; `
            Parameters = @{SqlServer = $InputObject; `
            Database = $Database; `
            ConfigValue = "sa";}} `
            -TestName '*owner*' `
            -PassThru `
	    -Show None

        # append results to PesterTests array
        $PesterTests += $ConfigTest
    }

We have a couple of extra lines in the code at the end to generate an XML file so that Jenkins can read the results of the Pester tests.

And then that script is called by: -

    $InputObjects = "List of servers passed in from the Jenkins test"
    $MaxThreads = $env:NUMBER_OF_PROCESSORS 

    $ScriptBlock = Get-Command "C:\ PowershellScripts\Script.ps1" | Select-Object -ExpandProperty ScriptBlock 

    # create a runspace pool with minrunspaces of 1 and maxrunspaces of $MaxThreads
    $RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, $MaxThreads)

    # set runspace options
    $RunspacePool.ApartmentState = "STA"
    $RunspacePool.ThreadOptions = "ReuseThread"

    # open pool
    $RunspacePool.Open()

    # create empty array for runspaces
    $Runspaces = @()

    foreach($InputObject in $InputObjects){
        # create powershell object and the script defined above with an argument
        $Runspace = [powershell]::Create().AddScript($ScriptBlock).AddArgument($InputObject)

        # add the runspace definition to the pool
        $Runspace.RunspacePool = $RunspacePool

        # start the runspace using PSObject to store information
        $Runspaces += New-Object PSObject -Property @{Pipe = $Runspace; Result = $Runspace.BeginInvoke()}
    }

    # wait for runspaces to complete
    While ($Runspaces.Result.IsCompleted -contains $false){}

    # capture results
    $Results = @()
    ForEach ($Runspace in $Runspaces){   
        $Results += $Runspace.Pipe.EndInvoke($Runspace.Result)
    }

    # close runspace pool
    $RunspacePool.Close() 
    $RunspacePool.Dispose()

    return $Results

dbafromthecold avatar Sep 18 '19 09:09 dbafromthecold

@dbafromthecold - I'm not yet able to reproduce your issue, but I've got a couple of observations from what I've done so far...

Console Logging

If you change your main code to pass the parent host object into the runspaces you can use write-host in your script block to output debugging info to the main console window...

# create a runspace pool with minrunspaces of 1 and maxrunspaces of $MaxThreads
$initialSessionState = [InitialSessionState]::CreateDefault();
$runspacePool = [RunspaceFactory]::CreateRunspacePool(1, $MaxThreads, $initialSessionState, $host);

Pester Version

I don't think the script block you run in the runspace shares the modules that are loaded in the main context, so I'm not totally sure what version of Pester it's loading on your system. You could make sure by adding something like this as a diagnostic step now that write-host works in your script block:

param (
    $InputObject,
    )
    $command = Get-Command "Invoke-Pester" -ListImported;
    write-host ($command | out-string);
    ... etc ...

This will output something like this when the script runs:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Invoke-Pester                                      4.9.0      pester

or maybe an unexpected back-level version if it's discovering it with auto-loading modules.

Import Module

If it's not finding the correct version of pester you can add an Import-Module command in your script block to force it to load...

param (
    $InputObject,
    )
    Import-Module -Name ".\Pester-4.9.0\pester.psd1" -ErrorAction "Stop";
   ... etc ...

If you could confirm what output you get if you make the above changes I can take another look.

Cheers,

M

mikeclayton avatar Sep 18 '19 22:09 mikeclayton

For reference, these are the test files I'm using...

Test-DbConfig.ps1

Describe "my describe" {
    Context "my context"{
        It "my it"{ 
            $true | Should Be $true
        }
    }
}

Script.ps1

param
(
    $ServerName
)

write-host "entering script block";

$databases = @( "database1", "database2", "database3" );

# create PesterTests array to store Pester results
$PesterTests = @()

foreach( $database in $databases )
{
    write-host "database = '$ServerName.$database'";
    # run Pester test
    $results = $null;
try
{
    Import-Module -Name ".\Pester-4.9.0\pester.psd1" -ErrorAction "Stop";
    $command = Get-Command "Invoke-Pester" -ListImported;
    write-host ($command | out-string);
    $results = Invoke-Pester `
        -Script @{
            Path = ".\Test-DbConfig.ps1"; `
            Parameters = @{
                SqlServer = $ServerName
                Database = $database
                ConfigValue = "sa"
            }
        } `
        -TestName "*owner*" `
        -PassThru `
        -Show "None";
}
catch
{
    $ex = $_.psbase.Exception;
    write-host  $ex.ToString();
    throw
}

    write-host "results = ";
    write-host ($results | fl * | out-string);
    write-host "done";

    # append results to PesterTests array
    $pesterTests += $results;

}

wrapper.ps1

$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

$InputObjects = @( "server1", "server2", "server3", "server4", "server5", "server6" );
$MaxThreads = $env:NUMBER_OF_PROCESSORS 

$scriptBlock = Get-Command ".\Script.ps1" | Select-Object -ExpandProperty ScriptBlock 
#write-host "script block = ";
#write-host $scriptBlock.GetType().FullName;
#write-host $scriptBlock;

# create a runspace pool with minrunspaces of 1 and maxrunspaces of $MaxThreads
$initialSessionState = [InitialSessionState]::CreateDefault();
$runspacePool = [RunspaceFactory]::CreateRunspacePool(1, $MaxThreads, $initialSessionState, $host);

# set runspace options
$runspacePool.ApartmentState = "STA"
$runspacePool.ThreadOptions = "ReuseThread"

# open pool
$runspacePool.Open()

# create empty array for runspaces
$runspaces = @()

foreach( $InputObject in $InputObjects )
{
    write-host "server = '$InputObject'";

    # create powershell object and the script defined above with an argument
    $powershell = [PowerShell]::Create().AddScript($scriptBlock).AddArgument($InputObject);

    # add the runspace definition to the pool
    $powershell.RunspacePool = $runspacePool;

    # start the runspace using PSObject to store information
    $runspaces += New-Object PSObject -Property @{
        Pipe = $powershell
        Result = $powershell.BeginInvoke()
    };

}

# wait for runspaces to complete
while( $runspaces.Result.IsCompleted -contains $false )
{
}

# capture results
write-host "processing results:";
$results = @();
foreach ($runspace in $runspaces)
{
    write-host ($runspace | fl * | out-string);
    $result = $runspace.Pipe.EndInvoke($runspace.Result);
    write-host $result;
    $results += $result;
}

# close runspace pool
$RunspacePool.Close() 
$RunspacePool.Dispose()

return $Results

and then calling it by running:

c:\issue-1360>powershell .\wrapper.ps1

mikeclayton avatar Sep 18 '19 22:09 mikeclayton

Thank you for coming back to me. I ran the scripts above in Jenkins. Here's the output: -

JenkinsOutput

I made sure that the only version of Pester on the server was v4.9.0 and ran one of our tests. It immediately failed with: - JenkinsOutput2

Stack trace at the bottom shows it's using v4.9.0

dbafromthecold avatar Sep 19 '19 09:09 dbafromthecold

@dbafromthecold - I'm still looking at this, but currently unable to reproduce locally. I've tried to reduce the amount of code in the example, but I hit what I think is a different bug in #1370.

As a test, could you try setting your $MaxThread to 1 to see if that shows the same issue? It will help isolate whether it's a multi-runspace race condition or something else...

Thanks,

Mike

mikeclayton avatar Sep 20 '19 10:09 mikeclayton

Been running our tests today with $MaxThread set to 1, no issues whatsoever.

Switched back to setting the MaxThreads to the number of processors on the server (4 or 6 depending on which node the Jenkins job executes on) and immediately got the error.

dbafromthecold avatar Sep 20 '19 14:09 dbafromthecold

How is that running the tests? There was a similar error like that where I was removing the base Registry Key by New-Item -Force which does a Delete and then Create. https://github.com/pester/Pester/issues/1181 so probably there is a similar bug as well. I don't unfortunately have access to a Windows machine right now :/

nohwnd avatar Sep 21 '19 10:09 nohwnd

The ScriptBlock passed into the runspaces executes the tests. Running with max threads set to 1 prevents the error from being raised but any tests run in parallel will error out.

dbafromthecold avatar Sep 24 '19 13:09 dbafromthecold

@nohwnd It looks like similar issue (#1181 )

I was able to reproduce it by having two PowerShell process in parallel. In fact I used the same reproducer from #1181

Get-Module Pester | Remove-Module
Import-Module C:\Projects\pester_main\Pester.psd1

while ($true) {
    try {
    Describe "A" { It "b" {}}
    } catch { 
    $global:err = $_ 
    throw $_
    }
}

I have Pester v4.9.0 installed on my machine

jegannathanmaniganadan avatar Oct 22 '19 22:10 jegannathanmaniganadan

Just wanted to chime in and say that this bug is definitely still present. Every third or fourth test run on our CI servers (which use Pester in parallel processes) fails due to it.

mattpwhite avatar Jan 28 '20 21:01 mattpwhite

I know the original bug was that I used New-Item -Force which on the Registry provider deletes the key and then recreates it (while on File it will just see that the folder exists and keep it). Could someone revisit the code to see if there was a regression somewhere?

I'd love to release the fix today/tomorrow with 4.10 if I finally get my certificate.

nohwnd avatar Jan 29 '20 10:01 nohwnd

I could not reproduce the bug with the above repro. But instead it got stuck in a state where each process had its own guid which was reused. Once I deleted those keys from registry it reported the error and then started working normally again. This is most likely an error in our initialization logic which probably thinks that it is inside of a describe if there was a cancelled test run before (so all the describes generated by the repro are thinking they are not top-level describes, and so they don’t setup the test registry, but just reuse the existing one). The weird thing is that I am re-importing the module on every run, so it must be saved outside of the module state.

nohwnd avatar Jan 31 '20 05:01 nohwnd

My guess is that we somehow look at the parent Pester key and think that pester is already running.

nohwnd avatar Jan 31 '20 05:01 nohwnd

Found it, the reported error was coming from clean-testregistry where I am trying to grab the test registry path. But because New-Item will occasionally throw IOException, "no more data available" when running in parallel, the testregistry drive is not setup yet. I fixed it by catching the exception and re-trying the operation. single re-try seems to work fine when running in 4 parallel processes, so hopefully this will work, otherwise I need to up the number of re-tries.

Another bug was present which caused the test registry (and test drive) to re-use the same path for all described when a previous run was aborted (as described above, testdrives were thinking that we are inside of another describe, and were not setting up that drive). I fixed that by cleaning up on invocation, just like I do with mocks.

nohwnd avatar Feb 01 '20 07:02 nohwnd