Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always return to original CWD after running Pester #2189

Merged
merged 3 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Main.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,9 @@ function Invoke-Pester {
$script:mockTable = @{}
# todo: move mock cleanup to BeforeAllBlockContainer when there is any
Remove-MockFunctionsAndAliases -SessionState $PSCmdlet.SessionState

# store CWD so we can revert any changes at the end
$initialPWD = $pwd.Path
}

end {
Expand Down Expand Up @@ -1214,6 +1217,9 @@ function Invoke-Pester {
}
}

# go back to original CWD
if ($null -ne $initialPWD) { & $SafeCommands['Set-Location'] -Path $initialPWD }

# exit with exit code if we fail and even if we succeed, otherwise we could inherit
# exit code of some other app end exit with it's exit code instead with ours
$failedCount = $run.FailedCount + $run.FailedBlocksCount + $run.FailedContainersCount
Expand Down
19 changes: 19 additions & 0 deletions tst/Pester.RSpec.ts.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2427,4 +2427,23 @@ i -PassThru:$PassThru {
$r.Containers[1].Blocks[0].Tests[0].ErrorRecord.TargetObject.Message | Verify-Equal "Skipped due to previous failure at 'a.b' and Run.SkipRemainingOnFailure set to 'Run'"
}
}

b 'Changes to CWD are reverted on exit' {
t 'PWD is equal before and after running Invoke-Pester' {
$beforePWD = $pwd.Path

$sb = {
Describe 'd' {
It 'i' {
Set-Location '../'
1 | Should -Be 1
}
}
}

$container = New-PesterContainer -ScriptBlock $sb
Invoke-Pester -Container $container -Output None
$pwd.Path | Verify-Equal $beforePWD
}
}
}