Skip to content

Commit

Permalink
Merge pull request #432 from dlwyatt/MockModuleQualifiedCalls
Browse files Browse the repository at this point in the history
Mock module qualified calls
  • Loading branch information
dlwyatt committed Dec 8, 2015
2 parents 292bca1 + 344aee6 commit 4a3bf16
Show file tree
Hide file tree
Showing 19 changed files with 325 additions and 188 deletions.
8 changes: 4 additions & 4 deletions Functions/Assertions/Be.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ function Get-CompareStringMessage {

$expectedLength = $expected.Length
$actualLength = $actual.Length
$maxLength = $expectedLength,$actualLength | Sort -Descending | select -First 1
$maxLength = $expectedLength,$actualLength | & $SafeCommands['Sort-Object'] -Descending | & $SafeCommands['Select-Object'] -First 1

$differenceIndex = $null
for ($i = 0; $i -lt $maxLength -and ($null -eq $differenceIndex); ++$i){
Expand Down Expand Up @@ -94,9 +94,9 @@ function Get-CompareStringMessage {
{
#count all the special characters before the difference
$specialCharacterOffset = ($actual[0..($differenceIndex-1)] |
Where {"`n","`r","`t","`b","`0" -contains $_} |
Measure-Object |
select -ExpandProperty Count)
& $SafeCommands['Where-Object'] {"`n","`r","`t","`b","`0" -contains $_} |
& $SafeCommands['Measure-Object'] |
& $SafeCommands['Select-Object'] -ExpandProperty Count)
}

'-'*($differenceIndex+$specialCharacterOffset+11)+'^'
Expand Down
2 changes: 1 addition & 1 deletion Functions/Assertions/Contain.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

function PesterContain($file, $contentExpecation) {
return ((Get-Content -Encoding UTF8 $file) -match $contentExpecation)
return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $file) -match $contentExpecation)
}

function PesterContainFailureMessage($file, $contentExpecation) {
Expand Down
2 changes: 1 addition & 1 deletion Functions/Assertions/ContainExactly.ps1
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
function PesterContainExactly($file, $contentExpecation) {
return ((Get-Content -Encoding UTF8 $file) -cmatch $contentExpecation)
return ((& $SafeCommands['Get-Content'] -Encoding UTF8 $file) -cmatch $contentExpecation)
}

function PesterContainExactlyFailureMessage($file, $contentExpecation) {
Expand Down
2 changes: 1 addition & 1 deletion Functions/Assertions/Exist.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

function PesterExist($value) {
Test-Path $value
& $SafeCommands['Test-Path'] $value
}

function PesterExistFailureMessage($value) {
Expand Down
6 changes: 3 additions & 3 deletions Functions/Assertions/Should.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function Parse-ShouldArgs([array] $shouldArgs) {

function Get-TestResult($shouldArgs, $value) {
$assertionMethod = $shouldArgs.AssertionMethod
$command = Get-Command $assertionMethod -ErrorAction $script:IgnoreErrorPreference
$command = Get-Command $assertionMethod -CommandType Function -ErrorAction $script:IgnoreErrorPreference

if ($null -eq $command)
{
Expand All @@ -60,12 +60,12 @@ function Get-FailureMessage($shouldArgs, $value) {
return (& $failureMessageFunction $value $shouldArgs.ExpectedValue)
}
function New-ShouldErrorRecord ([string] $Message, [string] $File, [string] $Line, [string] $LineText) {
$exception = New-Object Exception $Message
$exception = & $SafeCommands['New-Object'] Exception $Message
$errorID = 'PesterAssertionFailed'
$errorCategory = [Management.Automation.ErrorCategory]::InvalidResult
# we use ErrorRecord.TargetObject to pass structured information about the error to a reporting system.
$targetObject = @{Message = $Message; File = $File; Line = $Line; LineText = $LineText}
$errorRecord = New-Object Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject
$errorRecord = & $SafeCommands['New-Object'] Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject
return $errorRecord
}

Expand Down
4 changes: 2 additions & 2 deletions Functions/Context.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ about_TestDrive
}
catch
{
$firstStackTraceLine = $_.InvocationInfo.PositionMessage.Trim() -split '\r?\n' | Select-Object -First 1
$firstStackTraceLine = $_.InvocationInfo.PositionMessage.Trim() -split '\r?\n' | & $SafeCommands['Select-Object'] -First 1
$Pester.AddTestResult('Error occurred in Context block', "Failed", $null, $_.Exception.Message, $firstStackTraceLine, $null, $null, $_)
$Pester.TestResult[-1] | Write-PesterResult
}
Expand All @@ -78,7 +78,7 @@ about_TestDrive
}

Clear-SetupAndTeardown
Clear-TestDrive -Exclude ($TestDriveContent | select -ExpandProperty FullName)
Clear-TestDrive -Exclude ($TestDriveContent | & $SafeCommands['Select-Object'] -ExpandProperty FullName)
Exit-MockScope
$Pester.LeaveContext()
}
Expand Down
44 changes: 22 additions & 22 deletions Functions/Coverage.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ if ($PSVersionTable.PSVersion.Major -le 2)
function Enter-CoverageAnalysis {
param ( $CodeCoverage )

if ($CodeCoverage) { Write-Error 'Code coverage analysis requires PowerShell 3.0 or later.' }
if ($CodeCoverage) { & $SafeCommands['Write-Error'] 'Code coverage analysis requires PowerShell 3.0 or later.' }
}

return
Expand All @@ -33,12 +33,12 @@ function Exit-CoverageAnalysis
{
param ([object] $PesterState)

Set-StrictMode -Off
& $SafeCommands['Set-StrictMode'] -Off

$breakpoints = @($PesterState.CommandCoverage.Breakpoint) -ne $null
if ($breakpoints.Count -gt 0)
{
Remove-PSBreakpoint -Breakpoint $breakpoints
& $SafeCommands['Remove-PSBreakpoint'] -Breakpoint $breakpoints
}
}

Expand Down Expand Up @@ -116,25 +116,25 @@ function Resolve-CoverageInfo

try
{
$resolvedPaths = Resolve-Path -Path $path -ErrorAction Stop
$resolvedPaths = & $SafeCommands['Resolve-Path'] -Path $path -ErrorAction Stop
}
catch
{
Write-Error "Could not resolve coverage path '$path': $($_.Exception.Message)"
& $SafeCommands['Write-Error'] "Could not resolve coverage path '$path': $($_.Exception.Message)"
return
}

$filePaths =
foreach ($resolvedPath in $resolvedPaths)
{
$item = Get-Item -LiteralPath $resolvedPath
$item = & $SafeCommands['Get-Item'] -LiteralPath $resolvedPath
if ($item -is [System.IO.FileInfo] -and ('.ps1','.psm1') -contains $item.Extension)
{
$item.FullName
}
elseif (-not $item.PsIsContainer)
{
Write-Warning "CodeCoverage path '$path' resolved to a non-PowerShell file '$($item.FullName)'; this path will not be part of the coverage report."
& $SafeCommands['Write-Warning'] "CodeCoverage path '$path' resolved to a non-PowerShell file '$($item.FullName)'; this path will not be part of the coverage report."
}
}

Expand All @@ -158,10 +158,10 @@ function Get-CoverageBreakpoints
[object[]] $CoverageInfo
)

$fileGroups = @($CoverageInfo | Group-Object -Property Path)
$fileGroups = @($CoverageInfo | & $SafeCommands['Group-Object'] -Property Path)
foreach ($fileGroup in $fileGroups)
{
Write-Verbose "Initializing code coverage analysis for file '$($fileGroup.Name)'"
& $SafeCommands['Write-Verbose'] "Initializing code coverage analysis for file '$($fileGroup.Name)'"
$totalCommands = 0
$analyzedCommands = 0

Expand All @@ -181,7 +181,7 @@ function Get-CoverageBreakpoints
}
}

Write-Verbose "Analyzing $analyzedCommands of $totalCommands commands in file '$($fileGroup.Name)' for code coverage"
& $SafeCommands['Write-Verbose'] "Analyzing $analyzedCommands of $totalCommands commands in file '$($fileGroup.Name)' for code coverage"
}
}

Expand Down Expand Up @@ -279,7 +279,7 @@ function New-CoverageBreakpoint
Action = { }
}

$breakpoint = Set-PSBreakpoint @params
$breakpoint = & $SafeCommands['Set-PSBreakpoint'] @params

[pscustomobject] @{
File = $Command.Extent.File
Expand Down Expand Up @@ -454,7 +454,7 @@ function Get-KeyValuePairText
[System.Management.Automation.Language.Ast] $ChildAst
)

Set-StrictMode -Off
& $SafeCommands['Set-StrictMode'] -Off

foreach ($keyValuePair in $HashtableAst.KeyValuePairs)
{
Expand All @@ -471,13 +471,13 @@ function Get-KeyValuePairText
function Get-CoverageMissedCommands
{
param ([object[]] $CommandCoverage)
$CommandCoverage | Where-Object { $_.Breakpoint.HitCount -eq 0 }
$CommandCoverage | & $SafeCommands['Where-Object'] { $_.Breakpoint.HitCount -eq 0 }
}

function Get-CoverageHitCommands
{
param ([object[]] $CommandCoverage)
$CommandCoverage | Where-Object { $_.Breakpoint.HitCount -gt 0 }
$CommandCoverage | & $SafeCommands['Where-Object'] { $_.Breakpoint.HitCount -gt 0 }
}

function Get-CoverageReport
Expand All @@ -486,9 +486,9 @@ function Get-CoverageReport

$totalCommandCount = $PesterState.CommandCoverage.Count

$missedCommands = @(Get-CoverageMissedCommands -CommandCoverage $PesterState.CommandCoverage | Select-Object File, Line, Function, Command)
$hitCommands = @(Get-CoverageHitCommands -CommandCoverage $PesterState.CommandCoverage | Select-Object File, Line, Function, Command)
$analyzedFiles = @($PesterState.CommandCoverage | Select-Object -ExpandProperty File -Unique)
$missedCommands = @(Get-CoverageMissedCommands -CommandCoverage $PesterState.CommandCoverage | & $SafeCommands['Select-Object'] File, Line, Function, Command)
$hitCommands = @(Get-CoverageHitCommands -CommandCoverage $PesterState.CommandCoverage | & $SafeCommands['Select-Object'] File, Line, Function, Command)
$analyzedFiles = @($PesterState.CommandCoverage | & $SafeCommands['Select-Object'] -ExpandProperty File -Unique)
$fileCount = $analyzedFiles.Count

$executedCommandCount = $totalCommandCount - $missedCommands.Count
Expand Down Expand Up @@ -522,7 +522,7 @@ function Show-CoverageReport
if ($fileCount -gt 1) { $filePlural = 's' }

$commonParent = Get-CommonParentPath -Path $CoverageReport.AnalyzedFiles
$report = $CoverageReport.MissedCommands | Select-Object -Property @(
$report = $CoverageReport.MissedCommands | & $SafeCommands['Select-Object'] -Property @(
@{ Name = 'File'; Expression = { Get-RelativePath -Path $_.File -RelativeTo $commonParent } }
'Function'
'Line'
Expand All @@ -537,19 +537,19 @@ function Show-CoverageReport
{
Write-Screen ''
Write-Screen 'Missed commands:'
$report | Format-Table -AutoSize | Out-String | Write-Screen
$report | & $SafeCommands['Format-Table'] -AutoSize | & $SafeCommands['Out-String'] | Write-Screen
}
}

function Get-CommonParentPath
{
param ([string[]] $Path)

$pathsToTest = @( $Path | Select-Object -Unique )
$pathsToTest = @( $Path | & $SafeCommands['Select-Object'] -Unique )

if ($pathsToTest.Count -gt 0)
{
$parentPath = Split-Path -Path $pathsToTest[0] -Parent
$parentPath = & $SafeCommands['Split-Path'] -Path $pathsToTest[0] -Parent

while ($parentPath.Length -gt 0)
{
Expand All @@ -561,7 +561,7 @@ function Get-CommonParentPath
}
else
{
$parentPath = Split-Path -Path $parentPath -Parent
$parentPath = & $SafeCommands['Split-Path'] -Path $parentPath -Parent
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions Functions/Describe.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -65,22 +65,22 @@ about_TestDrive
[ScriptBlock] $Fixture = $(Throw "No test script block is provided. (Have you put the open curly brace on the next line?)")
)

if ($null -eq (Get-Variable -Name Pester -ValueOnly -ErrorAction $script:IgnoreErrorPreference))
if ($null -eq (& $SafeCommands['Get-Variable'] -Name Pester -ValueOnly -ErrorAction $script:IgnoreErrorPreference))
{
# User has executed a test script directly instead of calling Invoke-Pester
$Pester = New-PesterState -Path (Resolve-Path .) -TestNameFilter $null -TagFilter @() -SessionState $PSCmdlet.SessionState
$Pester = New-PesterState -Path (& $SafeCommands['Resolve-Path'] .) -TestNameFilter $null -TagFilter @() -SessionState $PSCmdlet.SessionState
$script:mockTable = @{}
}

if($Pester.TestNameFilter-and -not ($Pester.TestNameFilter | Where-Object { $Name -like $_ }))
if($Pester.TestNameFilter-and -not ($Pester.TestNameFilter | & $SafeCommands['Where-Object'] { $Name -like $_ }))
{
#skip this test
return
}

#TODO add test to test tags functionality
if($Pester.TagFilter -and @(Compare-Object $Tags $Pester.TagFilter -IncludeEqual -ExcludeDifferent).count -eq 0) {return}
if($Pester.ExcludeTagFilter -and @(Compare-Object $Tags $Pester.ExcludeTagFilter -IncludeEqual -ExcludeDifferent).count -gt 0) {return}
if($Pester.TagFilter -and @(& $SafeCommands['Compare-Object'] $Tags $Pester.TagFilter -IncludeEqual -ExcludeDifferent).count -eq 0) {return}
if($Pester.ExcludeTagFilter -and @(& $SafeCommands['Compare-Object'] $Tags $Pester.ExcludeTagFilter -IncludeEqual -ExcludeDifferent).count -gt 0) {return}

$Pester.EnterDescribe($Name)

Expand All @@ -102,7 +102,7 @@ about_TestDrive
}
catch
{
$firstStackTraceLine = $_.InvocationInfo.PositionMessage.Trim() -split '\r?\n' | Select-Object -First 1
$firstStackTraceLine = $_.InvocationInfo.PositionMessage.Trim() -split '\r?\n' | & $SafeCommands['Select-Object'] -First 1
$Pester.AddTestResult('Error occurred in Describe block', "Failed", $null, $_.Exception.Message, $firstStackTraceLine, $null, $null, $_)
$Pester.TestResult[-1] | Write-PesterResult
}
Expand Down
4 changes: 2 additions & 2 deletions Functions/In.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ param(
Assert-DescribeInProgress -CommandName In

$old_pwd = $pwd
pushd $path
& $SafeCommands['Push-Location'] $path
$pwd = $path
try {
& $execute
} finally {
popd
& $SafeCommands['Pop-Location']
$pwd = $old_pwd
}
}
12 changes: 6 additions & 6 deletions Functions/InModuleScope.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ function InModuleScope
$ScriptBlock
)

if ($null -eq (Get-Variable -Name Pester -ValueOnly -ErrorAction $script:IgnoreErrorPreference))
if ($null -eq (& $SafeCommands['Get-Variable'] -Name Pester -ValueOnly -ErrorAction $script:IgnoreErrorPreference))
{
# User has executed a test script directly instead of calling Invoke-Pester
$Pester = New-PesterState -Path (Resolve-Path .) -TestNameFilter $null -TagFilter @() -ExcludeTagFilter @() -SessionState $PSCmdlet.SessionState
$Pester = New-PesterState -Path (& $SafeCommands['Resolve-Path'] .) -TestNameFilter $null -TagFilter @() -ExcludeTagFilter @() -SessionState $PSCmdlet.SessionState
$script:mockTable = @{}
}

Expand Down Expand Up @@ -101,14 +101,14 @@ function Get-ScriptModule

try
{
$modules = @(Get-Module -Name $ModuleName -All -ErrorAction Stop)
$modules = @(& $SafeCommands['Get-Module'] -Name $ModuleName -All -ErrorAction Stop)
}
catch
{
throw "No module named '$ModuleName' is currently loaded."
}

$scriptModules = @($modules | Where-Object { $_.ModuleType -eq 'Script' })
$scriptModules = @($modules | & $SafeCommands['Where-Object'] { $_.ModuleType -eq 'Script' })

if ($scriptModules.Count -gt 1)
{
Expand All @@ -119,8 +119,8 @@ function Get-ScriptModule
{
$actualTypes = @(
$modules |
Where-Object { $_.ModuleType -ne 'Script' } |
Select-Object -ExpandProperty ModuleType -Unique
& $SafeCommands['Where-Object'] { $_.ModuleType -ne 'Script' } |
& $SafeCommands['Select-Object'] -ExpandProperty ModuleType -Unique
)

$actualTypes = $actualTypes -join ', '
Expand Down
10 changes: 5 additions & 5 deletions Functions/It.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ function Invoke-Test
}
else
{
Write-Progress -Activity "Running test '$Name'" -Status Processing
& $SafeCommands['Write-Progress'] -Activity "Running test '$Name'" -Status Processing

$errorRecord = $null
try
Expand Down Expand Up @@ -277,7 +277,7 @@ function Invoke-Test
$result = Get-PesterResult -ErrorRecord $errorRecord
$orderedParameters = Get-OrderedParameterDictionary -ScriptBlock $ScriptBlock -Dictionary $Parameters
$Pester.AddTestResult( $result.name, $result.Result, $null, $result.FailureMessage, $result.StackTrace, $ParameterizedSuiteName, $orderedParameters, $result.ErrorRecord )
Write-Progress -Activity "Running test '$Name'" -Completed -Status Processing
& $SafeCommands['Write-Progress'] -Activity "Running test '$Name'" -Completed -Status Processing
}

if ($null -ne $OutputScriptBlock)
Expand Down Expand Up @@ -364,7 +364,7 @@ function Get-OrderedParameterDictionary

$parameters = Get-ParameterDictionary -ScriptBlock $ScriptBlock

$orderedDictionary = New-Object System.Collections.Specialized.OrderedDictionary
$orderedDictionary = & $SafeCommands['New-Object'] System.Collections.Specialized.OrderedDictionary

foreach ($parameterName in $parameters.Keys)
{
Expand All @@ -390,13 +390,13 @@ function Get-ParameterDictionary

try
{
Set-Content function:\$guid $ScriptBlock
& $SafeCommands['Set-Content'] function:\$guid $ScriptBlock
$metadata = [System.Management.Automation.CommandMetadata](Get-Command -Name $guid -CommandType Function)

return $metadata.Parameters
}
finally
{
if (Test-Path function:\$guid) { Remove-Item function:\$guid }
if (& $SafeCommands['Test-Path'] function:\$guid) { & $SafeCommands['Remove-Item'] function:\$guid }
}
}
Loading

0 comments on commit 4a3bf16

Please sign in to comment.