Skip to content

Commit

Permalink
feat: Update Mock-EnvironmentVariable function
Browse files Browse the repository at this point in the history
Add the posibility to specify targets to mock and refactor the
implementation to a more enjoyable state.
  • Loading branch information
petru committed Jul 27, 2022
1 parent ffc0af6 commit c5c9f9e
Show file tree
Hide file tree
Showing 2 changed files with 267 additions and 149 deletions.
89 changes: 52 additions & 37 deletions src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1
Original file line number Diff line number Diff line change
@@ -1,53 +1,68 @@
function Restore {
param (
[string]
$Variable,

[EnvironmentVariableTarget[]]
$Targets,

[hashtable]
$Backup
)
foreach ($target in $targets) {
[Environment]::SetEnvironmentVariable($Variable, $Backup[$target], $target)
}
}

function Set-Values {
param (
[string]
$Variable,

[EnvironmentVariableTarget[]]
$Targets,

[string]
$value
)
$Backup = @{}

foreach ($target in $Targets) {
$OriginalValue = [Environment]::GetEnvironmentVariable($Variable, $target)
$Backup.Add($target, $OriginalValue)
if ($Value) {
[Environment]::SetEnvironmentVariable($Variable, $Value, $target)
}
}

return $Backup
}


function Mock-EnvironmentVariable {
param (
[parameter(Mandatory = $true, Position = 0)]
[parameter(Mandatory = $true)]
[string]
$Variable,

[Parameter(Mandatory = $true)]
[ScriptBlock]
$Fixture,

[Parameter(Mandatory = $false)]
[string]
$Value,

[Parameter(Mandatory = $false)]
[System.EnvironmentVariableTarget]
$Targets = [EnvironmentVariableTarget]::Process,

[Parameter(Mandatory = $true, Position = 1)]
[ScriptBlock]
$Fixture

[EnvironmentVariableTarget[]]
$Targets = @([EnvironmentVariableTarget]::Process)
)
$EnvironmentVariable = "env:${Variable}"

if (Test-Path -Path $EnvironmentVariable) {
$OriginalValue = (Get-ChildItem -Path $EnvironmentVariable).Value
if ($value) {
Set-Item -Path $EnvironmentVariable -Value $Value
}
}
else {
New-Item -Path $EnvironmentVariable -Value $Value | Out-Null
}
try {
Invoke-Command -ScriptBlock $Fixture
}

catch {
throw $_
}
$Backup = Set-Values -Variable $Variable -Targets $Targets -value $Value

finally {
if ($OriginalValue) {
Set-Item -Path $EnvironmentVariable -Value $OriginalValue
}
elseif (Test-Path -Path $EnvironmentVariable) {
Remove-Item `
-Path $EnvironmentVariable `
-Recurse `
-Force `
-ErrorAction Stop
}
}
try { Invoke-Command -ScriptBlock $Fixture }
catch { throw $_ }
finally { Restore -Variable $Variable -Targets $Targets -Backup $Backup }

<#
.PARAMETER Variable
Expand Down
Loading

0 comments on commit c5c9f9e

Please sign in to comment.