From b1c40cd67f86b737956e4e788146b66c9d9d95d9 Mon Sep 17 00:00:00 2001 From: "Christoph Bergmeister [MVP]" Date: Thu, 16 Apr 2020 23:38:17 +0100 Subject: [PATCH] Replace usage of $MyInvocation.MyCommand.Path with $PSScriptRoot and cleanup tests as a preparation for Pester v5 (#1438) * Replace usage of $MyInvocation.MyCommand.Pat with $PSScriptRoot and cleanup tests * Fix 2 small mistakes, test should now be green again * remove redundant [bool] before $IsCoreCLR and make casing consistent Co-authored-by: Christoph Bergmeister --- .../Documentation/RuleDocumentation.tests.ps1 | 8 +- Tests/Engine/CustomizedRule.tests.ps1 | 85 +++++++--------- Tests/Engine/EditableText.tests.ps1 | 8 +- Tests/Engine/Extensions.tests.ps1 | 3 +- Tests/Engine/GetScriptAnalyzerRule.tests.ps1 | 13 ++- Tests/Engine/GlobalSuppression.test.ps1 | 25 +++-- Tests/Engine/InvokeFormatter.tests.ps1 | 3 +- Tests/Engine/InvokeScriptAnalyzer.tests.ps1 | 97 +++++++++---------- Tests/Engine/LibraryUsage.tests.ps1 | 44 ++++----- .../Engine/ModuleDependencyHandler.tests.ps1 | 8 +- Tests/Engine/RuleSuppression.tests.ps1 | 9 +- Tests/Engine/RuleSuppressionClass.tests.ps1 | 9 +- Tests/Engine/Settings.tests.ps1 | 3 +- .../Rules/AlignAssignmentStatement.tests.ps1 | 3 +- ...nvertToSecureStringWithPlainText.tests.ps1 | 5 +- ...dDefaultTrueValueSwitchParameter.tests.ps1 | 5 +- Tests/Rules/AvoidEmptyCatchBlock.tests.ps1 | 5 +- Tests/Rules/AvoidGlobalAliases.tests.ps1 | 7 +- Tests/Rules/AvoidGlobalFunctions.tests.ps1 | 5 +- Tests/Rules/AvoidGlobalVars.tests.ps1 | 5 +- .../Rules/AvoidInvokingEmptyMembers.tests.ps1 | 5 +- ...dNullOrEmptyHelpMessageAttribute.tests.ps1 | 5 +- .../Rules/AvoidPositionalParameters.tests.ps1 | 7 +- Tests/Rules/AvoidReservedParams.tests.ps1 | 5 +- .../AvoidShouldContinueWithoutForce.tests.ps1 | 5 +- Tests/Rules/AvoidTrailingWhitespace.tests.ps1 | 4 +- ...OrMissingRequiredFieldInManifest.tests.ps1 | 25 +++-- .../AvoidUserNameAndPasswordParams.tests.ps1 | 5 +- Tests/Rules/AvoidUsingAlias.tests.ps1 | 9 +- .../AvoidUsingComputerNameHardcoded.tests.ps1 | 5 +- ...oidUsingDeprecatedManifestFields.tests.ps1 | 9 +- .../AvoidUsingInvokeExpression.tests.ps1 | 5 +- .../AvoidUsingPlainTextForPassword.tests.ps1 | 7 +- .../AvoidUsingReservedCharNames.tests.ps1 | 5 +- Tests/Rules/AvoidUsingWMICmdlet.tests.ps1 | 7 +- Tests/Rules/AvoidUsingWriteHost.tests.ps1 | 5 +- Tests/Rules/DscExamplesPresent.tests.ps1 | 9 +- Tests/Rules/DscTestsPresent.tests.ps1 | 9 +- Tests/Rules/MisleadingBacktick.tests.ps1 | 9 +- Tests/Rules/PSCredentialType.tests.ps1 | 7 +- Tests/Rules/PlaceCloseBrace.tests.ps1 | 4 +- ...sibleIncorrectComparisonWithNull.tests.ps1 | 5 +- Tests/Rules/ProvideCommentHelp.tests.ps1 | 10 +- ...eturnCorrectTypesForDSCFunctions.tests.ps1 | 9 +- .../UseBOMForUnicodeEncodedFile.tests.ps1 | 9 +- Tests/Rules/UseCmdletCorrectly.tests.ps1 | 5 +- Tests/Rules/UseCompatibleCmdlets.tests.ps1 | 5 +- .../Rules/UseConsistentIndentation.tests.ps1 | 4 +- Tests/Rules/UseConsistentWhitespace.tests.ps1 | 4 +- Tests/Rules/UseDSCResourceFunctions.tests.ps1 | 9 +- ...eDeclaredVarsMoreThanAssignments.tests.ps1 | 8 +- ...enticalMandatoryParametersForDSC.tests.ps1 | 3 +- .../Rules/UseIdenticalParametersDSC.tests.ps1 | 7 +- Tests/Rules/UseOutputTypeCorrectly.tests.ps1 | 7 +- .../Rules/UseShouldProcessCorrectly.tests.ps1 | 8 +- ...ProcessForStateChangingFunctions.tests.ps1 | 5 +- .../UseSingularNounsReservedVerbs.tests.ps1 | 10 +- .../Rules/UseSupportsShouldProcess.tests.ps1 | 4 +- .../UseToExportFieldsInManifest.tests.ps1 | 11 +-- .../UseUTF8EncodingForHelpFile.tests.ps1 | 9 +- .../UseVerboseMessageInDSCResource.Tests.ps1 | 7 +- 61 files changed, 275 insertions(+), 365 deletions(-) diff --git a/Tests/Documentation/RuleDocumentation.tests.ps1 b/Tests/Documentation/RuleDocumentation.tests.ps1 index ca41f4819..6b0d93a51 100644 --- a/Tests/Documentation/RuleDocumentation.tests.ps1 +++ b/Tests/Documentation/RuleDocumentation.tests.ps1 @@ -1,10 +1,6 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory -$repoRootDirectory = Split-Path -Parent $testRootDirectory -$ruleDocDirectory = Join-Path $repoRootDirectory RuleDocumentation - Describe "Validate rule documentation files" { BeforeAll { + $ruleDocDirectory = Join-Path $PSScriptRoot '../../RuleDocumentation' $docs = Get-ChildItem $ruleDocDirectory/*.md -Exclude README.md | ForEach-Object { "PS" + $_.BaseName} | Sort-Object @@ -56,7 +52,7 @@ Describe "Validate rule documentation files" { $filePath | Should -Exist } } - + It "Every rule name in the rule documentation README.md file must match the documentation file's basename" { foreach ($key in $readmeLinks.Keys) { $link = $readmeLinks[$key] diff --git a/Tests/Engine/CustomizedRule.tests.ps1 b/Tests/Engine/CustomizedRule.tests.ps1 index dbc295e50..b08d2dec2 100644 --- a/Tests/Engine/CustomizedRule.tests.ps1 +++ b/Tests/Engine/CustomizedRule.tests.ps1 @@ -1,8 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory -Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') - -if (-not (Test-PSEditionCoreCLR)) +if (-not $IsCoreCLR) { # Force Get-Help not to prompt for interactive input to download help using Update-Help # By adding this registry key we turn off Get-Help interactivity logic during ScriptRule parsing @@ -25,7 +21,7 @@ $measure = "Measure-RequiresRunAsAdministrator" Describe "Test importing customized rules with null return results" { Context "Test Get-ScriptAnalyzer with customized rules" { It "will not terminate the engine" { - $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\samplerule\SampleRulesWithErrors.psm1 | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\samplerule\SampleRulesWithErrors.psm1 | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 1 } @@ -33,7 +29,7 @@ Describe "Test importing customized rules with null return results" { Context "Test Invoke-ScriptAnalyzer with customized rules" { It "will not terminate the engine" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule\SampleRulesWithErrors.psm1 | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule\SampleRulesWithErrors.psm1 | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 0 } } @@ -42,7 +38,7 @@ Describe "Test importing customized rules with null return results" { Describe "Test importing correct customized rules" { - if(-not (Test-PSEditionCoreCLR)) + if(-not $IsCoreCLR) { Context "Test Get-Help functionality in ScriptRule parsing logic" { It "ScriptRule help section must be correctly processed when Get-Help is called for the first time" { @@ -58,7 +54,7 @@ Describe "Test importing correct customized rules" { } } - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule\samplerule.psm1 | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule\samplerule.psm1 | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 1 # Force Get-Help not to prompt for interactive input to download help using Update-Help @@ -79,70 +75,65 @@ Describe "Test importing correct customized rules" { Context "Test Get-ScriptAnalyzer with customized rules" { It "will show the custom rule" { - $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\samplerule\samplerule.psm1 | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\samplerule\samplerule.psm1 | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 1 } It "will show the custom rule when given a rule folder path" { - $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\samplerule | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\samplerule | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 1 } It "will show the custom rule when given a rule folder path with trailing backslash" -skip:$($IsLinux -or $IsMacOS) { - $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $directory/samplerule/ | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot/samplerule/ | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 1 } It "will show the custom rules when given a glob" { - # needs fixing for Linux - $expectedNumRules = 4 - $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\samplerule\samplerule* | Where-Object {$_.RuleName -match $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\samplerule\samplerule* | Where-Object {$_.RuleName -match $measure} $customizedRulePath.Count | Should -Be 4 } It "will show the custom rules when given recurse switch" { - $customizedRulePath = Get-ScriptAnalyzerRule -RecurseCustomRulePath -CustomizedRulePath "$directory\samplerule", "$directory\samplerule\samplerule2" | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -RecurseCustomRulePath -CustomizedRulePath "$PSScriptRoot\samplerule", "$PSScriptRoot\samplerule\samplerule2" | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 5 } It "will show the custom rules when given glob with recurse switch" { - # needs fixing for Linux - $expectedNumRules = 5 - $customizedRulePath = Get-ScriptAnalyzerRule -RecurseCustomRulePath -CustomizedRulePath $directory\samplerule\samplerule* | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -RecurseCustomRulePath -CustomizedRulePath $PSScriptRoot\samplerule\samplerule* | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 5 } It "will show the custom rules when given glob with recurse switch" { - $customizedRulePath = Get-ScriptAnalyzerRule -RecurseCustomRulePath -CustomizedRulePath $directory\samplerule* | Where-Object {$_.RuleName -eq $measure} + $customizedRulePath = Get-ScriptAnalyzerRule -RecurseCustomRulePath -CustomizedRulePath $PSScriptRoot\samplerule* | Where-Object {$_.RuleName -eq $measure} $customizedRulePath.Count | Should -Be 3 } } Context "Test Invoke-ScriptAnalyzer with customized rules" { It "will show the custom rule in the results" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule\samplerule.psm1 | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule\samplerule.psm1 | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 1 } It "will show the custom rule in the results when given a rule folder path" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 1 } It "will set ScriptName property to the target file name" { - $violations = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule $violations[0].ScriptName | Should -Be 'TestScript.ps1' } It "will set ScriptPath property to the target file path" { - $violations = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule - $expectedScriptPath = Join-Path $directory 'TestScript.ps1' + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule + $expectedScriptPath = Join-Path $PSScriptRoot 'TestScript.ps1' $violations[0].ScriptPath | Should -Be $expectedScriptPath } It "will set SuggestedCorrections" { - $violations = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule - $expectedScriptPath = Join-Path $directory 'TestScript.ps1' + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule $violations[0].SuggestedCorrections | Should -Not -BeNullOrEmpty $violations[0].SuggestedCorrections.StartLineNumber | Should -Be 1 $violations[0].SuggestedCorrections.EndLineNumber | Should -Be 2 @@ -158,7 +149,7 @@ Describe "Test importing correct customized rules" { $testScriptPath = "TestDrive:\SuppressedCustomRule.ps1" Set-Content -Path $testScriptPath -Value $script - $customizedRulePath = Invoke-ScriptAnalyzer -Path $testScriptPath -CustomizedRulePath $directory\samplerule\samplerule.psm1 | + $customizedRulePath = Invoke-ScriptAnalyzer -Path $testScriptPath -CustomizedRulePath $PSScriptRoot\samplerule\samplerule.psm1 | Where-Object { $_.Message -eq $message } $customizedRulePath.Count | Should -Be 0 @@ -202,7 +193,7 @@ Describe "Test importing correct customized rules" { } It "will set RuleSuppressionID" { - $violations = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule $violations[0].RuleSuppressionID | Should -Be "MyRuleSuppressionID" } @@ -212,63 +203,61 @@ Describe "Test importing correct customized rules" { # needs fixing for Linux if (!$IsLinux -and !$IsMacOS) { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule\ | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule\ | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 1 } } It "will show the custom rules when given a glob" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\samplerule\samplerule* | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\samplerule\samplerule* | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 3 } It "will show the custom rules when given recurse switch" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -RecurseCustomRulePath -CustomizedRulePath $directory\samplerule | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -RecurseCustomRulePath -CustomizedRulePath $PSScriptRoot\samplerule | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 3 } It "will show the custom rules when given glob with recurse switch" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -RecurseCustomRulePath -CustomizedRulePath $directory\samplerule\samplerule* | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -RecurseCustomRulePath -CustomizedRulePath $PSScriptRoot\samplerule\samplerule* | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 4 } It "will show the custom rules when given glob with recurse switch" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -RecurseCustomRulePath -CustomizedRulePath $directory\samplerule* | Where-Object {$_.Message -eq $message} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -RecurseCustomRulePath -CustomizedRulePath $PSScriptRoot\samplerule* | Where-Object {$_.Message -eq $message} $customizedRulePath.Count | Should -Be 3 } It "Using IncludeDefaultRules Switch with CustomRulePath" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomRulePath $directory\samplerule\samplerule.psm1 -IncludeDefaultRules + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomRulePath $PSScriptRoot\samplerule\samplerule.psm1 -IncludeDefaultRules $customizedRulePath.Count | Should -Be 2 } It "Using IncludeDefaultRules Switch without CustomRulePath" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -IncludeDefaultRules + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -IncludeDefaultRules $customizedRulePath.Count | Should -Be 1 } It "Not Using IncludeDefaultRules Switch and without CustomRulePath" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 $customizedRulePath.Count | Should -Be 1 } It "loads custom rules that contain version in their path" -Skip:($PSVersionTable.PSVersion -lt [Version]'5.0.0') { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomRulePath $directory\VersionedSampleRule\SampleRuleWithVersion - $customizedRulePath.Count | Should -Be 1 + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomRulePath $PSScriptRoot\VersionedSampleRule\SampleRuleWithVersion + $customizedRulePath.Count | Should -Be 1 - $customizedRulePath = Get-ScriptAnalyzerRule -CustomRulePath $directory\VersionedSampleRule\SampleRuleWithVersion - $customizedRulePath.Count | Should -Be 1 + $customizedRulePath = Get-ScriptAnalyzerRule -CustomRulePath $PSScriptRoot\VersionedSampleRule\SampleRuleWithVersion + $customizedRulePath.Count | Should -Be 1 } It "loads custom rules that contain version in their path with the RecurseCustomRule switch" -Skip:($PSVersionTable.PSVersion -lt [Version]'5.0.0') { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomRulePath $directory\VersionedSampleRule -RecurseCustomRulePath - $customizedRulePath.Count | Should -Be 1 + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomRulePath $PSScriptRoot\VersionedSampleRule -RecurseCustomRulePath + $customizedRulePath.Count | Should -Be 1 - $customizedRulePath = Get-ScriptAnalyzerRule -CustomRulePath $directory\VersionedSampleRule -RecurseCustomRulePath - $customizedRulePath.Count | Should -Be 1 - } + $customizedRulePath = Get-ScriptAnalyzerRule -CustomRulePath $PSScriptRoot\VersionedSampleRule -RecurseCustomRulePath + $customizedRulePath.Count | Should -Be 1 + } } - } } - diff --git a/Tests/Engine/EditableText.tests.ps1 b/Tests/Engine/EditableText.tests.ps1 index 4c941b6e8..eb0222e94 100644 --- a/Tests/Engine/EditableText.tests.ps1 +++ b/Tests/Engine/EditableText.tests.ps1 @@ -1,13 +1,10 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") - $editableTextType = "Microsoft.Windows.PowerShell.ScriptAnalyzer.EditableText" $textEditType = "Microsoft.Windows.PowerShell.ScriptAnalyzer.TextEdit" Describe "EditableText class" { - Context "When a sigle edit is given for application" { + Context "When a single edit is given for application" { It "Should replace in a single line string in the middle" { $def = 'This is just a single line.' $edit = New-Object -TypeName $textEditType -ArgumentList 1,14,1,22,"one" @@ -93,7 +90,6 @@ function foo { } '@ # Editor does not allow trailing white-spaces, hence this weird construct. - $s = ' ' $newText = @" [CmdletBinding()] diff --git a/Tests/Engine/Extensions.tests.ps1 b/Tests/Engine/Extensions.tests.ps1 index 72456b402..875c8ce96 100644 --- a/Tests/Engine/Extensions.tests.ps1 +++ b/Tests/Engine/Extensions.tests.ps1 @@ -1,5 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") function Get-Extent { diff --git a/Tests/Engine/GetScriptAnalyzerRule.tests.ps1 b/Tests/Engine/GetScriptAnalyzerRule.tests.ps1 index d94d419c7..53ffe5e63 100644 --- a/Tests/Engine/GetScriptAnalyzerRule.tests.ps1 +++ b/Tests/Engine/GetScriptAnalyzerRule.tests.ps1 @@ -1,5 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') $sa = Get-Command Get-ScriptAnalyzerRule @@ -105,28 +104,28 @@ Describe "Test RuleExtension" { $expectedNumCommunityRules = 12 } It "with the module folder path" { - $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\CommunityAnalyzerRules | Where-Object {$_.SourceName -eq $community} + $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules | Where-Object {$_.SourceName -eq $community} $ruleExtension.Count | Should -Be $expectedNumCommunityRules } It "with the psd1 path" { - $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1 | Where-Object {$_.SourceName -eq $community} + $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1 | Where-Object {$_.SourceName -eq $community} $ruleExtension.Count | Should -Be $expectedNumCommunityRules } It "with the psm1 path" { - $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 | Where-Object {$_.SourceName -eq $community} + $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 | Where-Object {$_.SourceName -eq $community} $ruleExtension.Count | Should -Be $expectedNumCommunityRules } It "with Name of a built-in rules" { - $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -Name $singularNouns + $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -Name $singularNouns $ruleExtension.Count | Should -Be 0 } It "with Names of built-in, DSC and non-built-in rules" { - $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -Name $singularNouns, $measureRequired, $dscIdentical + $ruleExtension = Get-ScriptAnalyzerRule -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -Name $singularNouns, $measureRequired, $dscIdentical $ruleExtension.Count | Should -Be 1 ($ruleExtension | Where-Object {$_.RuleName -eq $measureRequired}).Count | Should -Be 1 ($ruleExtension | Where-Object {$_.RuleName -eq $singularNouns}).Count | Should -Be 0 diff --git a/Tests/Engine/GlobalSuppression.test.ps1 b/Tests/Engine/GlobalSuppression.test.ps1 index 74e23fc48..76da8fc36 100644 --- a/Tests/Engine/GlobalSuppression.test.ps1 +++ b/Tests/Engine/GlobalSuppression.test.ps1 @@ -6,11 +6,10 @@ if (!(Get-Module PSScriptAnalyzer) -and !$testingLibraryUsage) Import-Module -Verbose PSScriptAnalyzer } -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -$violationsUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$directory\GlobalSuppression.ps1") -$suppression = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -Profile "$directory\Profile.ps1" -$suppressionUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$directory\GlobalSuppression.ps1") -Profile "$directory\Profile.ps1" +$violations = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" +$violationsUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$PSScriptRoot\GlobalSuppression.ps1") +$suppression = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" -Profile "$PSScriptRoot\Profile.ps1" +$suppressionUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$PSScriptRoot\GlobalSuppression.ps1") -Profile "$PSScriptRoot\Profile.ps1" Describe "GlobalSuppression" { Context "Exclude Rule" { @@ -29,11 +28,11 @@ Describe "GlobalSuppression" { } It "Does not raise any violation for cmdlet alias using configuration hashtable" { - $hashtableConfiguration = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -Configuration @{"excluderules" = "PSAvoidUsingCmdletAliases"} | + $hashtableConfiguration = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" -Configuration @{"excluderules" = "PSAvoidUsingCmdletAliases"} | Where-Object { $_.RuleName -eq "PSAvoidUsingCmdletAliases"} $hashtableConfiguration.Count | Should -Be 0 - $hashtableConfiguration = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$directory\GlobalSuppression.ps1") -Configuration @{"excluderules" = "PSAvoidUsingCmdletAliases"} | + $hashtableConfiguration = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$PSScriptRoot\GlobalSuppression.ps1") -Configuration @{"excluderules" = "PSAvoidUsingCmdletAliases"} | Where-Object { $_.RuleName -eq "PSAvoidUsingCmdletAliases"} $hashtableConfiguration.Count | Should -Be 0 } @@ -53,9 +52,9 @@ Describe "GlobalSuppression" { $withProfile = $suppressionUsingScriptDefinition | Where-Object { $_.RuleName -eq "PSAvoidUsingComputerNameHardcoded" } $withProfile.Count | Should -Be 0 } - + It "Does not raise any violation for computername hard-coded using configuration hashtable" { - $hashtableConfiguration = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -Settings @{"includerules" = @("PSAvoidUsingCmdletAliases", "PSUseOutputTypeCorrectly")} | + $hashtableConfiguration = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" -Settings @{"includerules" = @("PSAvoidUsingCmdletAliases", "PSUseOutputTypeCorrectly")} | Where-Object { $_.RuleName -eq "PSAvoidUsingComputerNameHardcoded"} $hashtableConfiguration.Count | Should -Be 0 } @@ -77,7 +76,7 @@ Describe "GlobalSuppression" { } It "Does not raise any violation for use output type correctly with configuration hashtable" { - $hashtableConfiguration = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -Settings @{"severity" = "warning"} | + $hashtableConfiguration = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" -Settings @{"severity" = "warning"} | Where-Object {$_.RuleName -eq "PSUseOutputTypeCorrectly"} $hashtableConfiguration.Count | Should -Be 0 } @@ -85,19 +84,19 @@ Describe "GlobalSuppression" { Context "Error Case" { It "Raises Error for file not found" { - $invokeWithError = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -Settings ".\ThisFileDoesNotExist.ps1" -ErrorAction SilentlyContinue + $invokeWithError = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" -Settings ".\ThisFileDoesNotExist.ps1" -ErrorAction SilentlyContinue $invokeWithError.Count | Should -Be 0 $Error[0].FullyQualifiedErrorId | Should -Match "SettingsFileNotFound,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeScriptAnalyzerCommand" } It "Raises Error for file with no hash table" { - $invokeWithError = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -Settings "$directory\GlobalSuppression.ps1" -ErrorAction SilentlyContinue + $invokeWithError = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" -Settings "$PSScriptRoot\GlobalSuppression.ps1" -ErrorAction SilentlyContinue $invokeWithError.Count | Should -Be 0 $Error[0].FullyQualifiedErrorId | Should -Match "SettingsFileHasNoHashTable,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeScriptAnalyzerCommand" } It "Raises Error for wrong profile" { - $invokeWithError = Invoke-ScriptAnalyzer "$directory\GlobalSuppression.ps1" -Settings "$directory\WrongProfile.ps1" -ErrorAction SilentlyContinue + $invokeWithError = Invoke-ScriptAnalyzer "$PSScriptRoot\GlobalSuppression.ps1" -Settings "$PSScriptRoot\WrongProfile.ps1" -ErrorAction SilentlyContinue $invokeWithError.Count | Should -Be 0 $Error[0].FullyQualifiedErrorId | Should -Match "WrongSettingsKey,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeScriptAnalyzerCommand" } diff --git a/Tests/Engine/InvokeFormatter.tests.ps1 b/Tests/Engine/InvokeFormatter.tests.ps1 index e1c51be1a..39f248865 100644 --- a/Tests/Engine/InvokeFormatter.tests.ps1 +++ b/Tests/Engine/InvokeFormatter.tests.ps1 @@ -1,5 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") Describe "Invoke-Formatter Cmdlet" { diff --git a/Tests/Engine/InvokeScriptAnalyzer.tests.ps1 b/Tests/Engine/InvokeScriptAnalyzer.tests.ps1 index 3cc9351af..39e98666c 100644 --- a/Tests/Engine/InvokeScriptAnalyzer.tests.ps1 +++ b/Tests/Engine/InvokeScriptAnalyzer.tests.ps1 @@ -1,5 +1,4 @@ $sa = Get-Command Invoke-ScriptAnalyzer -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path $singularNouns = "PSUseSingularNouns" $approvedVerb = "PSUseApprovedVerbs" $rules = Get-ScriptAnalyzerRule -Name ($singularNouns, "PSUseApprovedVerbs") @@ -125,7 +124,7 @@ Describe "Test ScriptDefinition" { Describe "Test Path" { Context "When given a single file" { It "Has the same effect as without Path parameter" { - $scriptPath = Join-Path $directory "TestScript.ps1" + $scriptPath = Join-Path $PSScriptRoot "TestScript.ps1" $withPath = Invoke-ScriptAnalyzer $scriptPath $withoutPath = Invoke-ScriptAnalyzer -Path $scriptPath $withPath.Count | Should -Be $withoutPath.Count @@ -144,8 +143,8 @@ Describe "Test Path" { Context "DiagnosticRecord " { It "has valid ScriptPath and ScriptName properties when an input file is given" { $scriptName = "TestScript.ps1" - $scriptPath = Join-Path $directory $scriptName - $expectedScriptPath = Resolve-Path $directory\TestScript.ps1 + $scriptPath = Join-Path $PSScriptRoot $scriptName + $expectedScriptPath = Resolve-Path $PSScriptRoot\TestScript.ps1 $diagnosticRecords = Invoke-ScriptAnalyzer $scriptPath -IncludeRule "PSAvoidUsingEmptyCatchBlock" $diagnosticRecords[0].ScriptPath | Should -Be $expectedScriptPath.Path $diagnosticRecords[0].ScriptName | Should -Be $scriptName @@ -175,8 +174,8 @@ Describe "Test Path" { Context "When given a glob" { It "Invokes on all the matching files" { - $numFilesResult = (Invoke-ScriptAnalyzer -Path $directory\TestTestPath*.ps1 | Select-Object -Property ScriptName -Unique).Count - $numFilesExpected = (Get-ChildItem -Path $directory\TestTestPath*.ps1).Count + $numFilesResult = (Invoke-ScriptAnalyzer -Path $PSScriptRoot\TestTestPath*.ps1 | Select-Object -Property ScriptName -Unique).Count + $numFilesExpected = (Get-ChildItem -Path $PSScriptRoot\TestTestPath*.ps1).Count $numFilesResult | Should -Be $numFilesExpected } } @@ -185,7 +184,7 @@ Describe "Test Path" { It "Recognizes the path" { $freeDriveNameLen = 2 $freeDrive, $freeDriveName = GetFreeDrive $freeDriveNameLen - New-PSDrive -Name $freeDriveName -PSProvider FileSystem -Root $directory + New-PSDrive -Name $freeDriveName -PSProvider FileSystem -Root $PSScriptRoot $numFilesExpected = (Get-ChildItem -Path $freeDrive\TestTestPath*.ps1).Count $numFilesResult = (Invoke-ScriptAnalyzer -Path $freeDrive\TestTestPath*.ps1 | Select-Object -Property ScriptName -Unique).Count Remove-PSDrive $freeDriveName @@ -195,23 +194,23 @@ Describe "Test Path" { Context "When piping in files" { It "Can be piped in from a string" { - $piped = ("$directory\TestScript.ps1" | Invoke-ScriptAnalyzer) - $explicit = Invoke-ScriptAnalyzer -Path $directory\TestScript.ps1 + $piped = ("$PSScriptRoot\TestScript.ps1" | Invoke-ScriptAnalyzer) + $explicit = Invoke-ScriptAnalyzer -Path $PSScriptRoot\TestScript.ps1 $piped.Count | Should Be $explicit.Count } It "Can be piped from Get-ChildItem" { - $piped = ( Get-ChildItem -Path $directory -Filter TestTestPath*.ps1 | Invoke-ScriptAnalyzer) - $explicit = Invoke-ScriptAnalyzer -Path $directory\TestTestPath*.ps1 + $piped = ( Get-ChildItem -Path $PSScriptRoot -Filter TestTestPath*.ps1 | Invoke-ScriptAnalyzer) + $explicit = Invoke-ScriptAnalyzer -Path $PSScriptRoot\TestTestPath*.ps1 $piped.Count | Should Be $explicit.Count } } } Context "When given a directory" { - $withoutPathWithDirectory = Invoke-ScriptAnalyzer -Recurse $directory\RecursionDirectoryTest - $withPathWithDirectory = Invoke-ScriptAnalyzer -Recurse -Path $directory\RecursionDirectoryTest + $withoutPathWithDirectory = Invoke-ScriptAnalyzer -Recurse $PSScriptRoot\RecursionDirectoryTest + $withPathWithDirectory = Invoke-ScriptAnalyzer -Recurse -Path $PSScriptRoot\RecursionDirectoryTest It "Has the same count as without Path parameter"{ $withoutPathWithDirectory.Count -eq $withPathWithDirectory.Count | Should -BeTrue @@ -232,27 +231,27 @@ Describe "Test Path" { Describe "Test ExcludeRule" { Context "When used correctly" { It "excludes 1 rule" { - $noViolations = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -ExcludeRule $singularNouns | Where-Object {$_.RuleName -eq $singularNouns} + $noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -ExcludeRule $singularNouns | Where-Object {$_.RuleName -eq $singularNouns} $noViolations.Count | Should -Be 0 } It "excludes 3 rules" { - $noViolations = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -ExcludeRule $rules | Where-Object {$rules -contains $_.RuleName} + $noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -ExcludeRule $rules | Where-Object {$rules -contains $_.RuleName} $noViolations.Count | Should -Be 0 } } Context "When used incorrectly" { It "does not exclude any rules" { - $noExclude = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 - $withExclude = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -ExcludeRule "This is a wrong rule" + $noExclude = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 + $withExclude = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -ExcludeRule "This is a wrong rule" $withExclude.Count -eq $noExclude.Count | Should -BeTrue } } Context "Support wild card" { It "supports wild card exclusions of input rules"{ - $excludeWildCard = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -ExcludeRule $avoidRules | Where-Object {$_.RuleName -match $avoidRules} + $excludeWildCard = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -ExcludeRule $avoidRules | Where-Object {$_.RuleName -match $avoidRules} } } @@ -261,44 +260,44 @@ Describe "Test ExcludeRule" { Describe "Test IncludeRule" { Context "When used correctly" { It "includes 1 rule" { - $violations = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -IncludeRule $approvedVerb | Where-Object {$_.RuleName -eq $approvedVerb} + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -IncludeRule $approvedVerb | Where-Object {$_.RuleName -eq $approvedVerb} $violations.Count | Should -Be 1 } It "includes the given rules" { # CoreCLR version of PSScriptAnalyzer does not contain PSUseSingularNouns rule $expectedNumViolations = 2 - if ((Test-PSEditionCoreCLR)) + if ($IsCoreCLR) { $expectedNumViolations = 1 } - $violations = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -IncludeRule $rules + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -IncludeRule $rules $violations.Count | Should -Be $expectedNumViolations } } Context "When used incorrectly" { It "does not include any rules" { - $wrongInclude = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -IncludeRule "This is a wrong rule" + $wrongInclude = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -IncludeRule "This is a wrong rule" $wrongInclude.Count | Should -Be 0 } } Context "IncludeRule supports wild card" { It "includes 1 wildcard rule"{ - $includeWildcard = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -IncludeRule $avoidRules + $includeWildcard = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -IncludeRule $avoidRules $includeWildcard.Count | Should -Be 0 } it "includes 2 wildcardrules" { # CoreCLR version of PSScriptAnalyzer does not contain PSUseSingularNouns rule $expectedNumViolations = 4 - if ((Test-PSEditionCoreCLR)) + if ($IsCoreCLR) { $expectedNumViolations = 3 } - $includeWildcard = Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -IncludeRule $avoidRules - $includeWildcard += Invoke-ScriptAnalyzer $directory\..\Rules\BadCmdlet.ps1 -IncludeRule $useRules + $includeWildcard = Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -IncludeRule $avoidRules + $includeWildcard += Invoke-ScriptAnalyzer $PSScriptRoot\..\Rules\BadCmdlet.ps1 -IncludeRule $useRules $includeWildcard.Count | Should -Be $expectedNumViolations } } @@ -306,12 +305,12 @@ Describe "Test IncludeRule" { Describe "Test Exclude And Include" {1 It "Exclude and Include different rules" { - $violations = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -IncludeRule "PSAvoidUsingEmptyCatchBlock" -ExcludeRule "PSAvoidUsingPositionalParameters" + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -IncludeRule "PSAvoidUsingEmptyCatchBlock" -ExcludeRule "PSAvoidUsingPositionalParameters" $violations.Count | Should -Be 1 } It "Exclude and Include the same rule" { - $violations = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -IncludeRule "PSAvoidUsingEmptyCatchBlock" -ExcludeRule "PSAvoidUsingEmptyCatchBlock" + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -IncludeRule "PSAvoidUsingEmptyCatchBlock" -ExcludeRule "PSAvoidUsingEmptyCatchBlock" $violations.Count | Should -Be 0 } } @@ -345,22 +344,22 @@ Describe "Test Severity" { Context "When used correctly" { It "works with one argument" { - $errors = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -Severity Information + $errors = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -Severity Information $errors.Count | Should -Be 0 } It "works with 2 arguments" { - $errors = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -Severity Information, Warning + $errors = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -Severity Information, Warning $errors.Count | Should -Be 1 } It "works with lowercase argument"{ - $errors = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -Severity information, warning + $errors = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -Severity information, warning $errors.Count | Should -Be 1 } It "works for dsc rules" { - $testDataPath = [System.IO.Path]::Combine($(Split-Path $directory -Parent), ` + $testDataPath = [System.IO.Path]::Combine($(Split-Path $PSScriptRoot -Parent), ` 'Rules', ` 'DSCResourceModule', ` 'DSCResources', ` @@ -383,7 +382,7 @@ Describe "Test Severity" { Context "When used incorrectly" { It "throws error" { - { Invoke-ScriptAnalyzer -Severity "Wrong" $directory\TestScript.ps1 } | Should -Throw + { Invoke-ScriptAnalyzer -Severity "Wrong" $PSScriptRoot\TestScript.ps1 } | Should -Throw } } } @@ -392,33 +391,33 @@ Describe "Test CustomizedRulePath" { $measureRequired = "CommunityAnalyzerRules\Measure-RequiresModules" Context "When used correctly" { It "with the module folder path" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\CommunityAnalyzerRules | Where-Object {$_.RuleName -eq $measureRequired} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules | Where-Object {$_.RuleName -eq $measureRequired} $customizedRulePath.Count | Should -Be 1 } It "with the psd1 path" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1 | Where-Object {$_.RuleName -eq $measureRequired} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1 | Where-Object {$_.RuleName -eq $measureRequired} $customizedRulePath.Count | Should -Be 1 } It "with the psm1 path" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 | Where-Object {$_.RuleName -eq $measureRequired} + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 | Where-Object {$_.RuleName -eq $measureRequired} $customizedRulePath.Count | Should -Be 1 } It "with IncludeRule" { - $customizedRulePathInclude = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -IncludeRule "Measure-RequiresModules" + $customizedRulePathInclude = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -IncludeRule "Measure-RequiresModules" $customizedRulePathInclude.Count | Should -Be 1 } It "with ExcludeRule" { - $customizedRulePathExclude = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomizedRulePath $directory\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -ExcludeRule "Measure-RequiresModules" | Where-Object {$_.RuleName -eq $measureRequired} + $customizedRulePathExclude = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomizedRulePath $PSScriptRoot\CommunityAnalyzerRules\CommunityAnalyzerRules.psm1 -ExcludeRule "Measure-RequiresModules" | Where-Object {$_.RuleName -eq $measureRequired} $customizedRulePathExclude.Count | Should -Be 0 } It "When supplied with a collection of paths" { - $customizedRulePath = Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomRulePath ("$directory\CommunityAnalyzerRules", "$directory\samplerule", "$directory\samplerule\samplerule2") + $customizedRulePath = Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomRulePath ("$PSScriptRoot\CommunityAnalyzerRules", "$PSScriptRoot\samplerule", "$PSScriptRoot\samplerule\samplerule2") $customizedRulePath.Count | Should -Be 3 } } @@ -457,34 +456,34 @@ Describe "Test CustomizedRulePath" { It "Should use the CustomRulePath parameter" { $settings = @{ - CustomRulePath = "$directory\CommunityAnalyzerRules" + CustomRulePath = "$PSScriptRoot\CommunityAnalyzerRules" IncludeDefaultRules = $false RecurseCustomRulePath = $false } - $v = Invoke-ScriptAnalyzer -Path $directory\TestScript.ps1 -Settings $settings + $v = Invoke-ScriptAnalyzer -Path $PSScriptRoot\TestScript.ps1 -Settings $settings $v.Count | Should -Be 1 } It "Should use the IncludeDefaultRulePath parameter" { $settings = @{ - CustomRulePath = "$directory\CommunityAnalyzerRules" + CustomRulePath = "$PSScriptRoot\CommunityAnalyzerRules" IncludeDefaultRules = $true RecurseCustomRulePath = $false } - $v = Invoke-ScriptAnalyzer -Path $directory\TestScript.ps1 -Settings $settings + $v = Invoke-ScriptAnalyzer -Path $PSScriptRoot\TestScript.ps1 -Settings $settings $v.Count | Should -Be 2 } It "Should use the RecurseCustomRulePath parameter" { $settings = @{ - CustomRulePath = "$directory\samplerule" + CustomRulePath = "$PSScriptRoot\samplerule" IncludeDefaultRules = $false RecurseCustomRulePath = $true } - $v = Invoke-ScriptAnalyzer -Path $directory\TestScript.ps1 -Settings $settings + $v = Invoke-ScriptAnalyzer -Path $PSScriptRoot\TestScript.ps1 -Settings $settings $v.Count | Should -Be 3 } } @@ -492,18 +491,18 @@ Describe "Test CustomizedRulePath" { Context "When used from settings file and command line simulataneusly" { BeforeAll { $settings = @{ - CustomRulePath = "$directory\samplerule" + CustomRulePath = "$PSScriptRoot\samplerule" IncludeDefaultRules = $false RecurseCustomRulePath = $false } $isaParams = @{ - Path = "$directory\TestScript.ps1" + Path = "$PSScriptRoot\TestScript.ps1" Settings = $settings } } It "Should combine CustomRulePaths" { - $v = Invoke-ScriptAnalyzer @isaParams -CustomRulePath "$directory\CommunityAnalyzerRules" + $v = Invoke-ScriptAnalyzer @isaParams -CustomRulePath "$PSScriptRoot\CommunityAnalyzerRules" $v.Count | Should -Be 2 } @@ -523,7 +522,7 @@ Describe "Test CustomizedRulePath" { It "file cannot be found" { try { - Invoke-ScriptAnalyzer $directory\TestScript.ps1 -CustomRulePath "Invalid CustomRulePath" + Invoke-ScriptAnalyzer $PSScriptRoot\TestScript.ps1 -CustomRulePath "Invalid CustomRulePath" } catch { diff --git a/Tests/Engine/LibraryUsage.tests.ps1 b/Tests/Engine/LibraryUsage.tests.ps1 index dc0c88daa..008483908 100644 --- a/Tests/Engine/LibraryUsage.tests.ps1 +++ b/Tests/Engine/LibraryUsage.tests.ps1 @@ -1,17 +1,15 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') # test is meant to verify functionality if csharp apis are used. Hence not if psedition is CoreCLR -if ((Test-PSEditionCoreCLR)) +if ($IsCoreCLR) { return } -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path # Overwrite Invoke-ScriptAnalyzer with a version that -# wraps the usage of ScriptAnalyzer as a .NET library +# wraps the usage of ScriptAnalyzer as a .NET library function Invoke-ScriptAnalyzer { param ( [CmdletBinding(DefaultParameterSetName="File", SupportsShouldProcess = $true)] @@ -34,12 +32,12 @@ function Invoke-ScriptAnalyzer { [string[]] $ExcludeRule = $null, [Parameter(Mandatory = $false)] - [string[]] $IncludeRule = $null, + [string[]] $IncludeRule = $null, [ValidateSet("Warning", "Error", "Information", "ParseError", IgnoreCase = $true)] [Parameter(Mandatory = $false)] [string[]] $Severity = $null, - + [Parameter(Mandatory = $false)] [switch] $Recurse, @@ -54,7 +52,7 @@ function Invoke-ScriptAnalyzer { [Parameter(Mandatory = $false)] [switch] $EnableExit, - + [Parameter(Mandatory = $false)] [switch] $ReportSummary ) @@ -63,18 +61,18 @@ function Invoke-ScriptAnalyzer { { $IncludeDefaultRules = $true } - # There is an inconsistency between this implementation and c# implementation of the cmdlet. + # There is an inconsistency between this implementation and c# implementation of the cmdlet. # The CustomRulePath parameter here is of "string[]" type whereas in the c# implementation it is of "string" type. - # If we set the CustomRulePath parameter here to "string[]", then the library usage test fails when run as an administrator. + # If we set the CustomRulePath parameter here to "string[]", then the library usage test fails when run as an administrator. # We want to note that the library usage test doesn't fail when run as a non-admin user. - # The following is the error statement when the test runs as an administrator. + # The following is the error statement when the test runs as an administrator. # Assert failed on "Initialize" with "7" argument(s): "Test failed due to terminating error: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)" $scriptAnalyzer = New-Object "Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer"; $scriptAnalyzer.Initialize( - $runspace, - $testOutputWriter, - $CustomRulePath, + $runspace, + $testOutputWriter, + $CustomRulePath, $IncludeRule, $ExcludeRule, $Severity, @@ -98,7 +96,7 @@ function Invoke-ScriptAnalyzer { { $results = $scriptAnalyzer.AnalyzeScriptDefinition($ScriptDefinition); } - + $results if ($ReportSummary.IsPresent) @@ -113,7 +111,7 @@ function Invoke-ScriptAnalyzer { Write-Host '0 rule violations found.' -ForegroundColor Green } } - + if ($EnableExit.IsPresent -and $null -ne $results) { exit $results.Count @@ -126,7 +124,7 @@ using System.Management.Automation; using System.Management.Automation.Host; using Microsoft.Windows.PowerShell.ScriptAnalyzer; -public class PesterTestOutputWriter : IOutputWriter +public class PesterTestOutputWriter : IOutputWriter { private PSHost psHost; @@ -166,8 +164,8 @@ public class PesterTestOutputWriter : IOutputWriter public void ThrowTerminatingError(ErrorRecord record) { throw new RuntimeException( - "Test failed due to terminating error: \r\n" + record.ToString(), - null, + "Test failed due to terminating error: \r\n" + record.ToString(), + null, record); } } @@ -192,7 +190,7 @@ $null,"Wow6432Node" | ForEach-Object { try { Set-ItemProperty -Name "DisablePromptToUpdateHelp" -Path "HKLM:\SOFTWARE\$($_)\Microsoft\PowerShell" -Value 1 -Force -ErrorAction SilentlyContinue - } + } catch { # Ignore for cases when tests are running in non-elevated more or registry key does not exist or not accessible @@ -200,9 +198,9 @@ $null,"Wow6432Node" | ForEach-Object { } # Invoke existing test files that use Invoke-ScriptAnalyzer -. $directory\InvokeScriptAnalyzer.tests.ps1 -. $directory\RuleSuppression.tests.ps1 -. $directory\CustomizedRule.tests.ps1 +. $PSScriptRoot\InvokeScriptAnalyzer.tests.ps1 +. $PSScriptRoot\RuleSuppression.tests.ps1 +. $PSScriptRoot\CustomizedRule.tests.ps1 # We're done testing library usage $testingLibraryUsage = $false diff --git a/Tests/Engine/ModuleDependencyHandler.tests.ps1 b/Tests/Engine/ModuleDependencyHandler.tests.ps1 index a392150f5..22045644e 100644 --- a/Tests/Engine/ModuleDependencyHandler.tests.ps1 +++ b/Tests/Engine/ModuleDependencyHandler.tests.ps1 @@ -1,5 +1,3 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path - Describe "Resolve DSC Resource Dependency" { BeforeAll { $skipTest = $false # Test that require DSC to be installed @@ -19,8 +17,8 @@ Describe "Resolve DSC Resource Dependency" { $savedPSModulePath = $env:PSModulePath $violationFileName = 'MissingDSCResource.ps1' - $violationFilePath = Join-Path $directory $violationFileName - $testRootDirectory = Split-Path -Parent $directory + $violationFilePath = Join-Path $PSScriptRoot $violationFileName + $testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') Function Test-EnvironmentVariables($oldEnv) @@ -186,7 +184,7 @@ Describe "Resolve DSC Resource Dependency" { if ( $skipTest ) { return } $oldEnvVars = Get-Item Env:\* | Sort-Object -Property Key $moduleName = "MyDscResource" - $modulePath = "$(Split-Path $directory)\Rules\DSCResourceModule\DSCResources\$moduleName" + $modulePath = "$(Split-Path $PSScriptRoot)\Rules\DSCResourceModule\DSCResources\$moduleName" # Save the current environment variables $oldLocalAppDataPath = Get-LocalAppDataFolder diff --git a/Tests/Engine/RuleSuppression.tests.ps1 b/Tests/Engine/RuleSuppression.tests.ps1 index a3fd9a07b..5aeff14e9 100644 --- a/Tests/Engine/RuleSuppression.tests.ps1 +++ b/Tests/Engine/RuleSuppression.tests.ps1 @@ -1,9 +1,8 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') -$violationsUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$directory\RuleSuppression.ps1") -$violations = Invoke-ScriptAnalyzer "$directory\RuleSuppression.ps1" +$violationsUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$PSScriptRoot\RuleSuppression.ps1") +$violations = Invoke-ScriptAnalyzer "$PSScriptRoot\RuleSuppression.ps1" $ruleSuppressionBad = @' Function do-something @@ -123,7 +122,7 @@ Write-Host "write-host" It "Suppresses violation of an external ast rule" { Invoke-ScriptAnalyzer ` -ScriptDefinition $externalRuleSuppression ` - -CustomRulePath (Join-Path $directory "CommunityAnalyzerRules") ` + -CustomRulePath (Join-Path $PSScriptRoot "CommunityAnalyzerRules") ` -OutVariable ruleViolations ` -SuppressedOnly $ruleViolations.Count | Should -Be 1 diff --git a/Tests/Engine/RuleSuppressionClass.tests.ps1 b/Tests/Engine/RuleSuppressionClass.tests.ps1 index 94d26057b..22e5fcd20 100644 --- a/Tests/Engine/RuleSuppressionClass.tests.ps1 +++ b/Tests/Engine/RuleSuppressionClass.tests.ps1 @@ -3,11 +3,10 @@ if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { $script:skipForV3V4 = $false } -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violationsUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$directory\RuleSuppression.ps1") -$violations = Invoke-ScriptAnalyzer "$directory\RuleSuppression.ps1" +$violationsUsingScriptDefinition = Invoke-ScriptAnalyzer -ScriptDefinition (Get-Content -Raw "$PSScriptRoot\RuleSuppression.ps1") +$violations = Invoke-ScriptAnalyzer "$PSScriptRoot\RuleSuppression.ps1" -Describe "RuleSuppressionWithoutScope" { +Describe "RuleSuppressionWithoutScope" { Context "Class" { It "Does not raise violations" -skip:$script:skipForV3V4 { @@ -24,7 +23,7 @@ Describe "RuleSuppressionWithoutScope" { $suppression.Count | Should -Be 0 $suppression = $violationsUsingScriptDefinition | Where-Object {$_.RuleName -eq "PSAvoidUsingCmdletAliases" } $suppression.Count | Should -Be 0 - } + } } Context "Script" { diff --git a/Tests/Engine/Settings.tests.ps1 b/Tests/Engine/Settings.tests.ps1 index cfd814274..a6fd41eb8 100644 --- a/Tests/Engine/Settings.tests.ps1 +++ b/Tests/Engine/Settings.tests.ps1 @@ -1,5 +1,4 @@ -$directory = Split-Path $MyInvocation.MyCommand.Path -$settingsTestDirectory = [System.IO.Path]::Combine($directory, "SettingsTest") +$settingsTestDirectory = [System.IO.Path]::Combine($PSScriptRoot, "SettingsTest") $project1Root = [System.IO.Path]::Combine($settingsTestDirectory, "Project1") $project2Root = [System.IO.Path]::Combine($settingsTestDirectory, "Project2") $settingsTypeName = 'Microsoft.Windows.PowerShell.ScriptAnalyzer.Settings' diff --git a/Tests/Rules/AlignAssignmentStatement.tests.ps1 b/Tests/Rules/AlignAssignmentStatement.tests.ps1 index 72074f91c..1f3dbad0f 100644 --- a/Tests/Rules/AlignAssignmentStatement.tests.ps1 +++ b/Tests/Rules/AlignAssignmentStatement.tests.ps1 @@ -1,5 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") diff --git a/Tests/Rules/AvoidConvertToSecureStringWithPlainText.tests.ps1 b/Tests/Rules/AvoidConvertToSecureStringWithPlainText.tests.ps1 index c2a017771..0e7f760cb 100644 --- a/Tests/Rules/AvoidConvertToSecureStringWithPlainText.tests.ps1 +++ b/Tests/Rules/AvoidConvertToSecureStringWithPlainText.tests.ps1 @@ -1,9 +1,8 @@ Set-Alias ctss ConvertTo-SecureString $violationMessage = "File 'AvoidConvertToSecureStringWithPlainText.ps1' uses ConvertTo-SecureString with plaintext. This will expose secure information. Encrypted standard strings should be used instead." $violationName = "PSAvoidUsingConvertToSecureStringWithPlainText" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidConvertToSecureStringWithPlainText.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidConvertToSecureStringWithPlainTextNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidConvertToSecureStringWithPlainText.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidConvertToSecureStringWithPlainTextNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidConvertToSecureStringWithPlainText" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidDefaultTrueValueSwitchParameter.tests.ps1 b/Tests/Rules/AvoidDefaultTrueValueSwitchParameter.tests.ps1 index 1950bc2fc..6714ace07 100644 --- a/Tests/Rules/AvoidDefaultTrueValueSwitchParameter.tests.ps1 +++ b/Tests/Rules/AvoidDefaultTrueValueSwitchParameter.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = "File 'AvoidDefaultTrueValueSwitchParameter.ps1' has a switch parameter default to true." $violationName = "PSAvoidDefaultValueSwitchParameter" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidDefaultTrueValueSwitchParameter.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidDefaultTrueValueSwitchParameterNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidDefaultTrueValueSwitchParameter.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidDefaultTrueValueSwitchParameterNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidDefaultTrueValueSwitchParameter" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidEmptyCatchBlock.tests.ps1 b/Tests/Rules/AvoidEmptyCatchBlock.tests.ps1 index 25215cbef..636075099 100644 --- a/Tests/Rules/AvoidEmptyCatchBlock.tests.ps1 +++ b/Tests/Rules/AvoidEmptyCatchBlock.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = "Empty catch block is used. Please use Write-Error or throw statements in catch blocks." $violationName = "PSAvoidUsingEmptyCatchBlock" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidEmptyCatchBlock.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidEmptyCatchBlockNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidEmptyCatchBlock.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidEmptyCatchBlockNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "UseDeclaredVarsMoreThanAssignments" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidGlobalAliases.tests.ps1 b/Tests/Rules/AvoidGlobalAliases.tests.ps1 index 8d069c9f8..1b8716236 100644 --- a/Tests/Rules/AvoidGlobalAliases.tests.ps1 +++ b/Tests/Rules/AvoidGlobalAliases.tests.ps1 @@ -1,11 +1,10 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') $AvoidGlobalAliasesError = "Avoid creating aliases with a Global scope." $violationName = "PSAvoidGlobalAliases" -$violations = Invoke-ScriptAnalyzer $directory\AvoidGlobalAliases.psm1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidGlobalAliasesNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidGlobalAliases.psm1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidGlobalAliasesNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} $IsV3OrV4 = (Test-PSVersionV3) -or (Test-PSVersionV4) Describe "$violationName " { diff --git a/Tests/Rules/AvoidGlobalFunctions.tests.ps1 b/Tests/Rules/AvoidGlobalFunctions.tests.ps1 index b1a55847f..b420f5b83 100644 --- a/Tests/Rules/AvoidGlobalFunctions.tests.ps1 +++ b/Tests/Rules/AvoidGlobalFunctions.tests.ps1 @@ -1,9 +1,8 @@ $functionErroMessage = "Avoid creating functions with a Global scope." $violationName = "PSAvoidGlobalFunctions" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidGlobalFunctions.psm1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidGlobalFunctionsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidGlobalFunctions.psm1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidGlobalFunctionsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "$violationName " { diff --git a/Tests/Rules/AvoidGlobalVars.tests.ps1 b/Tests/Rules/AvoidGlobalVars.tests.ps1 index 8a4611e52..2b3297bd0 100644 --- a/Tests/Rules/AvoidGlobalVars.tests.ps1 +++ b/Tests/Rules/AvoidGlobalVars.tests.ps1 @@ -2,12 +2,11 @@ $globalName = "PSAvoidGlobalVars" $nonInitializedMessage = "Variable 'globalVars' is not initialized. Non-global variables must be initialized. To fix a violation of this rule, please initialize non-global variables." -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidGlobalOrUnitializedVars.ps1 +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidGlobalOrUnitializedVars.ps1 $globalViolations = $violations | Where-Object {$_.RuleName -eq $globalName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidGlobalOrUnitializedVarsNoViolations.ps1 +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidGlobalOrUnitializedVarsNoViolations.ps1 $noGlobalViolations = $noViolations | Where-Object {$_.RuleName -eq $globalName} Describe "AvoidGlobalVars" { diff --git a/Tests/Rules/AvoidInvokingEmptyMembers.tests.ps1 b/Tests/Rules/AvoidInvokingEmptyMembers.tests.ps1 index d9bb76f56..5e8580068 100644 --- a/Tests/Rules/AvoidInvokingEmptyMembers.tests.ps1 +++ b/Tests/Rules/AvoidInvokingEmptyMembers.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = "() has non-constant members. Invoking non-constant members may cause bugs in the script." $violationName = "PSAvoidInvokingEmptyMembers" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidInvokingEmptyMembers.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidInvokingEmptyMembersNonViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidInvokingEmptyMembers.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidInvokingEmptyMembersNonViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidInvokingEmptyMembers" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidNullOrEmptyHelpMessageAttribute.tests.ps1 b/Tests/Rules/AvoidNullOrEmptyHelpMessageAttribute.tests.ps1 index 909e34289..a710297aa 100644 --- a/Tests/Rules/AvoidNullOrEmptyHelpMessageAttribute.tests.ps1 +++ b/Tests/Rules/AvoidNullOrEmptyHelpMessageAttribute.tests.ps1 @@ -1,8 +1,7 @@ $violationName = "PSAvoidNullOrEmptyHelpMessageAttribute" $violationMessage = "HelpMessage parameter attribute should not be null or empty. To fix a violation of this rule, please set its value to a non-empty string." -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer "$directory\AvoidNullOrEmptyHelpMessageAttribute.ps1" -IncludeRule PSAvoidNullOrEmptyHelpMessageAttribute -$noViolations = Invoke-ScriptAnalyzer "$directory\AvoidNullOrEmptyHelpMessageAttributeNoViolations.ps1" -IncludeRule PSAvoidNullOrEmptyHelpMessageAttribute +$violations = Invoke-ScriptAnalyzer "$PSScriptRoot\AvoidNullOrEmptyHelpMessageAttribute.ps1" -IncludeRule PSAvoidNullOrEmptyHelpMessageAttribute +$noViolations = Invoke-ScriptAnalyzer "$PSScriptRoot\AvoidNullOrEmptyHelpMessageAttributeNoViolations.ps1" -IncludeRule PSAvoidNullOrEmptyHelpMessageAttribute Describe "AvoidNullOrEmptyHelpMessageAttribute" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidPositionalParameters.tests.ps1 b/Tests/Rules/AvoidPositionalParameters.tests.ps1 index ded53c954..03f9368fc 100644 --- a/Tests/Rules/AvoidPositionalParameters.tests.ps1 +++ b/Tests/Rules/AvoidPositionalParameters.tests.ps1 @@ -1,9 +1,8 @@ $violationMessage = "Cmdlet 'Get-Command' has positional parameter. Please use named parameters instead of positional parameters when calling a command." $violationName = "PSAvoidUsingPositionalParameters" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidPositionalParameters.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidPositionalParametersNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolationsDSC = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\serviceconfigdisabled.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidPositionalParameters.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidPositionalParametersNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolationsDSC = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\serviceconfigdisabled.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidPositionalParameters" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidReservedParams.tests.ps1 b/Tests/Rules/AvoidReservedParams.tests.ps1 index 358c0e9dd..52020df37 100644 --- a/Tests/Rules/AvoidReservedParams.tests.ps1 +++ b/Tests/Rules/AvoidReservedParams.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = [regex]::Escape("Verb-Files' defines the reserved common parameter 'Verbose'.") $violationName = "PSReservedParams" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidReservedParams" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidShouldContinueWithoutForce.tests.ps1 b/Tests/Rules/AvoidShouldContinueWithoutForce.tests.ps1 index 0e8e2dfec..7ebff4de5 100644 --- a/Tests/Rules/AvoidShouldContinueWithoutForce.tests.ps1 +++ b/Tests/Rules/AvoidShouldContinueWithoutForce.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = "Function 'Verb-Noun2' in file 'AvoidShouldContinueWithoutForce.ps1' uses ShouldContinue but does not have a boolean force parameter. The force parameter will allow users of the script to bypass ShouldContinue prompt" $violationName = "PSAvoidShouldContinueWithoutForce" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidShouldContinueWithoutForce.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidShouldContinueWithoutForce.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidShouldContinueWithoutForce" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidTrailingWhitespace.tests.ps1 b/Tests/Rules/AvoidTrailingWhitespace.tests.ps1 index da722a529..b51398984 100644 --- a/Tests/Rules/AvoidTrailingWhitespace.tests.ps1 +++ b/Tests/Rules/AvoidTrailingWhitespace.tests.ps1 @@ -1,6 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") $ruleName = "PSAvoidTrailingWhitespace" diff --git a/Tests/Rules/AvoidUnloadableModuleOrMissingRequiredFieldInManifest.tests.ps1 b/Tests/Rules/AvoidUnloadableModuleOrMissingRequiredFieldInManifest.tests.ps1 index 2198fa178..017382aeb 100644 --- a/Tests/Rules/AvoidUnloadableModuleOrMissingRequiredFieldInManifest.tests.ps1 +++ b/Tests/Rules/AvoidUnloadableModuleOrMissingRequiredFieldInManifest.tests.ps1 @@ -1,17 +1,16 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') $missingMessage = "The member 'ModuleVersion' is not present in the module manifest." $missingMemberRuleName = "PSMissingModuleManifestField" -$violationFilepath = Join-Path $directory "TestBadModule\TestBadModule.psd1" +$violationFilepath = Join-Path $PSScriptRoot "TestBadModule\TestBadModule.psd1" $violations = Invoke-ScriptAnalyzer $violationFilepath | Where-Object {$_.RuleName -eq $missingMemberRuleName} -$noViolations = Invoke-ScriptAnalyzer $directory\TestGoodModule\TestGoodModule.psd1 | Where-Object {$_.RuleName -eq $missingMemberRuleName} -$noHashtableFilepath = Join-Path $directory "TestBadModule\NoHashtable.psd1" +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\TestGoodModule\TestGoodModule.psd1 | Where-Object {$_.RuleName -eq $missingMemberRuleName} +$noHashtableFilepath = Join-Path $PSScriptRoot "TestBadModule\NoHashtable.psd1" Describe "MissingRequiredFieldModuleManifest" { BeforeAll { - Import-Module (Join-Path $directory "PSScriptAnalyzerTestHelper.psm1") -Force + Import-Module (Join-Path $PSScriptRoot "PSScriptAnalyzerTestHelper.psm1") -Force } AfterAll{ @@ -55,32 +54,32 @@ Describe "MissingRequiredFieldModuleManifest" { Context "Validate the contents of a .psd1 file" { It "detects a valid module manifest file" { - $filepath = Join-Path $directory "TestManifest/ManifestGood.psd1" + $filepath = Join-Path $PSScriptRoot "TestManifest/ManifestGood.psd1" [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::IsModuleManifest($filepath, [version]"5.0.0") | Should -BeTrue } It "detects a .psd1 file which is not module manifest" { - $filepath = Join-Path $directory "TestManifest/PowerShellDataFile.psd1" + $filepath = Join-Path $PSScriptRoot "TestManifest/PowerShellDataFile.psd1" [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::IsModuleManifest($filepath, [version]"5.0.0") | Should -BeFalse } It "detects valid module manifest file for PSv5" { - $filepath = Join-Path $directory "TestManifest/ManifestGoodPsv5.psd1" + $filepath = Join-Path $PSScriptRoot "TestManifest/ManifestGoodPsv5.psd1" [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::IsModuleManifest($filepath, [version]"5.0.0") | Should -BeTrue } It "does not validate PSv5 module manifest file for PSv3 check" { - $filepath = Join-Path $directory "TestManifest/ManifestGoodPsv5.psd1" + $filepath = Join-Path $PSScriptRoot "TestManifest/ManifestGoodPsv5.psd1" [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::IsModuleManifest($filepath, [version]"3.0.0") | Should -BeFalse } It "detects valid module manifest file for PSv4" { - $filepath = Join-Path $directory "TestManifest/ManifestGoodPsv4.psd1" + $filepath = Join-Path $PSScriptRoot "TestManifest/ManifestGoodPsv4.psd1" [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::IsModuleManifest($filepath, [version]"4.0.0") | Should -BeTrue } It "detects valid module manifest file for PSv3" { - $filepath = Join-Path $directory "TestManifest/ManifestGoodPsv3.psd1" + $filepath = Join-Path $PSScriptRoot "TestManifest/ManifestGoodPsv3.psd1" [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::IsModuleManifest($filepath, [version]"3.0.0") | Should -BeTrue } } @@ -88,7 +87,7 @@ Describe "MissingRequiredFieldModuleManifest" { Context "When given a non module manifest file" { It "does not flag a PowerShell data file" { Invoke-ScriptAnalyzer ` - -Path "$directory/TestManifest/PowerShellDataFile.psd1" ` + -Path "$PSScriptRoot/TestManifest/PowerShellDataFile.psd1" ` -IncludeRule "PSMissingModuleManifestField" ` -OutVariable ruleViolation $ruleViolation.Count | Should -Be 0 diff --git a/Tests/Rules/AvoidUserNameAndPasswordParams.tests.ps1 b/Tests/Rules/AvoidUserNameAndPasswordParams.tests.ps1 index b499205f9..7b3c966e8 100644 --- a/Tests/Rules/AvoidUserNameAndPasswordParams.tests.ps1 +++ b/Tests/Rules/AvoidUserNameAndPasswordParams.tests.ps1 @@ -1,9 +1,8 @@  $violationMessage = "Function 'TestFunction1' has both Username and Password parameters. Either set the type of the Password parameter to SecureString or replace the Username and Password parameters with a Credential parameter of type PSCredential. If using a Credential parameter in PowerShell 4.0 or earlier, please define a credential transformation attribute after the PSCredential type attribute." $violationName = "PSAvoidUsingUserNameAndPasswordParams" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidUserNameAndPasswordParams.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidUserNameAndPasswordParamsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUserNameAndPasswordParams.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUserNameAndPasswordParamsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidUserNameAndPasswordParams" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidUsingAlias.tests.ps1 b/Tests/Rules/AvoidUsingAlias.tests.ps1 index 478646c27..cd0ff4a4d 100644 --- a/Tests/Rules/AvoidUsingAlias.tests.ps1 +++ b/Tests/Rules/AvoidUsingAlias.tests.ps1 @@ -1,10 +1,9 @@ $violationMessage = "'cls' is an alias of 'Clear-Host'. Alias can introduce possible problems and make scripts hard to maintain. Please consider changing alias to its full content." $violationName = "PSAvoidUsingCmdletAliases" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory -$violationFilepath = Join-Path $directory 'AvoidUsingAlias.ps1' +$testRootDirectory = Split-Path -Parent $PSScriptRoot +$violationFilepath = Join-Path $PSScriptRoot 'AvoidUsingAlias.ps1' $violations = Invoke-ScriptAnalyzer $violationFilepath | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidUsingAliasNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingAliasNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") @@ -90,7 +89,7 @@ Configuration MyDscConfiguration { It "honors the whitelist provided through settings file" { # even though join-path returns string, if we do not use tostring, then invoke-scriptanalyzer cannot cast it to string type - $settingsFilePath = (Join-Path $directory (Join-Path 'TestSettings' 'AvoidAliasSettings.psd1')).ToString() + $settingsFilePath = (Join-Path $PSScriptRoot (Join-Path 'TestSettings' 'AvoidAliasSettings.psd1')).ToString() $violations = Invoke-ScriptAnalyzer -ScriptDefinition $whiteListTestScriptDef -Settings $settingsFilePath -IncludeRule $violationName $violations.Count | Should -Be 1 } diff --git a/Tests/Rules/AvoidUsingComputerNameHardcoded.tests.ps1 b/Tests/Rules/AvoidUsingComputerNameHardcoded.tests.ps1 index 1c87a8068..3c0fc58a7 100644 --- a/Tests/Rules/AvoidUsingComputerNameHardcoded.tests.ps1 +++ b/Tests/Rules/AvoidUsingComputerNameHardcoded.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = [regex]::Escape("The ComputerName parameter of cmdlet 'Invoke-Command' is hardcoded. This will expose sensitive information about the system if the script is shared.") $violationName = "PSAvoidUsingComputerNameHardcoded" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidUsingComputerNameHardcoded.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidUsingComputerNameHardcodedNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingComputerNameHardcoded.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingComputerNameHardcodedNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidUsingComputerNameHardcoded" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidUsingDeprecatedManifestFields.tests.ps1 b/Tests/Rules/AvoidUsingDeprecatedManifestFields.tests.ps1 index 8ecae2af1..9a04b96d5 100644 --- a/Tests/Rules/AvoidUsingDeprecatedManifestFields.tests.ps1 +++ b/Tests/Rules/AvoidUsingDeprecatedManifestFields.tests.ps1 @@ -1,8 +1,7 @@ $violationName = "PSAvoidUsingDeprecatedManifestFields" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer "$directory\TestBadModule\TestDeprecatedManifestFields.psd1" | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer "$directory\TestGoodModule\TestGoodModule.psd1" | Where-Object {$_.RuleName -eq $violationName} -$noViolations2 = Invoke-ScriptAnalyzer "$directory\TestGoodModule\TestDeprecatedManifestFieldsWithVersion2.psd1" | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer "$PSScriptRoot\TestBadModule\TestDeprecatedManifestFields.psd1" | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer "$PSScriptRoot\TestGoodModule\TestGoodModule.psd1" | Where-Object {$_.RuleName -eq $violationName} +$noViolations2 = Invoke-ScriptAnalyzer "$PSScriptRoot\TestGoodModule\TestDeprecatedManifestFieldsWithVersion2.psd1" | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidUsingDeprecatedManifestFields" { Context "When there are violations" { @@ -24,7 +23,7 @@ Describe "AvoidUsingDeprecatedManifestFields" { Context "When given a non module manifest file" { It "does not flag a PowerShell data file" { Invoke-ScriptAnalyzer ` - -Path "$directory/TestManifest/PowerShellDataFile.psd1" ` + -Path "$PSScriptRoot/TestManifest/PowerShellDataFile.psd1" ` -IncludeRule "PSAvoidUsingDeprecatedManifestFields" ` -OutVariable ruleViolation $ruleViolation.Count | Should -Be 0 diff --git a/Tests/Rules/AvoidUsingInvokeExpression.tests.ps1 b/Tests/Rules/AvoidUsingInvokeExpression.tests.ps1 index dc7e38644..322a52b0a 100644 --- a/Tests/Rules/AvoidUsingInvokeExpression.tests.ps1 +++ b/Tests/Rules/AvoidUsingInvokeExpression.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = "Invoke-Expression is used. Please remove Invoke-Expression from script and find other options instead." $violationName = "PSAvoidUsingInvokeExpression" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidUsingInvokeExpression.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidConvertToSecureStringWithPlainTextNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingInvokeExpression.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidConvertToSecureStringWithPlainTextNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "AvoidUsingInvokeExpression" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidUsingPlainTextForPassword.tests.ps1 b/Tests/Rules/AvoidUsingPlainTextForPassword.tests.ps1 index 44a83d1a0..2824a8088 100644 --- a/Tests/Rules/AvoidUsingPlainTextForPassword.tests.ps1 +++ b/Tests/Rules/AvoidUsingPlainTextForPassword.tests.ps1 @@ -1,10 +1,9 @@ $violationMessage = [regex]::Escape("Parameter '`$password' should use SecureString, otherwise this will expose sensitive information. See ConvertTo-SecureString for more information.") $violationName = "PSAvoidUsingPlainTextForPassword" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violationFilepath = Join-Path $directory 'AvoidUsingPlainTextForPassword.ps1' +$violationFilepath = Join-Path $PSScriptRoot 'AvoidUsingPlainTextForPassword.ps1' $violations = Invoke-ScriptAnalyzer $violationFilepath | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidUsingPlainTextForPasswordNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} -Import-Module (Join-Path $directory "PSScriptAnalyzerTestHelper.psm1") +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingPlainTextForPasswordNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +Import-Module (Join-Path $PSScriptRoot "PSScriptAnalyzerTestHelper.psm1") Describe "AvoidUsingPlainTextForPassword" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidUsingReservedCharNames.tests.ps1 b/Tests/Rules/AvoidUsingReservedCharNames.tests.ps1 index 1b6a32b90..4321c97f9 100644 --- a/Tests/Rules/AvoidUsingReservedCharNames.tests.ps1 +++ b/Tests/Rules/AvoidUsingReservedCharNames.tests.ps1 @@ -1,8 +1,7 @@ $reservedCharMessage = "The cmdlet 'Use-#Reserved' uses a reserved char in its name." $reservedCharName = "PSReservedCmdletChar" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidUsingReservedCharNames.ps1 | Where-Object {$_.RuleName -eq $reservedCharName} -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $reservedCharName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingReservedCharNames.ps1 | Where-Object {$_.RuleName -eq $reservedCharName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $reservedCharName} Describe "Avoid Using Reserved Char" { Context "When there are violations" { diff --git a/Tests/Rules/AvoidUsingWMICmdlet.tests.ps1 b/Tests/Rules/AvoidUsingWMICmdlet.tests.ps1 index b367f11fe..688707121 100644 --- a/Tests/Rules/AvoidUsingWMICmdlet.tests.ps1 +++ b/Tests/Rules/AvoidUsingWMICmdlet.tests.ps1 @@ -1,8 +1,7 @@ $WMIRuleName = "PSAvoidUsingWMICmdlet" $violationMessage = "File 'AvoidUsingWMICmdlet.ps1' uses WMI cmdlet. For PowerShell 3.0 and above, use CIM cmdlet which perform the same tasks as the WMI cmdlets. The CIM cmdlets comply with WS-Management (WSMan) standards and with the Common Information Model (CIM) standard, which enables the cmdlets to use the same techniques to manage Windows computers and those running other operating systems." -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidUsingWMICmdlet.ps1 -IncludeRule $WMIRuleName -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidUsingWMICmdletNoViolations.ps1 -IncludeRule $WMIRuleName +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingWMICmdlet.ps1 -IncludeRule $WMIRuleName +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingWMICmdletNoViolations.ps1 -IncludeRule $WMIRuleName Describe "AvoidUsingWMICmdlet" { Context "Script contains references to WMI cmdlets - Violation" { @@ -11,7 +10,7 @@ Describe "AvoidUsingWMICmdlet" { } It "has the correct description message for WMI rule violation" { - $violations[0].Message | Should -Be $violationMessage + $violations[0].Message | Should -Be $violationMessage } } diff --git a/Tests/Rules/AvoidUsingWriteHost.tests.ps1 b/Tests/Rules/AvoidUsingWriteHost.tests.ps1 index bfb8977d6..947328cdd 100644 --- a/Tests/Rules/AvoidUsingWriteHost.tests.ps1 +++ b/Tests/Rules/AvoidUsingWriteHost.tests.ps1 @@ -1,9 +1,8 @@ Set-Alias ctss ConvertTo-SecureString $writeHostMessage = [Regex]::Escape("File 'AvoidUsingWriteHost.ps1' uses Write-Host. Avoid using Write-Host because it might not work in all hosts, does not work when there is no host, and (prior to PS 5.0) cannot be suppressed, captured, or redirected. Instead, use Write-Output, Write-Verbose, or Write-Information.") $writeHostName = "PSAvoidUsingWriteHost" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\AvoidUsingWriteHost.ps1 | Where-Object {$_.RuleName -eq $writeHostName} -$noViolations = Invoke-ScriptAnalyzer $directory\AvoidUsingWriteHostNoViolations.ps1 | Where-Object {$_.RuleName -eq $clearHostName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingWriteHost.ps1 | Where-Object {$_.RuleName -eq $writeHostName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\AvoidUsingWriteHostNoViolations.ps1 | Where-Object {$_.RuleName -eq $clearHostName} Describe "AvoidUsingWriteHost" { Context "When there are violations" { diff --git a/Tests/Rules/DscExamplesPresent.tests.ps1 b/Tests/Rules/DscExamplesPresent.tests.ps1 index 7436d2b77..c8f52dd85 100644 --- a/Tests/Rules/DscExamplesPresent.tests.ps1 +++ b/Tests/Rules/DscExamplesPresent.tests.ps1 @@ -1,12 +1,11 @@ -$currentPath = Split-Path -Parent $MyInvocation.MyCommand.Path $ruleName = "PSDSCDscExamplesPresent" if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { Describe "DscExamplesPresent rule in class based resource" { - $examplesPath = "$currentPath\DSCResourceModule\DSCResources\MyDscResource\Examples" - $classResourcePath = "$currentPath\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1" + $examplesPath = "$PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\Examples" + $classResourcePath = "$PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1" Context "When examples absent" { @@ -39,8 +38,8 @@ if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { Describe "DscExamplesPresent rule in regular (non-class) based resource" { - $examplesPath = "$currentPath\DSCResourceModule\Examples" - $resourcePath = "$currentPath\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1" + $examplesPath = "$PSScriptRoot\DSCResourceModule\Examples" + $resourcePath = "$PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1" Context "When examples absent" { diff --git a/Tests/Rules/DscTestsPresent.tests.ps1 b/Tests/Rules/DscTestsPresent.tests.ps1 index d90a70f3f..d9af9da94 100644 --- a/Tests/Rules/DscTestsPresent.tests.ps1 +++ b/Tests/Rules/DscTestsPresent.tests.ps1 @@ -1,12 +1,11 @@ -$currentPath = Split-Path -Parent $MyInvocation.MyCommand.Path $ruleName = "PSDSCDscTestsPresent" if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { Describe "DscTestsPresent rule in class based resource" { - $testsPath = "$currentPath\DSCResourceModule\DSCResources\MyDscResource\Tests" - $classResourcePath = "$currentPath\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1" + $testsPath = "$PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\Tests" + $classResourcePath = "$PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1" Context "When tests absent" { @@ -39,8 +38,8 @@ if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { Describe "DscTestsPresent rule in regular (non-class) based resource" { - $testsPath = "$currentPath\DSCResourceModule\Tests" - $resourcePath = "$currentPath\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1" + $testsPath = "$PSScriptRoot\DSCResourceModule\Tests" + $resourcePath = "$PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1" Context "When tests absent" { diff --git a/Tests/Rules/MisleadingBacktick.tests.ps1 b/Tests/Rules/MisleadingBacktick.tests.ps1 index e4cd97195..b640e8b04 100644 --- a/Tests/Rules/MisleadingBacktick.tests.ps1 +++ b/Tests/Rules/MisleadingBacktick.tests.ps1 @@ -1,16 +1,15 @@ $writeHostName = "PSMisleadingBacktick" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violationFilepath = Join-Path $directory 'MisleadingBacktick.ps1' +$violationFilepath = Join-Path $PSScriptRoot 'MisleadingBacktick.ps1' $violations = Invoke-ScriptAnalyzer $violationFilepath | Where-Object {$_.RuleName -eq $writeHostName} -$noViolations = Invoke-ScriptAnalyzer $directory\NoMisleadingBacktick.ps1 | Where-Object {$_.RuleName -eq $clearHostName} -Import-Module (Join-Path $directory "PSScriptAnalyzerTestHelper.psm1") +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\NoMisleadingBacktick.ps1 | Where-Object {$_.RuleName -eq $clearHostName} +Import-Module (Join-Path $PSScriptRoot "PSScriptAnalyzerTestHelper.psm1") Describe "Avoid Misleading Backticks" { Context "When there are violations" { It "has 5 misleading backtick violations" { $violations.Count | Should -Be 5 } - + It "suggests correction" { Test-CorrectionExtent $violationFilepath $violations[0] 1 ' ' '' Test-CorrectionExtent $violationFilepath $violations[1] 1 ' ' '' diff --git a/Tests/Rules/PSCredentialType.tests.ps1 b/Tests/Rules/PSCredentialType.tests.ps1 index 344bfa5fb..fb339d29d 100644 --- a/Tests/Rules/PSCredentialType.tests.ps1 +++ b/Tests/Rules/PSCredentialType.tests.ps1 @@ -1,11 +1,10 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') $violationMessage = "The Credential parameter in 'Credential' must be of type PSCredential. For PowerShell 4.0 and earlier, please define a credential transformation attribute, e.g. [System.Management.Automation.Credential()], after the PSCredential type attribute." $violationName = "PSUsePSCredentialType" -$violations = Invoke-ScriptAnalyzer $directory\PSCredentialType.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\PSCredentialTypeNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\PSCredentialType.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\PSCredentialTypeNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "PSCredentialType" { Context "When there are violations" { diff --git a/Tests/Rules/PlaceCloseBrace.tests.ps1 b/Tests/Rules/PlaceCloseBrace.tests.ps1 index df1be8812..94c65473f 100644 --- a/Tests/Rules/PlaceCloseBrace.tests.ps1 +++ b/Tests/Rules/PlaceCloseBrace.tests.ps1 @@ -1,6 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") $ruleConfiguration = @{ diff --git a/Tests/Rules/PossibleIncorrectComparisonWithNull.tests.ps1 b/Tests/Rules/PossibleIncorrectComparisonWithNull.tests.ps1 index 5c9f45553..ff00080d8 100644 --- a/Tests/Rules/PossibleIncorrectComparisonWithNull.tests.ps1 +++ b/Tests/Rules/PossibleIncorrectComparisonWithNull.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = [regex]::Escape('$null should be on the left side of equality comparisons.') $violationName = "PSPossibleIncorrectComparisonWithNull" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\PossibleIncorrectComparisonWithNull.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\PossibleIncorrectComparisonWithNullNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\PossibleIncorrectComparisonWithNull.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\PossibleIncorrectComparisonWithNullNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "PossibleIncorrectComparisonWithNull" { Context "When there are violations" { diff --git a/Tests/Rules/ProvideCommentHelp.tests.ps1 b/Tests/Rules/ProvideCommentHelp.tests.ps1 index 51dd2137f..6ab2504e9 100644 --- a/Tests/Rules/ProvideCommentHelp.tests.ps1 +++ b/Tests/Rules/ProvideCommentHelp.tests.ps1 @@ -1,6 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") $violationMessage = "The cmdlet 'Comment' does not have a help comment." @@ -18,13 +16,13 @@ $settings = @{ Rules = @{ PSProvideCommentHelp = $ruleSettings } } -$violations = Invoke-ScriptAnalyzer $directory\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { - $dscViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} + $dscViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} } -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} function Test-Correction { param($scriptDef, $expectedCorrection, $settings) diff --git a/Tests/Rules/ReturnCorrectTypesForDSCFunctions.tests.ps1 b/Tests/Rules/ReturnCorrectTypesForDSCFunctions.tests.ps1 index 8d85f81b6..78b5f91e2 100644 --- a/Tests/Rules/ReturnCorrectTypesForDSCFunctions.tests.ps1 +++ b/Tests/Rules/ReturnCorrectTypesForDSCFunctions.tests.ps1 @@ -1,14 +1,13 @@ $violationMessageDSCResource = "Test-TargetResource function in DSC Resource should return object of type System.Boolean instead of System.Collections.Hashtable" $violationMessageDSCClass = "Get function in DSC Class FileResource should return object of type FileResource instead of type System.Collections.Hashtable" $violationName = "PSDSCReturnCorrectTypesForDSCFunctions" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { - $classViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\BadDscResource\BadDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} - $noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} + $classViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\BadDscResource\BadDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} + $noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} } Describe "ReturnCorrectTypesForDSCFunctions" { diff --git a/Tests/Rules/UseBOMForUnicodeEncodedFile.tests.ps1 b/Tests/Rules/UseBOMForUnicodeEncodedFile.tests.ps1 index 0aa479ce1..ba992d43e 100644 --- a/Tests/Rules/UseBOMForUnicodeEncodedFile.tests.ps1 +++ b/Tests/Rules/UseBOMForUnicodeEncodedFile.tests.ps1 @@ -1,11 +1,10 @@ $violationMessageOne = "Missing BOM encoding for non-ASCII encoded file 'BOMAbsent_UTF16EncodedScript.ps1'" $violationMessageTwo = "Missing BOM encoding for non-ASCII encoded file 'BOMAbsent_UnknownEncodedScript.ps1'" $violationName = "PSUseBOMForUnicodeEncodedFile" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violationsOne = Invoke-ScriptAnalyzer "$directory\TestFiles\BOMAbsent_UTF16EncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} -$violationsTwo = Invoke-ScriptAnalyzer "$directory\TestFiles\BOMAbsent_UnknownEncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} -$noViolationsOne = Invoke-ScriptAnalyzer "$directory\TestFiles\BOMPresent_UTF16EncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} -$noViolationsTwo = Invoke-ScriptAnalyzer "$directory\TestFiles\BOMAbsent_ASCIIEncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} +$violationsOne = Invoke-ScriptAnalyzer "$PSScriptRoot\TestFiles\BOMAbsent_UTF16EncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} +$violationsTwo = Invoke-ScriptAnalyzer "$PSScriptRoot\TestFiles\BOMAbsent_UnknownEncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} +$noViolationsOne = Invoke-ScriptAnalyzer "$PSScriptRoot\TestFiles\BOMPresent_UTF16EncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} +$noViolationsTwo = Invoke-ScriptAnalyzer "$PSScriptRoot\TestFiles\BOMAbsent_ASCIIEncodedScript.ps1" | Where-Object {$_.RuleName -eq $violationName} Describe "UseBOMForUnicodeEncodedFile" { Context "When there are violations" { diff --git a/Tests/Rules/UseCmdletCorrectly.tests.ps1 b/Tests/Rules/UseCmdletCorrectly.tests.ps1 index 1e2ac6633..207036eb1 100644 --- a/Tests/Rules/UseCmdletCorrectly.tests.ps1 +++ b/Tests/Rules/UseCmdletCorrectly.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = "Cmdlet 'Write-Warning' may be used incorrectly. Please check that all mandatory parameters are supplied." $violationName = "PSUseCmdletCorrectly" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\UseCmdletCorrectly.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\UseCmdletCorrectly.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "UseCmdletCorrectly" { Context "When there are violations" { diff --git a/Tests/Rules/UseCompatibleCmdlets.tests.ps1 b/Tests/Rules/UseCompatibleCmdlets.tests.ps1 index 41ff3d420..d4db68502 100644 --- a/Tests/Rules/UseCompatibleCmdlets.tests.ps1 +++ b/Tests/Rules/UseCompatibleCmdlets.tests.ps1 @@ -1,7 +1,6 @@ $ruleName = "PSUseCompatibleCmdlets" -$directory = Split-Path $MyInvocation.MyCommand.Path -Parent -$testRootDirectory = Split-Path -Parent $directory -$ruleTestDirectory = Join-Path $directory 'UseCompatibleCmdlets' +$testRootDirectory = Split-Path -Parent $PSScriptRoot +$ruleTestDirectory = Join-Path $PSScriptRoot 'UseCompatibleCmdlets' Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') diff --git a/Tests/Rules/UseConsistentIndentation.tests.ps1 b/Tests/Rules/UseConsistentIndentation.tests.ps1 index 2e9a03fd7..06dbea290 100644 --- a/Tests/Rules/UseConsistentIndentation.tests.ps1 +++ b/Tests/Rules/UseConsistentIndentation.tests.ps1 @@ -1,6 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") diff --git a/Tests/Rules/UseConsistentWhitespace.tests.ps1 b/Tests/Rules/UseConsistentWhitespace.tests.ps1 index 0d1441384..23bf18350 100644 --- a/Tests/Rules/UseConsistentWhitespace.tests.ps1 +++ b/Tests/Rules/UseConsistentWhitespace.tests.ps1 @@ -1,6 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") $ruleName = "PSUseConsistentWhitespace" diff --git a/Tests/Rules/UseDSCResourceFunctions.tests.ps1 b/Tests/Rules/UseDSCResourceFunctions.tests.ps1 index 45ebef3d9..f88801a21 100644 --- a/Tests/Rules/UseDSCResourceFunctions.tests.ps1 +++ b/Tests/Rules/UseDSCResourceFunctions.tests.ps1 @@ -2,14 +2,13 @@ $violationMessage = "Missing 'Get-TargetResource' function. DSC Resource must implement Get, Set and Test-TargetResource functions." $classViolationMessage = "Missing 'Set' function. DSC Class must implement Get, Set and Test functions." $violationName = "PSDSCStandardDSCFunctionsInResource" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { - $classViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\BadDscResource\BadDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} - $noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} + $classViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\BadDscResource\BadDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} + $noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} } Describe "StandardDSCFunctionsInResource" { diff --git a/Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1 b/Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1 index 43775b36d..c81fc74f7 100644 --- a/Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1 +++ b/Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1 @@ -1,12 +1,10 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') $violationMessage = "The variable 'declaredVar2' is assigned but never used." $violationName = "PSUseDeclaredVarsMoreThanAssignments" -$violations = Invoke-ScriptAnalyzer $directory\UseDeclaredVarsMoreThanAssignments.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\UseDeclaredVarsMoreThanAssignmentsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\UseDeclaredVarsMoreThanAssignments.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\UseDeclaredVarsMoreThanAssignmentsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "UseDeclaredVarsMoreThanAssignments" { Context "When there are violations" { diff --git a/Tests/Rules/UseIdenticalMandatoryParametersForDSC.tests.ps1 b/Tests/Rules/UseIdenticalMandatoryParametersForDSC.tests.ps1 index 6d49eb4b3..d8e96c709 100644 --- a/Tests/Rules/UseIdenticalMandatoryParametersForDSC.tests.ps1 +++ b/Tests/Rules/UseIdenticalMandatoryParametersForDSC.tests.ps1 @@ -1,6 +1,5 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path $ruleName = 'PSDSCUseIdenticalMandatoryParametersForDSC' -$resourceBasepath = "$directory\DSCResourceModule\DSCResources" +$resourceBasepath = "$PSScriptRoot\DSCResourceModule\DSCResources" $badResourceFilepath = [System.IO.Path]::Combine( $resourceBasepath, 'MSFT_WaitForAnyNoIdenticalMandatoryParameter', diff --git a/Tests/Rules/UseIdenticalParametersDSC.tests.ps1 b/Tests/Rules/UseIdenticalParametersDSC.tests.ps1 index 55e8e27d4..36250cd04 100644 --- a/Tests/Rules/UseIdenticalParametersDSC.tests.ps1 +++ b/Tests/Rules/UseIdenticalParametersDSC.tests.ps1 @@ -1,12 +1,11 @@ $violationMessage = "The Test and Set-TargetResource functions of DSC Resource must have the same parameters." $violationName = "PSDSCUseIdenticalParametersForDSC" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { - $noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} + $noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} } Describe "UseIdenticalParametersDSC" { diff --git a/Tests/Rules/UseOutputTypeCorrectly.tests.ps1 b/Tests/Rules/UseOutputTypeCorrectly.tests.ps1 index 92ab67182..8674643d5 100644 --- a/Tests/Rules/UseOutputTypeCorrectly.tests.ps1 +++ b/Tests/Rules/UseOutputTypeCorrectly.tests.ps1 @@ -1,14 +1,13 @@ $violationMessage = "The cmdlet 'Verb-Files' returns an object of type 'System.Collections.Hashtable' but this type is not declared in the OutputType attribute." $violationName = "PSUseOutputTypeCorrectly" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} if ($PSVersionTable.PSVersion -ge [Version]'5.0.0') { - $dscViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} + $dscViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} } -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "UseOutputTypeCorrectly" { Context "When there are violations" { diff --git a/Tests/Rules/UseShouldProcessCorrectly.tests.ps1 b/Tests/Rules/UseShouldProcessCorrectly.tests.ps1 index cec228f47..d870c69ae 100644 --- a/Tests/Rules/UseShouldProcessCorrectly.tests.ps1 +++ b/Tests/Rules/UseShouldProcessCorrectly.tests.ps1 @@ -1,12 +1,10 @@ $violationMessage = "'Verb-Files' has the ShouldProcess attribute but does not call ShouldProcess/ShouldContinue." $violationName = "PSShouldProcess" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') -$violations = Invoke-ScriptAnalyzer $directory\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\BadCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 | Where-Object {$_.RuleName -eq $violationName} $IsV3OrV4 = (Test-PSVersionV3) -or (Test-PSVersionV4) Describe "UseShouldProcessCorrectly" { diff --git a/Tests/Rules/UseShouldProcessForStateChangingFunctions.tests.ps1 b/Tests/Rules/UseShouldProcessForStateChangingFunctions.tests.ps1 index 8d8ae23e4..ed377f1c0 100644 --- a/Tests/Rules/UseShouldProcessForStateChangingFunctions.tests.ps1 +++ b/Tests/Rules/UseShouldProcessForStateChangingFunctions.tests.ps1 @@ -1,8 +1,7 @@ $violationMessage = "Function 'Set-MyObject' has verb that could change system state. Therefore, the function has to support 'ShouldProcess'" $violationName = "PSUseShouldProcessForStateChangingFunctions" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\UseShouldProcessForStateChangingFunctions.ps1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\UseShouldProcessForStateChangingFunctionsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\UseShouldProcessForStateChangingFunctions.ps1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\UseShouldProcessForStateChangingFunctionsNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName} Describe "It checks UseShouldProcess is enabled when there are state changing verbs in the function names" { Context "When function name has state changing verb" { diff --git a/Tests/Rules/UseSingularNounsReservedVerbs.tests.ps1 b/Tests/Rules/UseSingularNounsReservedVerbs.tests.ps1 index e16ee5cc2..7bd3e432f 100644 --- a/Tests/Rules/UseSingularNounsReservedVerbs.tests.ps1 +++ b/Tests/Rules/UseSingularNounsReservedVerbs.tests.ps1 @@ -1,20 +1,16 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory -Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') - $nounViolationMessage = "The cmdlet 'Verb-Files' uses a plural noun. A singular noun should be used instead." $verbViolationMessage = "The cmdlet 'Verb-Files' uses an unapproved verb." $nounViolationName = "PSUseSingularNouns" $verbViolationName = "PSUseApprovedVerbs" -$violations = Invoke-ScriptAnalyzer $directory\BadCmdlet.ps1 +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\BadCmdlet.ps1 $nounViolations = $violations | Where-Object {$_.RuleName -eq $nounViolationName} $verbViolations = $violations | Where-Object {$_.RuleName -eq $verbViolationName} -$noViolations = Invoke-ScriptAnalyzer $directory\GoodCmdlet.ps1 +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\GoodCmdlet.ps1 $nounNoViolations = $noViolations | Where-Object {$_.RuleName -eq $nounViolationName} $verbNoViolations = $noViolations | Where-Object {$_.RuleName -eq $verbViolationName} # this rule doesn't exist in the non desktop version of PSScriptAnalyzer -if (-not (Test-PSEditionCoreCLR)) +if (-not $IsCoreCLR) { Describe "UseSingularNouns" { Context "When there are violations" { diff --git a/Tests/Rules/UseSupportsShouldProcess.tests.ps1 b/Tests/Rules/UseSupportsShouldProcess.tests.ps1 index 91c9865b6..ba43c06b0 100644 --- a/Tests/Rules/UseSupportsShouldProcess.tests.ps1 +++ b/Tests/Rules/UseSupportsShouldProcess.tests.ps1 @@ -1,6 +1,4 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory - +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1") $settings = @{ diff --git a/Tests/Rules/UseToExportFieldsInManifest.tests.ps1 b/Tests/Rules/UseToExportFieldsInManifest.tests.ps1 index 5285bd6ac..3edb6b54f 100644 --- a/Tests/Rules/UseToExportFieldsInManifest.tests.ps1 +++ b/Tests/Rules/UseToExportFieldsInManifest.tests.ps1 @@ -1,8 +1,7 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$testRootDirectory = Split-Path -Parent $directory +$testRootDirectory = Split-Path -Parent $PSScriptRoot Import-Module (Join-Path $testRootDirectory 'PSScriptAnalyzerTestHelper.psm1') -$testManifestPath = Join-Path $directory "TestManifest" +$testManifestPath = Join-Path $PSScriptRoot "TestManifest" $testManifestBadFunctionsWildcardPath = "ManifestBadFunctionsWildcard.psd1" $testManifestBadFunctionsWildcardInArrayPath = "ManifestBadFunctionsWildcardInArray.psd1" $testManifestBadFunctionsNullPath = "ManifestBadFunctionsNull.psd1" @@ -12,7 +11,7 @@ $testManifestBadVariablesWildcardPath = "ManifestBadVariablesWildcard.psd1" $testManifestBadAllPath = "ManifestBadAll.psd1" $testManifestGoodPath = "ManifestGood.psd1" $testManifestInvalidPath = "ManifestInvalid.psd1" -Import-Module (Join-Path $directory "PSScriptAnalyzerTestHelper.psm1") +Import-Module (Join-Path $PSScriptRoot "PSScriptAnalyzerTestHelper.psm1") Function Run-PSScriptAnalyzerRule { @@ -82,7 +81,7 @@ Describe "UseManifestExportFields" { $results[0].Extent.Text | Should -Be "'*'" } - It "suggests corrections for AliasesToExport with wildcard" -pending:($IsCoreClr) { + It "suggests corrections for AliasesToExport with wildcard" -pending:($IsCoreCLR) { $violations = Run-PSScriptAnalyzerRule $testManifestBadAliasesWildcardPath $violationFilepath = Join-path $testManifestPath $testManifestBadAliasesWildcardPath Test-CorrectionExtent $violationFilepath $violations[0] 1 "'*'" "@('gbar', 'gfoo')" @@ -104,7 +103,7 @@ Describe "UseManifestExportFields" { Context "When given a non module manifest file" { It "does not flag a PowerShell data file" { Invoke-ScriptAnalyzer ` - -Path "$directory/TestManifest/PowerShellDataFile.psd1" ` + -Path "$PSScriptRoot/TestManifest/PowerShellDataFile.psd1" ` -IncludeRule "PSUseToExportFieldsInManifest" ` -OutVariable ruleViolation $ruleViolation.Count | Should -Be 0 diff --git a/Tests/Rules/UseUTF8EncodingForHelpFile.tests.ps1 b/Tests/Rules/UseUTF8EncodingForHelpFile.tests.ps1 index 1f99549d5..6404dcab8 100644 --- a/Tests/Rules/UseUTF8EncodingForHelpFile.tests.ps1 +++ b/Tests/Rules/UseUTF8EncodingForHelpFile.tests.ps1 @@ -1,11 +1,10 @@ -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -Describe "UseUTF8EncodingForHelpFile" { +Describe "UseUTF8EncodingForHelpFile" { BeforeAll { $violationMessage = "File about_utf16.help.txt has to use UTF8 instead of System.Text.UTF32Encoding encoding because it is a powershell help file." $violationName = "PSUseUTF8EncodingForHelpFile" - $violations = Invoke-ScriptAnalyzer $directory\about_utf16.help.txt | Where-Object {$_.RuleName -eq $violationName} - $noViolations = Invoke-ScriptAnalyzer $directory\about_utf8.help.txt | Where-Object {$_.RuleName -eq $violationName} - $notHelpFileViolations = Invoke-ScriptAnalyzer $directory\utf16.txt | Where-Object {$_.RuleName -eq $violationName} + $violations = Invoke-ScriptAnalyzer $PSScriptRoot\about_utf16.help.txt | Where-Object {$_.RuleName -eq $violationName} + $noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\about_utf8.help.txt | Where-Object {$_.RuleName -eq $violationName} + $notHelpFileViolations = Invoke-ScriptAnalyzer $PSScriptRoot\utf16.txt | Where-Object {$_.RuleName -eq $violationName} } Context "When there are violations" { diff --git a/Tests/Rules/UseVerboseMessageInDSCResource.Tests.ps1 b/Tests/Rules/UseVerboseMessageInDSCResource.Tests.ps1 index cb5111ed8..c7440c37a 100644 --- a/Tests/Rules/UseVerboseMessageInDSCResource.Tests.ps1 +++ b/Tests/Rules/UseVerboseMessageInDSCResource.Tests.ps1 @@ -1,9 +1,8 @@ $violationMessage = "There is no call to Write-Verbose in DSC function 'Test-TargetResource'. If you are using Write-Verbose in a helper function, suppress this rule application." $violationName = "PSDSCUseVerboseMessageInDSCResource" -$directory = Split-Path -Parent $MyInvocation.MyCommand.Path -$violations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} -$noViolations = Invoke-ScriptAnalyzer $directory\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} -$noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $directory\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} +$violations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAll\MSFT_WaitForAll.psm1 | Where-Object {$_.RuleName -eq $violationName} +$noViolations = Invoke-ScriptAnalyzer $PSScriptRoot\DSCResourceModule\DSCResources\MSFT_WaitForAny\MSFT_WaitForAny.psm1 | Where-Object {$_.RuleName -eq $violationName} +$noClassViolations = Invoke-ScriptAnalyzer -ErrorAction SilentlyContinue $PSScriptRoot\DSCResourceModule\DSCResources\MyDscResource\MyDscResource.psm1 | Where-Object {$_.RuleName -eq $violationName} Describe "UseVerboseMessageInDSCResource" { Context "When there are violations" {