From 33a8db3e273c5059fffe46d9791a195a9d71bde9 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 15:47:58 +0000 Subject: [PATCH 01/33] Added Get-FileContentTest and fixes to function --- .../Get-FileContent.ps1 | 98 ++++++++++---- Source/Tests/Unit/Get-FileContent.Tests.ps1 | 127 ++++++++++++++++++ 2 files changed, 197 insertions(+), 28 deletions(-) diff --git a/Source/PSQualityCheck.Functions/Get-FileContent.ps1 b/Source/PSQualityCheck.Functions/Get-FileContent.ps1 index e26ad8e..0623f1f 100644 --- a/Source/PSQualityCheck.Functions/Get-FileContent.ps1 +++ b/Source/PSQualityCheck.Functions/Get-FileContent.ps1 @@ -19,55 +19,97 @@ function Get-FileContent { [string]$Path ) - $fileContent = Get-Content -Path $Path + try { - $parserErrors = $null + $fileContent = Get-Content -Path $Path - # If the file content is null (an empty file) then generate an empty parsedFileFunctions array to allow the function to complete - if ([string]::IsNullOrEmpty($fileContent)) { - $parsedFileFunctions = @() - } - else { - $parsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($fileContent, [ref]$parserErrors) - } + $parserErrors = $null + + # If the file content is null (an empty file) then generate an empty parsedFileFunctions array to allow the function to complete + if ([string]::IsNullOrEmpty($fileContent)) { + $parsedFileFunctions = @() + } + else { + $parsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($fileContent, [ref]$parserErrors) + } + + # Create an array of where each reference of the keyword 'function' is + $parsedFunctions = ($parsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) + + if ($parsedFunctions.Count -gt 1) { + throw "Too many functions in file, file is invalid" + } - # Create an array of where each reference of the keyword 'function' is - $parsedFunctions = ($parsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) + if ($parsedFunctions.Count -eq 1) { - if ($parsedFunctions) { + if ($fileContent.Count -gt 1) { - foreach ($function in $parsedFunctions) { + foreach ($function in $parsedFunctions) { - $startLine = ($function.StartLine) + $startLine = ($function.StartLine) - for ($line = $fileContent.Count; $line -gt $function.StartLine; $line--) { + for ($line = $fileContent.Count; $line -gt $function.StartLine; $line--) { - if ($fileContent[$line] -like "}") { + if ($fileContent[$line] -like "*}*") { - $endLine = $line - break + $endLine = $line + break + + } + + } + + # Output the lines of the function to the FunctionOutputFile + for ($line = $startLine; $line -lt $endLine; $line++) { + + $parsedFileContent += $fileContent[$line] + + if ($line -ne ($fileContent.Count - 1)) { + $parsedFileContent += "`r`n" + } + + } } } + else { - # Output the lines of the function to the FunctionOutputFile - for ($line = $startLine; $line -lt $endLine; $line++) { - $parsedFileContent += $fileContent[$line] - $parsedFileContent += "`n" - } + # if there is only one line then the content should be on the line between { and } + [int]$startBracket = $fileContent.IndexOf('{') + [int]$endBracket = $fileContent.LastIndexOf('}') + $parsedFileContent = $fileContent.substring($startBracket + 1, $endBracket - 1 - $startBracket) + + } } + else { - } - else { + if ($fileContent.Count -gt 1) { + + for ($line = 0; $line -lt $fileContent.Count; $line++) { + + $parsedFileContent += $fileContent[$line] + + if ($line -ne ($fileContent.Count - 1)) { + $parsedFileContent += "`r`n" + } + + } + + } + else { + + $parsedFileContent = $fileContent + + } - for ($line = 0; $line -lt $fileContent.Count; $line++) { - $parsedFileContent += $fileContent[$line] - $parsedFileContent += "`n" } } + catch { + throw + } return $parsedFileContent diff --git a/Source/Tests/Unit/Get-FileContent.Tests.ps1 b/Source/Tests/Unit/Get-FileContent.Tests.ps1 index e35b3d8..f4b5196 100644 --- a/Source/Tests/Unit/Get-FileContent.Tests.ps1 +++ b/Source/Tests/Unit/Get-FileContent.Tests.ps1 @@ -37,6 +37,133 @@ Describe "Get-FileContent.Tests" { } + It "should pass when Path is valid with no function, empty content in the file" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent = "" + Set-Content -Path $testPath -Value $fileContent + + $parsedFileContent = Get-FileContent -Path $testPath + + ($fileContent -eq $parsedFileContent) | Should -BeTrue + + } + + It "should pass when Path is valid with no function, single-line content in the file" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent = "Write-Host" + Set-Content -Path $testPath -Value $fileContent + + $parsedFileContent = Get-FileContent -Path $testPath + + ($fileContent -eq $parsedFileContent) | Should -BeTrue + + } + + It "should pass when Path is valid with no function, multi-line content in the file" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent = "Write-Host + Write-Host + " + Set-Content -Path $testPath -Value $fileContent + + $parsedFileContent = Get-FileContent -Path $testPath + + ($fileContent -eq $parsedFileContent) | Should -BeTrue + + } + + It "should pass when Path is valid with only one empty function in the file" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent = "function Get-FileContent {}" + $matchContent = "" + Set-Content -Path $testPath -Value $fileContent + + $parsedFileContent = Get-FileContent -Path $testPath + + ($matchContent -eq $parsedFileContent) | Should -BeTrue + + } + + It "should pass when Path is valid with only one single-line function in the file" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent = "function Get-FileContent { Write-Host }" + $matchContent = " Write-Host " + Set-Content -Path $testPath -Value $fileContent + + $parsedFileContent = Get-FileContent -Path $testPath + + ($matchContent -eq $parsedFileContent) | Should -BeTrue + + } + + It "should pass when Path is valid with only one single-line advanced function in the file" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent = "function Get-FileContent { if ($true) { Write-Host } }" + $matchContent = " if ($true) { Write-Host } " + Set-Content -Path $testPath -Value $fileContent + + $parsedFileContent = Get-FileContent -Path $testPath + + ($matchContent -eq $parsedFileContent) | Should -BeTrue + + } + + It "should pass when Path is valid with only one multi-line function in the file" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent1 = "function Get-FileContent { + Write-Host + }" + $matchContent1 = " Write-Host`r`n" + + Set-Content -Path $testPath -Value $fileContent1 + + $parsedFileContent1 = Get-FileContent -Path $testPath + + $fileContent2 = "function Get-FileContent { + if ($true) { + Write-Host + } + }" + $matchContent2 = " if ($true) { + Write-Host + }`r`n" + + Set-Content -Path $testPath -Value $fileContent2 + + $parsedFileContent2 = Get-FileContent -Path $testPath + + ($matchContent1 -eq $parsedFileContent1) | Should -BeTrue + ($matchContent2 -eq $parsedFileContent2) | Should -BeTrue + + } + + It "should throw when Path is valid with two functions in the file" { + + { + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $fileContent = "function Get-FileContent { + Write-Host + } + + function Test-Function { + Write-Host + }" + + Set-Content -Path $testPath -Value $fileContent + + $parsedFileContent = Get-FileContent -Path $testPath + + } | Should -Throw + + } + } } From e2629f77025429baf23b2575c1d37f07145ddcec Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 16:04:36 +0000 Subject: [PATCH 02/33] Fix filenames in unit test --- README.md | 5 +++++ Source/Tests/Unit/Get-FileContent.Tests.ps1 | 16 ++++++++-------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6299a2c..7f5528f 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,11 @@ The quality standards are summarised here: [Quality Standards Summary](https://g [![github pre-release tag](https://img.shields.io/github/v/tag/andrewrdavidson/psqualitycheck?include_prereleases)](https://img.shields.io/github/v/release/andrewrdavidson/PSQualityCheck?include_prereleases) +**Commits** + +[![commits since 1.0.9](https://img.shields.io/github/commits-since/andrewrdavidson/psqualitycheck/1.0.9/main?include_prereleases)](https://github.com/andrewrdavidson/PSQualityCheck/releases/1.0.9) +[![commits since 1.0.10-alpha2](https://img.shields.io/github/commits-since/andrewrdavidson/psqualitycheck/latest/release-1.0.10?include_prereleases)](https://github.com/andrewrdavidson/PSQualityCheck/releases/1.0.10-alpha1) + #### Issues [![open issues](https://img.shields.io/github/issues-raw/andrewrdavidson/psqualitycheck)](https://github.com/andrewrdavidson/PSQualityCheck/issues?q=is%3Aopen+is%3Aissue) [![closed](https://img.shields.io/github/issues-closed-raw/andrewrdavidson/psqualitycheck)](https://github.com/andrewrdavidson/PSQualityCheck/issues?q=is%3Aissue+is%3Aclosed) diff --git a/Source/Tests/Unit/Get-FileContent.Tests.ps1 b/Source/Tests/Unit/Get-FileContent.Tests.ps1 index f4b5196..047f8a3 100644 --- a/Source/Tests/Unit/Get-FileContent.Tests.ps1 +++ b/Source/Tests/Unit/Get-FileContent.Tests.ps1 @@ -39,7 +39,7 @@ Describe "Get-FileContent.Tests" { It "should pass when Path is valid with no function, empty content in the file" { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent = "" Set-Content -Path $testPath -Value $fileContent @@ -51,7 +51,7 @@ Describe "Get-FileContent.Tests" { It "should pass when Path is valid with no function, single-line content in the file" { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent = "Write-Host" Set-Content -Path $testPath -Value $fileContent @@ -63,7 +63,7 @@ Describe "Get-FileContent.Tests" { It "should pass when Path is valid with no function, multi-line content in the file" { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent = "Write-Host Write-Host " @@ -77,7 +77,7 @@ Describe "Get-FileContent.Tests" { It "should pass when Path is valid with only one empty function in the file" { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent = "function Get-FileContent {}" $matchContent = "" Set-Content -Path $testPath -Value $fileContent @@ -90,7 +90,7 @@ Describe "Get-FileContent.Tests" { It "should pass when Path is valid with only one single-line function in the file" { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent = "function Get-FileContent { Write-Host }" $matchContent = " Write-Host " Set-Content -Path $testPath -Value $fileContent @@ -103,7 +103,7 @@ Describe "Get-FileContent.Tests" { It "should pass when Path is valid with only one single-line advanced function in the file" { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent = "function Get-FileContent { if ($true) { Write-Host } }" $matchContent = " if ($true) { Write-Host } " Set-Content -Path $testPath -Value $fileContent @@ -116,7 +116,7 @@ Describe "Get-FileContent.Tests" { It "should pass when Path is valid with only one multi-line function in the file" { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent1 = "function Get-FileContent { Write-Host }" @@ -147,7 +147,7 @@ Describe "Get-FileContent.Tests" { It "should throw when Path is valid with two functions in the file" { { - $testPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' $fileContent = "function Get-FileContent { Write-Host } From e986957174431ca20654c03717c9acdab095ea4f Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 16:39:38 +0000 Subject: [PATCH 03/33] Added Get-FileList test --- Source/Tests/Unit/Get-FileList.Tests.ps1 | 110 +++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/Source/Tests/Unit/Get-FileList.Tests.ps1 b/Source/Tests/Unit/Get-FileList.Tests.ps1 index ae12780..67d625b 100644 --- a/Source/Tests/Unit/Get-FileList.Tests.ps1 +++ b/Source/Tests/Unit/Get-FileList.Tests.ps1 @@ -44,6 +44,116 @@ Describe "Get-FileList.Tests" { } + It "should return one file when checking folder with one matching files" { + + $fileContent = "function Get-FileContent {}" + $testPath1 = Join-Path -Path $TestDrive -ChildPath 'test1.ps1' + Set-Content -Path $testPath1 -Value $fileContent + + $fileList = Get-FileList -Path $TestDrive -Extension ".ps1" + + Remove-Item -Path $testPath1 -Force + + $fileList.Count | Should -BeExactly 1 + + } + + It "should return two files when checking folder with two matching files" { + + $fileContent = "function Get-FileContent {}" + $testPath1 = Join-Path -Path $TestDrive -ChildPath 'test1.ps1' + Set-Content -Path $testPath1 -Value $fileContent + $testPath2 = Join-Path -Path $TestDrive -ChildPath 'test2.ps1' + Set-Content -Path $testPath2 -Value $fileContent + + $fileList = Get-FileList -Path $TestDrive -Extension ".ps1" + + Remove-Item -Path $testPath1 -Force + Remove-Item -Path $testPath2 -Force + + $fileList.Count | Should -BeExactly 2 + + } + + It "should return no files when checking folder with non-matching files" { + + $fileContent = "function Get-FileContent {}" + $testPath1 = Join-Path -Path $TestDrive -ChildPath 'test1.psm1' + Set-Content -Path $testPath1 -Value $fileContent + + $fileList = Get-FileList -Path $TestDrive -Extension ".ps1" + + Remove-Item -Path $testPath1 -Force + + $fileList.Count | Should -BeExactly 0 + + } + + It "should return one file when checking folder with some matching files" { + + $fileContent = "function Get-FileContent {}" + $testPath1 = Join-Path -Path $TestDrive -ChildPath 'test1.psm1' + Set-Content -Path $testPath1 -Value $fileContent + $testPath2 = Join-Path -Path $TestDrive -ChildPath 'test2.ps1' + Set-Content -Path $testPath2 -Value $fileContent + + $fileList = Get-FileList -Path $TestDrive -Extension ".ps1" + + Remove-Item -Path $testPath1 -Force + Remove-Item -Path $testPath2 -Force + + $fileList.Count | Should -BeExactly 1 + + } + + It "should return correct file when checking folder" { + + $fileContent = "function Get-FileContent {}" + $testPath1 = Join-Path -Path $TestDrive -ChildPath 'test1.psm1' + Set-Content -Path $testPath1 -Value $fileContent + $testPath2 = Join-Path -Path $TestDrive -ChildPath 'test2.ps1' + Set-Content -Path $testPath2 -Value $fileContent + + $fileList = Get-FileList -Path $TestDrive -Extension ".ps1" + + Remove-Item -Path $testPath1 -Force + Remove-Item -Path $testPath2 -Force + + $fileList | Should -BeExactly $testPath2 + + } + + It "should return multiple correct files when checking folder" { + + $fileContent = "function Get-FileContent {}" + $testPath1 = Join-Path -Path $TestDrive -ChildPath 'test1.ps1' + Set-Content -Path $testPath1 -Value $fileContent + $testPath2 = Join-Path -Path $TestDrive -ChildPath 'test2.ps1' + Set-Content -Path $testPath2 -Value $fileContent + + $fileList = Get-FileList -Path $TestDrive -Extension ".ps1" + + Remove-Item -Path $testPath1 -Force + Remove-Item -Path $testPath2 -Force + + $fileList | Should -BeExactly @($testPath1, $testPath2) + + } + + It "should not return Test files when checking folder" { + + $fileContent = "function Get-FileContent {}" + $testPath1 = Join-Path -Path $TestDrive -ChildPath 'test.Tests.ps1' + Set-Content -Path $testPath1 -Value $fileContent + + $fileList = Get-FileList -Path $TestDrive -Extension ".ps1" + + Remove-Item -Path $testPath1 -Force + + $fileList.Count | Should -BeExactly 0 + + } + } } From 4667701774bd346376cb6bca5acec20b1f5e8b37 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 17:16:24 +0000 Subject: [PATCH 04/33] Added Export-FunctionsFromModule test --- .../Unit/Export-FunctionsFromModule.Tests.ps1 | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 b/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 index c9dd399..5c20547 100644 --- a/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 +++ b/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 @@ -34,6 +34,11 @@ Describe "Export-FunctionsFromModule.Tests" { Context "Function tests" { + $sourcePath = Join-Path -Path $TestDrive -ChildPath "Source" + New-Item -Path $sourcePath -ItemType Directory + $extractPath = Join-Path -Path $TestDrive -ChildPath "Extract" + New-Item -Path $extractPath -ItemType Directory + It "should throw when passing null parameters" { { @@ -44,6 +49,82 @@ Describe "Export-FunctionsFromModule.Tests" { } + It "should throw when passing non-module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + + { + $fileContent = "" + $testPath1 = Join-Path -Path $sourcePath -ChildPath 'test.ps1' + Set-Content -Path $testPath1 -Value $fileContent + + Export-FunctionsFromModule -Path $testPath1 -ExtractPath $extractPath + + } | Should -Throw + + } + + It "should throw when passing functionless module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + + { + $fileContent = "" + $testPath1 = Join-Path -Path $sourcePath -ChildPath 'test.psm1' + Set-Content -Path $testPath1 -Value $fileContent + + Export-FunctionsFromModule -Path $testPath1 -ExtractPath $extractPath + + } | Should -Throw + + } + + It "should not throw and create valid extracted file when passing simple, valid module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + + { + $testPath1 = Join-Path -Path $sourcePath -ChildPath 'test.psm1' + $fileContent = "function Test-Function { + Write-Host + }" + Set-Content -Path $testPath1 -Value $fileContent + + $functionPath = Join-Path $extractPath -ChildPath "test" + $functionFile = Join-Path $functionPath -ChildPath "Test-Function.ps1" + + Export-FunctionsFromModule -Path $testPath1 -ExtractPath $extractPath + + $files = Get-ChildItem -Path $functionPath + + (Get-ChildItem -Path $functionPath).Count | Should -BeExactly 1 + (Get-ChildItem -Path $functionPath).FullName | Should -BeExactly $functionFile + + } | Should -Not -Throw + + } + + It "should not throw and create valid extracted files when passing simple, valid multi-function module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + + { + $testPath1 = Join-Path -Path $sourcePath -ChildPath 'test.psm1' + $fileContent = "function Test-Function { + Write-Host + } + function Test-SecondFunction { + Write-Host + }" + Set-Content -Path $testPath1 -Value $fileContent + + $functionPath = Join-Path $extractPath -ChildPath "test" + $functionFile1 = Join-Path $functionPath -ChildPath "Test-Function.ps1" + $functionFile2 = Join-Path $functionPath -ChildPath "Test-SecondFunction.ps1" + + Export-FunctionsFromModule -Path $testPath1 -ExtractPath $extractPath + + $files = Get-ChildItem -Path $functionPath + + (Get-ChildItem -Path $functionPath).Count | Should -BeExactly 2 + (Get-ChildItem -Path $functionPath).FullName | Should -BeExactly @($functionFile1, $functionFile2) + + } | Should -Not -Throw + + } + } } From 2f4ebfb86e503b9506e0eef9611cc13fc51703fd Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 17:17:04 +0000 Subject: [PATCH 05/33] Added try/catch and path test to fix issues arising from unit test --- .../Export-FunctionsFromModule.ps1 | 118 ++++++++++-------- 1 file changed, 65 insertions(+), 53 deletions(-) diff --git a/Source/PSQualityCheck.Functions/Export-FunctionsFromModule.ps1 b/Source/PSQualityCheck.Functions/Export-FunctionsFromModule.ps1 index ef75b05..36eef1a 100644 --- a/Source/PSQualityCheck.Functions/Export-FunctionsFromModule.ps1 +++ b/Source/PSQualityCheck.Functions/Export-FunctionsFromModule.ps1 @@ -24,83 +24,95 @@ function Export-FunctionsFromModule { [string]$ExtractPath ) - # Get the file properties of our module - $fileProperties = (Get-Item -LiteralPath $Path) - $moduleName = $fileProperties.BaseName + try { + # Get the file properties of our module + $fileProperties = (Get-Item -LiteralPath $Path) - # Generate a new temporary output path for our extracted functions - $FunctionOutputPath = Join-Path -Path $ExtractPath -ChildPath $moduleName - New-Item $FunctionOutputPath -ItemType 'Directory' + if ($fileProperties.Extension -ne ".psm1") { + throw "Passed file does not appear to be a PowerShell module" + } + + $moduleName = $fileProperties.BaseName - # Get the plain content of the module file - $ModuleFileContent = Get-Content -Path $Path -ErrorAction Stop + # Get the plain content of the module file + $ModuleFileContent = Get-Content -Path $Path -ErrorAction Stop - # Parse the PowerShell module using PSParser - $ParserErrors = $null - $ParsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($ModuleFileContent, [ref]$ParserErrors) + # Parse the PowerShell module using PSParser + $ParserErrors = $null + $ParsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($ModuleFileContent, [ref]$ParserErrors) - # Create an array of where each reference of the keyword 'function' is - $ParsedFunctions = ($ParsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) + # Create an array of where each reference of the keyword 'function' is + $ParsedFunctions = ($ParsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) - # Initialise the $parsedFunction tracking variable - $parsedFunction = 0 + # Initialise the $parsedFunction tracking variable + $parsedFunction = 0 - if ($ParsedFunctions.Count -ge 1) { + if ($ParsedFunctions.Count -ge 1) { - foreach ($Function in $ParsedFunctions) { + # Generate a new temporary output path for our extracted functions + $FunctionOutputPath = Join-Path -Path $ExtractPath -ChildPath $moduleName + + if (-not (Test-Path -Path $FunctionOutputPath)) { + New-Item $FunctionOutputPath -ItemType 'Directory' + } - # Counter for the array $ParsedFunction to help find the 'next' function - $parsedFunction++ + foreach ($Function in $ParsedFunctions) { - # Get the name of the current function - # Cheat: Simply getting all properties with the same line number as the 'function' statement - $FunctionProperties = $ParsedFileFunctions | Where-Object { $_.StartLine -eq $Function.StartLine } - $FunctionName = ($FunctionProperties | Where-Object { $_.Type -eq "CommandArgument" }).Content + # Counter for the array $ParsedFunction to help find the 'next' function + $parsedFunction++ - # Establish the Start and End lines for the function in the main module file - if ($parsedFunction -eq $ParsedFunctions.Count) { + # Get the name of the current function + # Cheat: Simply getting all properties with the same line number as the 'function' statement + $FunctionProperties = $ParsedFileFunctions | Where-Object { $_.StartLine -eq $Function.StartLine } + $FunctionName = ($FunctionProperties | Where-Object { $_.Type -eq "CommandArgument" }).Content - # This is the last function in the module so set the last line of this function to be the last line in the module file + # Establish the Start and End lines for the function in the main module file + if ($parsedFunction -eq $ParsedFunctions.Count) { - $StartLine = ($Function.StartLine) - for ($line = $ModuleFileContent.Count; $line -gt $Function.StartLine; $line--) { - if ($ModuleFileContent[$line] -like "}") { - $EndLine = $line - break + # This is the last function in the module so set the last line of this function to be the last line in the module file + + $StartLine = ($Function.StartLine) + for ($line = $ModuleFileContent.Count; $line -gt $Function.StartLine; $line--) { + if ($ModuleFileContent[$line] -like "}") { + $EndLine = $line + break + } } } - } - else { + else { - $StartLine = ($Function.StartLine) + $StartLine = ($Function.StartLine) - # EndLine needs to be where the last } is - for ($line = $ParsedFunctions[$parsedFunction].StartLine; $line -gt $Function.StartLine; $line--) { - if ($ModuleFileContent[$line] -like "}") { - $EndLine = $line - break + # EndLine needs to be where the last } is + for ($line = $ParsedFunctions[$parsedFunction].StartLine; $line -gt $Function.StartLine; $line--) { + if ($ModuleFileContent[$line] -like "}") { + $EndLine = $line + break + } } + } - } + # Setup the FunctionOutputFile for the function file + $FunctionOutputFileName = "{0}\{1}{2}" -f $FunctionOutputPath, $FunctionName, ".ps1" - # Setup the FunctionOutputFile for the function file - $FunctionOutputFileName = "{0}\{1}{2}" -f $FunctionOutputPath, $FunctionName, ".ps1" + # If the file doesn't exist create an empty file so that we can Add-Content to it + if (-not (Test-Path -Path $FunctionOutputFileName)) { + Out-File -FilePath $FunctionOutputFileName + } - # If the file doesn't exist create an empty file so that we can Add-Content to it - if (-not (Test-Path -Path $FunctionOutputFileName)) { - Out-File -FilePath $FunctionOutputFileName - } + # Output the lines of the function to the FunctionOutputFile + for ($line = $StartLine; $line -lt $EndLine; $line++) { + Add-Content -Path $FunctionOutputFileName -Value $ModuleFileContent[$line] + } - # Output the lines of the function to the FunctionOutputFile - for ($line = $StartLine; $line -lt $EndLine; $line++) { - Add-Content -Path $FunctionOutputFileName -Value $ModuleFileContent[$line] } - + } + else { + throw "File contains no functions" } } - else { - Write-Warning "Module contains no functions, skipping" + catch { + throw } - } From a2b0571326ef6f388667820a8a0da0d32f467f07 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 18:54:07 +0000 Subject: [PATCH 06/33] Fixes to tests to match Pester guidelines --- .../Unit/Export-FunctionsFromModule.Tests.ps1 | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 b/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 index 5c20547..1eed392 100644 --- a/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 +++ b/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 @@ -34,10 +34,14 @@ Describe "Export-FunctionsFromModule.Tests" { Context "Function tests" { - $sourcePath = Join-Path -Path $TestDrive -ChildPath "Source" - New-Item -Path $sourcePath -ItemType Directory - $extractPath = Join-Path -Path $TestDrive -ChildPath "Extract" - New-Item -Path $extractPath -ItemType Directory + BeforeAll { + + $sourcePath = Join-Path -Path $TestDrive -ChildPath "Source" + New-Item -Path $sourcePath -ItemType Directory + $extractPath = Join-Path -Path $TestDrive -ChildPath "Extract" + New-Item -Path $extractPath -ItemType Directory + + } It "should throw when passing null parameters" { @@ -49,7 +53,7 @@ Describe "Export-FunctionsFromModule.Tests" { } - It "should throw when passing non-module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + It "should throw when passing non-module file" { { $fileContent = "" @@ -62,7 +66,7 @@ Describe "Export-FunctionsFromModule.Tests" { } - It "should throw when passing functionless module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + It "should throw when passing functionless module file" { { $fileContent = "" @@ -75,7 +79,7 @@ Describe "Export-FunctionsFromModule.Tests" { } - It "should not throw and create valid extracted file when passing simple, valid module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + It "should not throw and create valid extracted file when passing simple, valid module file" { { $testPath1 = Join-Path -Path $sourcePath -ChildPath 'test.psm1' @@ -98,7 +102,7 @@ Describe "Export-FunctionsFromModule.Tests" { } - It "should not throw and create valid extracted files when passing simple, valid multi-function module file" -TestCases @{ 'sourcePath' = $sourcePath; 'extractPath' = $extractPath } { + It "should not throw and create valid extracted files when passing simple, valid multi-function module file" { { $testPath1 = Join-Path -Path $sourcePath -ChildPath 'test.psm1' From 5a49425348d9a7d5c9f8d1eba960908f3f75edcf Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 18:54:46 +0000 Subject: [PATCH 07/33] Added Get-FunctionCount tests --- Source/Tests/Unit/Get-FunctionCount.Tests.ps1 | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 b/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 index f8f7498..18bcf14 100644 --- a/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 +++ b/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 @@ -34,6 +34,13 @@ Describe "Get-FunctionCount.Tests" { Context "Function tests" { + BeforeAll { + + $moduleFile = Join-Path -Path $TestDrive -ChildPath 'test1.psm1' + $manifestFile = Join-Path -Path $TestDrive -ChildPath 'test1.psd1' + + } + It "should throw when passing null parameters" { { @@ -44,6 +51,92 @@ Describe "Get-FunctionCount.Tests" { } + It "should find one function with matching module and manifest" { + + $fileContent = "function Get-FileContent {}" + Set-Content -Path $moduleFile -Value $fileContent + + New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent') + + Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(1, 1, 1, 1) + + Remove-Item -Path $moduleFile -Force + Remove-Item -Path $manifestFile -Force + + } + + It "should find two functions in module with matching manifest and module" { + + $fileContent = "function Get-FileContent {} + function Get-FileContent2 {}" + Set-Content -Path $moduleFile -Value $fileContent + + New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent', 'Get-FileContent2') + + Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(2, 2, 2, 2) + + Remove-Item -Path $moduleFile -Force + Remove-Item -Path $manifestFile -Force + + } + + It "should not find any function in manifest or module with empty manifest" { + + $fileContent = "function Get-FileContent {}" + Set-Content -Path $moduleFile -Value $fileContent + + New-ModuleManifest -Path $manifestFile + + Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(0, 0, 0, 0) + + Remove-Item -Path $moduleFile -Force + Remove-Item -Path $manifestFile -Force + + } + + It "should not find function in manifest and module with mismatched functions between manifest and module" { + + $fileContent = "function Get-FileContent {}" + Set-Content -Path $moduleFile -Value $fileContent + + New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent2') + + Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(1, 0, 1, 0) + + Remove-Item -Path $moduleFile -Force + Remove-Item -Path $manifestFile -Force + + } + + It "should not find function in module with function in manifest and not in module" { + + $fileContent = "function Get-FileContent {}" + Set-Content -Path $moduleFile -Value $fileContent + + New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent', 'Get-FileContent2') + + Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(2, 1, 1, 1) + + Remove-Item -Path $moduleFile -Force + Remove-Item -Path $manifestFile -Force + + } + + It "should not find function in module with function in module and not in manifest" { + + $fileContent = "function Get-FileContent {} + function Get-FileContent2 {}" + Set-Content -Path $moduleFile -Value $fileContent + + New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent') + + Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(1, 1, 2, 1) + + Remove-Item -Path $moduleFile -Force + Remove-Item -Path $manifestFile -Force + + } + } } From f51af77b9f218cf610bad5a8a94cf81ec7728089 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 19:22:00 +0000 Subject: [PATCH 08/33] Updated to match Pester 5 guidelines more --- Source/Tests/Unit/Get-ParsedContent.Tests.ps1 | 97 ++++++++++--------- 1 file changed, 50 insertions(+), 47 deletions(-) diff --git a/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 b/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 index 8670a73..fe95a40 100644 --- a/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 +++ b/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 @@ -6,6 +6,7 @@ Describe "Get-ParsedContent.Tests" { 'Content' ) + # TODO: This needs replacing with the correct Pester 5 way of doing things, but it does work foreach ($parameter in $mandatoryParameters) { It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { @@ -27,6 +28,53 @@ Describe "Get-ParsedContent.Tests" { Context "Function tests" { + BeforeAll { + + $parsedFileContent = @( + @{ + "Content" = "function" + "Type" = "Keyword" + "Start" = 0 + "Length" = 8 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 9 + }, + @{ + "Content" = "Get-FileContent" + "Type" = "CommandArgument" + "Start" = 9 + "Length" = 15 + "StartLine" = 1 + "StartColumn" = 10 + "EndLine" = 1 + "EndColumn" = 25 + }, + @{ + "Content" = "{" + "Type" = "GroupStart" + "Start" = 25 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 26 + "EndLine" = 1 + "EndColumn" = 27 + }, + @{ + "Content" = "}" + "Type" = "GroupEnd" + "Start" = 26 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 27 + "EndLine" = 1 + "EndColumn" = 28 + } + ) + + } + It "should throw when passing null parameters" { { @@ -36,51 +84,7 @@ Describe "Get-ParsedContent.Tests" { } | Should -Throw } - - $parsedFileContent = @( - @{ - "Content" = "function" - "Type" = "Keyword" - "Start" = 0 - "Length" = 8 - "StartLine" = 1 - "StartColumn" = 1 - "EndLine" = 1 - "EndColumn" = 9 - }, - @{ - "Content" = "Get-FileContent" - "Type" = "CommandArgument" - "Start" = 9 - "Length" = 15 - "StartLine" = 1 - "StartColumn" = 10 - "EndLine" = 1 - "EndColumn" = 25 - }, - @{ - "Content" = "{" - "Type" = "GroupStart" - "Start" = 25 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 26 - "EndLine" = 1 - "EndColumn" = 27 - }, - @{ - "Content" = "}" - "Type" = "GroupEnd" - "Start" = 26 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 27 - "EndLine" = 1 - "EndColumn" = 28 - } - ) - - It "should return correct parse tokens for content" -TestCases @{ 'ParsedFileContent' = $parsedFileContent } { + It "should return correct parse tokens for content" { $fileContent = "function Get-FileContent {}" @@ -105,8 +109,7 @@ Describe "Get-ParsedContent.Tests" { } - - It "should not return matching parse tokens for mismatching content" -TestCases @{ 'ParsedFileContent' = $parsedFileContent } { + It "should not return matching parse tokens for mismatching content" { $fileContent = "function Get-Content {}" From 707b192220c4a4354fd1179fd3facc71952c9e29 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 19:22:20 +0000 Subject: [PATCH 09/33] Added Get-ParsedFile tests --- Source/Tests/Unit/Get-ParsedFile.Tests.ps1 | 124 +++++++++++++++++++++ 1 file changed, 124 insertions(+) diff --git a/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 b/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 index 432dc47..6d6856f 100644 --- a/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 +++ b/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 @@ -27,6 +27,63 @@ Describe "Get-ParsedFile.Tests" { Context "Function tests" { + BeforeAll { + + $parsedFileContent = @( + @{ + "Content" = "function" + "Type" = "Keyword" + "Start" = 0 + "Length" = 8 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 9 + }, + @{ + "Content" = "Get-FileContent" + "Type" = "CommandArgument" + "Start" = 9 + "Length" = 15 + "StartLine" = 1 + "StartColumn" = 10 + "EndLine" = 1 + "EndColumn" = 25 + }, + @{ + "Content" = "{" + "Type" = "GroupStart" + "Start" = 25 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 26 + "EndLine" = 1 + "EndColumn" = 27 + }, + @{ + "Content" = "}" + "Type" = "GroupEnd" + "Start" = 26 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 27 + "EndLine" = 1 + "EndColumn" = 28 + } + @{ + "Content" = "`r`n" + "Type" = "NewLine" + "Start" = 27 + "Length" = 2 + "StartLine" = 1 + "StartColumn" = 28 + "EndLine" = 2 + "EndColumn" = 1 + } + ) + + } + It "should throw when passing null parameters" { { @@ -37,6 +94,73 @@ Describe "Get-ParsedFile.Tests" { } + It "should return correct parse tokens for content" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' + $fileContent = "function Get-FileContent {}" + + Set-Content -Path $testPath -Value $fileContent + + ($parsedModule, $parserErrorCount) = Get-ParsedFile -Path $testPath + + for ($x = 0; $x -lt $parsedModule.Count; $x++) { + + ( + ($parsedModule[$x].StartLine -eq $parsedFileContent[$x].StartLine) -and + ($parsedModule[$x].Content -eq $parsedFileContent[$x].Content) -and + ($parsedModule[$x].Type -eq $parsedFileContent[$x].Type) -and + ($parsedModule[$x].Start -eq $parsedFileContent[$x].Start) -and + ($parsedModule[$x].Length -eq $parsedFileContent[$x].Length) -and + ($parsedModule[$x].StartColumn -eq $parsedFileContent[$x].StartColumn) -and + ($parsedModule[$x].EndLine -eq $parsedFileContent[$x].EndLine) -and + ($parsedModule[$x].EndColumn -eq $parsedFileContent[$x].EndColumn) + ) | Should -BeTrue + + } + + Remove-Item -Path $testPath -Force + + $parserErrorCount | Should -BeExactly 0 + + } + + + It "should not return matching parse tokens for mismatching content" { + + $testPath = Join-Path -Path $TestDrive -ChildPath 'test.ps1' + $fileContent = "function Get-Content {}" + + Set-Content -Path $testPath -Value $fileContent + + ($parsedModule, $parserErrorCount) = Get-ParsedFile -Path $testPath + + $flag = $true + + for ($x = 0; $x -lt $parsedModule.Count; $x++) { + + if ( + ($parsedModule[$x].StartLine -ne $parsedFileContent[$x].StartLine) -or + ($parsedModule[$x].Content -ne $parsedFileContent[$x].Content) -or + ($parsedModule[$x].Type -ne $parsedFileContent[$x].Type) -or + ($parsedModule[$x].Start -ne $parsedFileContent[$x].Start) -or + ($parsedModule[$x].Length -ne $parsedFileContent[$x].Length) -or + ($parsedModule[$x].StartColumn -ne $parsedFileContent[$x].StartColumn) -or + ($parsedModule[$x].EndLine -ne $parsedFileContent[$x].EndLine) -or + ($parsedModule[$x].EndColumn -ne $parsedFileContent[$x].EndColumn) + ) { + $flag = $false + } + + } + + Remove-Item -Path $testPath -Force + + $flag | Should -BeFalse + + $parserErrorCount | Should -BeExactly 0 + + } + } } From f4b76912bcd0426fea6cb0362a8b0e876fc6cae9 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 19:53:49 +0000 Subject: [PATCH 10/33] Added throw for empty parameter block --- Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 b/Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 index e910bb7..9afec95 100644 --- a/Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 +++ b/Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 @@ -23,6 +23,10 @@ function Get-ScriptParameters { $parsedScript = [System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$null, [ref]$null) + if ([string]::IsNullOrEmpty($parsedScript.ParamBlock)) { + throw "No parameters found" + } + [string]$paramBlock = $parsedScript.ParamBlock ($ParsedContent, $ParserErrorCount) = Get-ParsedContent -Content $paramBlock From 0f7461db026ca9a0e2df3c9f08032526ee191934 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 19:54:05 +0000 Subject: [PATCH 11/33] Added Get-ScriptParameter tests --- .../Tests/Unit/Get-ScriptParameters.Tests.ps1 | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 b/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 index 9a2dcf2..511d481 100644 --- a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 +++ b/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 @@ -37,6 +37,57 @@ Describe "Get-ScriptParameters.Tests" { } + It "should throw when passed find no parameters" { + + { + $fileContent = "function Get-FileContent { }" + + $parameterVariables = Get-ScriptParameters -Content $fileContent + + $parameterVariables | Should -BeNullOrEmpty + + } | Should -Throw + + } + + It "should find one parameter without type" { + + $fileContent = 'param ( $parameterOne )' + + $parameterVariables = Get-ScriptParameters -Content $fileContent + + $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue + + } + + It "should find one parameter with type" { + + $fileContent = 'param ( [int]$parameterOne )' + + $parameterVariables = Get-ScriptParameters -Content $fileContent + + $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue + $parameterVariables.('parameterOne') | Should -BeExactly '[int]' + + } + + It "should find one parameter with type" { + + $fileContent = 'param ( + [int]$parameterOne, + [string]$parameterTwo + )' + + $parameterVariables = Get-ScriptParameters -Content $fileContent + + $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue + $parameterVariables.('parameterOne') | Should -BeExactly '[int]' + + $parameterVariables.ContainsKey('parameterTwo') | Should -BeTrue + $parameterVariables.('parameterTwo') | Should -BeExactly '[string]' + + } + } } From 27d87ab09141c16bd4d26c4053095b16ba0d6433 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 19:56:26 +0000 Subject: [PATCH 12/33] Fixed test description for Get-TokenComponent --- Source/Tests/Unit/Get-TokenComponent.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 index d00c4d7..0429eed 100644 --- a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 +++ b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 @@ -87,7 +87,7 @@ Describe "Get-TokenComponent.Tests" { } ) - It "should not find token where 'StartLine' is valid" -TestCases @{ 'parsedFileContent' = $parsedFileContent } { + It "should find token where 'StartLine' is valid" -TestCases @{ 'parsedFileContent' = $parsedFileContent } { $token = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine 1 From f093a8da143813588c2afe7c23eff976ab9d61ad Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 20:13:25 +0000 Subject: [PATCH 13/33] Updates to match Pester 5 guidelines --- .../Tests/Unit/Get-TokenComponent.Tests.ps1 | 90 ++++++++++--------- 1 file changed, 46 insertions(+), 44 deletions(-) diff --git a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 index 0429eed..c2a96bd 100644 --- a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 +++ b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 @@ -44,50 +44,52 @@ Describe "Get-TokenComponent.Tests" { } - $parsedFileContent = @( - @{ - "Content" = "function" - "Type" = "Keyword" - "Start" = 0 - "Length" = 8 - "StartLine" = 1 - "StartColumn" = 1 - "EndLine" = 1 - "EndColumn" = 9 - }, - @{ - "Content" = "Get-FileContent" - "Type" = "CommandArgument" - "Start" = 9 - "Length" = 15 - "StartLine" = 1 - "StartColumn" = 10 - "EndLine" = 1 - "EndColumn" = 25 - }, - @{ - "Content" = "{" - "Type" = "GroupStart" - "Start" = 25 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 26 - "EndLine" = 1 - "EndColumn" = 27 - }, - @{ - "Content" = "}" - "Type" = "GroupEnd" - "Start" = 26 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 27 - "EndLine" = 1 - "EndColumn" = 28 - } - ) + BeforeAll { + $parsedFileContent = @( + @{ + "Content" = "function" + "Type" = "Keyword" + "Start" = 0 + "Length" = 8 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 9 + }, + @{ + "Content" = "Get-FileContent" + "Type" = "CommandArgument" + "Start" = 9 + "Length" = 15 + "StartLine" = 1 + "StartColumn" = 10 + "EndLine" = 1 + "EndColumn" = 25 + }, + @{ + "Content" = "{" + "Type" = "GroupStart" + "Start" = 25 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 26 + "EndLine" = 1 + "EndColumn" = 27 + }, + @{ + "Content" = "}" + "Type" = "GroupEnd" + "Start" = 26 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 27 + "EndLine" = 1 + "EndColumn" = 28 + } + ) + } - It "should find token where 'StartLine' is valid" -TestCases @{ 'parsedFileContent' = $parsedFileContent } { + It "should find token where 'StartLine' is valid" { $token = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine 1 @@ -95,7 +97,7 @@ Describe "Get-TokenComponent.Tests" { } - It "should not find token where 'StartLine' is invalid" -TestCases @{ 'parsedFileContent' = $parsedFileContent } { + It "should not find token where 'StartLine' is invalid" { $token = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine 3 $token | Should -BeNullOrEmpty From c2785a684ff21873a2f472e122dd44363ce04824 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 20:13:44 +0000 Subject: [PATCH 14/33] Added Get-Token tests --- Source/Tests/Unit/Get-Token.Tests.ps1 | 78 +++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/Source/Tests/Unit/Get-Token.Tests.ps1 b/Source/Tests/Unit/Get-Token.Tests.ps1 index 655a23f..845e495 100644 --- a/Source/Tests/Unit/Get-Token.Tests.ps1 +++ b/Source/Tests/Unit/Get-Token.Tests.ps1 @@ -53,4 +53,82 @@ Describe "Get-Token.Tests" { } + + BeforeAll { + $parsedFileContent = @( + @{ + "Content" = "function" + "Type" = "Keyword" + "Start" = 0 + "Length" = 8 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 9 + }, + @{ + "Content" = "Get-FileContent" + "Type" = "CommandArgument" + "Start" = 9 + "Length" = 15 + "StartLine" = 1 + "StartColumn" = 10 + "EndLine" = 1 + "EndColumn" = 25 + }, + @{ + "Content" = "{" + "Type" = "GroupStart" + "Start" = 25 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 26 + "EndLine" = 1 + "EndColumn" = 27 + }, + @{ + "Content" = "}" + "Type" = "GroupEnd" + "Start" = 26 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 27 + "EndLine" = 1 + "EndColumn" = 28 + } + ) + } + + It "should find token where parameters are valid" { + + $token = Get-Token -ParsedFileContent $parsedFileContent -Type "Keyword" -Content "Function" + + Write-Host ($token | Out-String) -ForegroundColor Cyan + Write-Host $tokenMatch.StartLine -ForegroundColor Magenta + + for ($x = 0; $x -lt $parsedModule.Count; $x++) { + + ( + ($token[$x].StartLine -eq $parsedFileContent[$x].StartLine) -and + ($token[$x].Content -eq $parsedFileContent[$x].Content) -and + ($token[$x].Type -eq $parsedFileContent[$x].Type) -and + ($token[$x].Start -eq $parsedFileContent[$x].Start) -and + ($token[$x].Length -eq $parsedFileContent[$x].Length) -and + ($token[$x].StartColumn -eq $parsedFileContent[$x].StartColumn) -and + ($token[$x].EndLine -eq $parsedFileContent[$x].EndLine) -and + ($token[$x].EndColumn -eq $parsedFileContent[$x].EndColumn) + ) | Should -BeTrue + + } + + } + + It "should not find token where parameters are invalid" { + + $token = (Get-Token -ParsedFileContent $parsedFileContent -Type "Unknown" -Content "Data") + + $token | Should -BeNullOrEmpty + + } + } From c14be255bbd1522a8731d84efff33b95677d8e73 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 20:16:11 +0000 Subject: [PATCH 15/33] Removed debug code --- Source/Tests/Unit/Get-Token.Tests.ps1 | 3 --- 1 file changed, 3 deletions(-) diff --git a/Source/Tests/Unit/Get-Token.Tests.ps1 b/Source/Tests/Unit/Get-Token.Tests.ps1 index 845e495..ab5b0c9 100644 --- a/Source/Tests/Unit/Get-Token.Tests.ps1 +++ b/Source/Tests/Unit/Get-Token.Tests.ps1 @@ -103,9 +103,6 @@ Describe "Get-Token.Tests" { $token = Get-Token -ParsedFileContent $parsedFileContent -Type "Keyword" -Content "Function" - Write-Host ($token | Out-String) -ForegroundColor Cyan - Write-Host $tokenMatch.StartLine -ForegroundColor Magenta - for ($x = 0; $x -lt $parsedModule.Count; $x++) { ( From 010fc4d78f47207876e3bc6d0379f82545901c9e Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 20:19:11 +0000 Subject: [PATCH 16/33] Added new tests and improved existing one --- .../Tests/Unit/Get-ScriptParameters.Tests.ps1 | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 b/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 index 511d481..03284fd 100644 --- a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 +++ b/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 @@ -37,7 +37,7 @@ Describe "Get-ScriptParameters.Tests" { } - It "should throw when passed find no parameters" { + It "should throw when passed no parameters" { { $fileContent = "function Get-FileContent { }" @@ -57,6 +57,7 @@ Describe "Get-ScriptParameters.Tests" { $parameterVariables = Get-ScriptParameters -Content $fileContent $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue + $parameterVariables.('parameterOne') | Should -BeNullOrEmpty } @@ -71,7 +72,7 @@ Describe "Get-ScriptParameters.Tests" { } - It "should find one parameter with type" { + It "should find two parameters with type" { $fileContent = 'param ( [int]$parameterOne, @@ -88,6 +89,23 @@ Describe "Get-ScriptParameters.Tests" { } + It "should find two parameters one with type and one without" { + + $fileContent = 'param ( + [int]$parameterOne, + $parameterTwo + )' + + $parameterVariables = Get-ScriptParameters -Content $fileContent + + $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue + $parameterVariables.('parameterOne') | Should -BeExactly '[int]' + + $parameterVariables.ContainsKey('parameterTwo') | Should -BeTrue + $parameterVariables.('parameterTwo') | Should -BeNullOrEmpty + + } + } } From ddba502138d5d41e6c9bdc87e5ed8ea34ad69d84 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 21:21:25 +0000 Subject: [PATCH 17/33] Refactored code to be more useful --- .../PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 b/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 index 684a7fe..f9b4fc4 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 +++ b/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 @@ -23,9 +23,11 @@ function Test-HelpForRequiredTokens { $module = Get-Module -Name PSQualityCheck - if (Test-Path -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) { + $helpElementRulesPath = (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1") - $helpElementRules = (Import-PowerShellDataFile -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) + if (Test-Path -Path $helpElementRulesPath) { + + $helpElementRules = Import-PowerShellDataFile -Path $helpElementRulesPath } else { From 91c42cb4b13ffa669b2ff56a030f2fac9a83de78 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sat, 9 Jan 2021 21:21:49 +0000 Subject: [PATCH 18/33] Added Test-HelpForRequiredTokens tests --- .../Unit/Test-HelpForRequiredTokens.Tests.ps1 | 190 ++++++++++++++++++ 1 file changed, 190 insertions(+) diff --git a/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 b/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 index ade7395..1dc0395 100644 --- a/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 @@ -27,6 +27,68 @@ Describe "Test-HelpForRequiredTokens.Tests" { Context "Function tests" { + BeforeAll { + New-Item -Path (Join-Path -Path $TestDrive -ChildPath 'module') -ItemType Directory + New-Item -Path (Join-Path -Path $TestDrive -ChildPath 'module\checks') -ItemType Directory + + '@{ + ''1'' = @{ + Key = ''.SYNOPSIS'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 1 + } + ''2'' = @{ + Key = ''.DESCRIPTION'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 1 + } + ''3'' = @{ + Key = ''.PARAMETER'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''4'' = @{ + Key = ''.EXAMPLE'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 100 + } + ''5'' = @{ + Key = ''.INPUTS'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''6'' = @{ + Key = ''.OUTPUTS'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''7'' = @{ + Key = ''.NOTES'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''8'' = @{ + Key = ''.LINK'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + }' | Set-Content -Path (Join-Path -Path $TestDrive -ChildPath 'module\checks\HelpElementRules.psd1') + } + + BeforeEach { + Mock Get-Module -ParameterFilter { $Name -eq "PSQualityCheck" } { + return @{'ModuleBase' = Join-Path -Path $TestDrive -ChildPath 'module' } + } + } + It "should throw when passing null parameters" { { @@ -37,6 +99,134 @@ Describe "Test-HelpForRequiredTokens.Tests" { } + It "should not throw when checking required help tokens" { + + { + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + '.DESCRIPTION' = @( + @{ + "Name" = $null + "LineNumber" = 3 + "Text" = "" + } + ) + '.PARAMETER' = @( + @{ + "Name" = "Path" + "LineNumber" = 5 + "Text" = "" + } + ) + '.EXAMPLE' = @( + @{ + "Name" = "" + "LineNumber" = 7 + "Text" = "This is example text" + } + ) + } + + Test-HelpForRequiredTokens -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Not -Throw + + } + + It "should not throw when checking required help tokens plus optional help tokens" { + + { + + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + '.DESCRIPTION' = @( + @{ + "Name" = $null + "LineNumber" = 3 + "Text" = "" + } + ) + '.PARAMETER' = @( + @{ + "Name" = "Path" + "LineNumber" = 5 + "Text" = "" + } + ) + '.EXAMPLE' = @( + @{ + "Name" = "" + "LineNumber" = 7 + "Text" = "This is example text" + } + ) + '.NOTES' = @( + @{ + "Name" = "" + "LineNumber" = 10 + "Text" = "This is a note" + } + ) + + } + + Test-HelpForRequiredTokens -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Not -Throw + + } + + It "should throw when required help token is missing" { + + { + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + '.DESCRIPTION' = @( + @{ + "Name" = $null + "LineNumber" = 3 + "Text" = "" + } + ) + '.PARAMETER' = @( + @{ + "Name" = "Path" + "LineNumber" = 5 + "Text" = "" + } + ) + } + + Test-HelpForRequiredTokens -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Throw + + } + } } From 68bdc9e4bc01230d7f7128d7b429a1535f9c2486 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sun, 10 Jan 2021 12:37:46 +0000 Subject: [PATCH 19/33] Added Test-HelpForUnspecifiedTokens tests --- .../Test-HelpForUnspecifiedTokens.Tests.ps1 | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 b/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 index 64b9efc..9781166 100644 --- a/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 @@ -27,6 +27,68 @@ Describe "Test-HelpForUnspecifiedTokens.Tests" { Context "Function tests" { + BeforeAll { + New-Item -Path (Join-Path -Path $TestDrive -ChildPath 'module') -ItemType Directory + New-Item -Path (Join-Path -Path $TestDrive -ChildPath 'module\checks') -ItemType Directory + + '@{ + ''1'' = @{ + Key = ''.SYNOPSIS'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 1 + } + ''2'' = @{ + Key = ''.DESCRIPTION'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 1 + } + ''3'' = @{ + Key = ''.PARAMETER'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''4'' = @{ + Key = ''.EXAMPLE'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 100 + } + ''5'' = @{ + Key = ''.INPUTS'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''6'' = @{ + Key = ''.OUTPUTS'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''7'' = @{ + Key = ''.NOTES'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''8'' = @{ + Key = ''.LINK'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + }' | Set-Content -Path (Join-Path -Path $TestDrive -ChildPath 'module\checks\HelpElementRules.psd1') + } + + BeforeEach { + Mock Get-Module -ParameterFilter { $Name -eq "PSQualityCheck" } { + return @{'ModuleBase' = Join-Path -Path $TestDrive -ChildPath 'module' } + } + } + It "should throw when passing null parameters" { { @@ -37,6 +99,120 @@ Describe "Test-HelpForUnspecifiedTokens.Tests" { } + It "should not throw when checking required help tokens" { + + { + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + '.DESCRIPTION' = @( + @{ + "Name" = $null + "LineNumber" = 3 + "Text" = "" + } + ) + '.PARAMETER' = @( + @{ + "Name" = "Path" + "LineNumber" = 5 + "Text" = "" + } + ) + '.EXAMPLE' = @( + @{ + "Name" = "" + "LineNumber" = 7 + "Text" = "This is example text" + } + ) + } + + Test-HelpForRequiredTokens -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Not -Throw + + } + + It "should not throw when checking required help tokens plus optional help tokens" { + + { + + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + '.DESCRIPTION' = @( + @{ + "Name" = $null + "LineNumber" = 3 + "Text" = "" + } + ) + '.PARAMETER' = @( + @{ + "Name" = "Path" + "LineNumber" = 5 + "Text" = "" + } + ) + '.EXAMPLE' = @( + @{ + "Name" = "" + "LineNumber" = 7 + "Text" = "This is example text" + } + ) + '.NOTES' = @( + @{ + "Name" = "" + "LineNumber" = 10 + "Text" = "This is a note" + } + ) + + } + + Test-HelpForRequiredTokens -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Not -Throw + + } + + It "should throw when unspecified help token is present" { + + { + $helpTokens = @{ + '.DUMMY' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + } + + Test-HelpForRequiredTokens -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Throw + + } + } } From cc3736ff512a9891a7e883400d028c0a9049711c Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Sun, 10 Jan 2021 13:21:06 +0000 Subject: [PATCH 20/33] Added Test-HelpTokensCountIsValid --- .../Test-HelpTokensCountIsValid.Tests.ps1 | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 b/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 index 05dd729..71ebe80 100644 --- a/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 @@ -27,6 +27,68 @@ Describe "Test-HelpTokensCountIsValid.Tests" { Context "Function tests" { + BeforeAll { + New-Item -Path (Join-Path -Path $TestDrive -ChildPath 'module') -ItemType Directory + New-Item -Path (Join-Path -Path $TestDrive -ChildPath 'module\checks') -ItemType Directory + + '@{ + ''1'' = @{ + Key = ''.SYNOPSIS'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 1 + } + ''2'' = @{ + Key = ''.DESCRIPTION'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 1 + } + ''3'' = @{ + Key = ''.PARAMETER'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''4'' = @{ + Key = ''.EXAMPLE'' + Required = $true + MinOccurrences = 1 + MaxOccurrences = 100 + } + ''5'' = @{ + Key = ''.INPUTS'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''6'' = @{ + Key = ''.OUTPUTS'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''7'' = @{ + Key = ''.NOTES'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + ''8'' = @{ + Key = ''.LINK'' + Required = $false + MinOccurrences = 0 + MaxOccurrences = 0 + } + }' | Set-Content -Path (Join-Path -Path $TestDrive -ChildPath 'module\checks\HelpElementRules.psd1') + } + + BeforeEach { + Mock Get-Module -ParameterFilter { $Name -eq "PSQualityCheck" } { + return @{'ModuleBase' = Join-Path -Path $TestDrive -ChildPath 'module' } + } + } + It "should throw when passing null parameters" { { @@ -37,6 +99,115 @@ Describe "Test-HelpTokensCountIsValid.Tests" { } + It "should not throw when checking required help tokens count" { + + { + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + } + + Test-HelpTokensCountIsValid -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Not -Throw + + } + + It "should throw when required help token is out of min/max range" { + + { + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + }, + @{ + "Name" = $null + "LineNumber" = 2 + "Text" = "" + } + ) + '.DESCRIPTION' = @( + @{ + "Name" = $null + "LineNumber" = 3 + "Text" = "" + } + ) + '.PARAMETER' = @( + @{ + "Name" = "Path" + "LineNumber" = 5 + "Text" = "" + } + ) + } + + Test-HelpTokensCountIsValid -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Throw + + } + + + It "should not throw when optional help token is out of min/max range" { + + { + $helpTokens = @{ + '.SYNOPSIS' = @( + @{ + "Name" = $null + "LineNumber" = 1 + "Text" = "" + } + ) + '.DESCRIPTION' = @( + @{ + "Name" = $null + "LineNumber" = 3 + "Text" = "" + } + ) + '.PARAMETER' = @( + @{ + "Name" = "Path" + "LineNumber" = 5 + "Text" = "" + } + ) + '.NOTES' = @( + @{ + "Name" = "" + "LineNumber" = 10 + "Text" = "This is a note" + }, + @{ + "Name" = "" + "LineNumber" = 10 + "Text" = "This is a note" + } + ) + } + + Test-HelpTokensCountIsValid -HelpTokens $helpTokens + + Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } + + } | Should -Not -Throw + + } + } } From 6de53e14645bf11dd49fd808a5e2c33b6136d943 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 10:13:24 +0000 Subject: [PATCH 21/33] Fix finding module name --- .../PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 b/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 index 2ee9d9a..fe107fd 100644 --- a/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 +++ b/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 @@ -35,7 +35,12 @@ function Test-ImportModuleIsValid { $importModuleStatement = Get-TokenComponent -ParsedFileContent $ParsedFile -StartLine $token.StartLine # Get the name of the module to be imported (for logging only) - $name = ($importModuleStatement | Where-Object { $_.Type -eq "String" } | Select-Object -First 1).Content + $name = ($importModuleStatement | Where-Object { $_.Type -eq "CommandArgument" } | Select-Object -First 1).Content + if ($null -eq $name) { + + $name = ($importModuleStatement | Where-Object { $_.Type -eq "String" } | Select-Object -First 1).Content + + } # if the -Name parameter is not found if (-not($importModuleStatement | Where-Object { $_.Type -eq "CommandParameter" -and $_.Content -eq "-Name" })) { From b6e4a0e3d525f0d5686267e6b0c641f03049aa64 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 10:13:51 +0000 Subject: [PATCH 22/33] Added Test-ImportModuleisValid tests --- .../Unit/Test-ImportModuleIsValid.Tests.ps1 | 202 +++++++++++++++++- 1 file changed, 201 insertions(+), 1 deletion(-) diff --git a/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 b/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 index 60bf94b..a12b1ec 100644 --- a/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 +++ b/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 @@ -30,7 +30,6 @@ Describe "Test-ImportModuleIsValid.Tests" { } - } Context "Function tests" { @@ -44,6 +43,207 @@ Describe "Test-ImportModuleIsValid.Tests" { } | Should -Throw } + + It "should pass when passed a valid Import-Module command" { + + { + + $parsedFile = @( + @{ + "Content" = "Import-Module" + "Type" = "Command" + "Start" = 0 + "Length" = 13 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 14 + }, + @{ + "Content" = "-Name" + "Type" = "CommandParameter" + "Start" = 14 + "Length" = 5 + "StartLine" = 1 + "StartColumn" = 15 + "EndLine" = 1 + "EndColumn" = 20 + }, + @{ + "Content" = "ModuleName" + "Type" = "CommandArgument" + "Start" = 20 + "Length" = 10 + "StartLine" = 1 + "StartColumn" = 21 + "EndLine" = 1 + "EndColumn" = 31 + }, + @{ + "Content" = "-RequiredVersion" + "Type" = "CommandParameter" + "Start" = 31 + "Length" = 16 + "StartLine" = 1 + "StartColumn" = 32 + "EndLine" = 1 + "EndColumn" = 48 + }, + @{ + "Content" = "1.0.0" + "Type" = "String" + "Start" = 48 + "Length" = 7 + "StartLine" = 1 + "StartColumn" = 49 + "EndLine" = 1 + "EndColumn" = 56 + } + ) + + $importModuleTokens = $parsedFile + + Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + + } | Should -Not -Throw + + } + + It "should throw when passed a valid Import-Module command missing all required parameters" { + + { + + $parsedFile = @( + @{ + "Content" = "Import-Module" + "Type" = "Command" + "Start" = 0 + "Length" = 13 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 14 + }, + @{ + "Content" = "ModuleName" + "Type" = "CommandArgument" + "Start" = 14 + "Length" = 10 + "StartLine" = 1 + "StartColumn" = 15 + "EndLine" = 1 + "EndColumn" = 25 + } + ) + + $importModuleTokens = $parsedFile + + Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + + } | Should -Not -Throw + + } + + It "should throw when passed a valid Import-Module command missing -Name only" { + + { + + $parsedFile = @( + @{ + "Content" = "Import-Module" + "Type" = "Command" + "Start" = 0 + "Length" = 13 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 14 + }, + @{ + "Content" = "ModuleName" + "Type" = "CommandArgument" + "Start" = 14 + "Length" = 10 + "StartLine" = 1 + "StartColumn" = 15 + "EndLine" = 1 + "EndColumn" = 25 + }, + @{ + "Content" = "-RequiredVersion" + "Type" = "CommandParameter" + "Start" = 25 + "Length" = 16 + "StartLine" = 1 + "StartColumn" = 26 + "EndLine" = 1 + "EndColumn" = 42 + }, + @{ + "Content" = "1.0.0" + "Type" = "String" + "Start" = 42 + "Length" = 7 + "StartLine" = 1 + "StartColumn" = 43 + "EndLine" = 1 + "EndColumn" = 50 + } + ) + + $importModuleTokens = $parsedFile + + Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + + } | Should -Not -Throw + + } + + It "should throw when passed a valid Import-Module command missing -RequiredVersion, -MinimumVersion or -MaximumVersion" { + + { + + $parsedFile = @( + @{ + "Content" = "Import-Module" + "Type" = "Command" + "Start" = 0 + "Length" = 13 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 14 + }, + @{ + "Content" = "-Name" + "Type" = "CommandParameter" + "Start" = 14 + "Length" = 5 + "StartLine" = 1 + "StartColumn" = 15 + "EndLine" = 1 + "EndColumn" = 20 + }, + @{ + "Content" = "ModuleName" + "Type" = "CommandArgument" + "Start" = 20 + "Length" = 10 + "StartLine" = 1 + "StartColumn" = 21 + "EndLine" = 1 + "EndColumn" = 31 + } + ) + + $importModuleTokens = $parsedFile + + Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + + } | Should -Not -Throw + + } + } } From 8bd57e3e4250c0d1a775b8978c7b73e04ad77a3d Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 10:57:29 +0000 Subject: [PATCH 23/33] Parameter consistency fixes --- .../PSQualityCheck.Functions/Convert-Help.ps1 | 20 ++--- .../Get-FunctionCount.ps1 | 18 ++--- Source/PSQualityCheck.Functions/Get-Token.ps1 | 10 +-- .../Get-TokenComponent.ps1 | 8 +- .../Get-TokenMarker.ps1 | 8 +- .../Test-HelpForRequiredTokens.ps1 | 2 +- .../Test-HelpForUnspecifiedTokens.ps1 | 2 +- .../Test-HelpTokensCountIsValid.ps1 | 2 +- .../Test-HelpTokensParamsMatch.ps1 | 2 +- .../Test-HelpTokensTextIsValid.ps1 | 2 +- .../Test-ImportModuleIsValid.ps1 | 10 +-- Source/Tests/Unit/Convert-Help.Tests.ps1 | 38 ++++----- Source/Tests/Unit/Get-FunctionCount.Tests.ps1 | 78 +++++++++---------- Source/Tests/Unit/Get-Token.Tests.ps1 | 30 +++---- .../Tests/Unit/Get-TokenComponent.Tests.ps1 | 18 ++--- Source/Tests/Unit/Get-TokenMarker.Tests.ps1 | 26 +++---- .../Unit/Test-ImportModuleIsValid.Tests.ps1 | 38 ++++----- 17 files changed, 156 insertions(+), 156 deletions(-) diff --git a/Source/PSQualityCheck.Functions/Convert-Help.ps1 b/Source/PSQualityCheck.Functions/Convert-Help.ps1 index 4a655ce..aa74790 100644 --- a/Source/PSQualityCheck.Functions/Convert-Help.ps1 +++ b/Source/PSQualityCheck.Functions/Convert-Help.ps1 @@ -6,17 +6,17 @@ function Convert-Help { .DESCRIPTION Convert the help comment into an object containing all the elements from the help comment - .PARAMETER HelpComment + .PARAMETER Help A string containing the Help Comment .EXAMPLE - $helpObject = Convert-Help -HelpComment $helpComment + $helpObject = Convert-Help -Help $Help #> [CmdletBinding()] [OutputType([HashTable], [System.Exception])] param ( [parameter(Mandatory = $true)] - [string]$HelpComment + [string]$Help ) # These are the possible Help Comment elements that the script will look for @@ -41,8 +41,8 @@ function Convert-Help { try { if (-not( - $HelpComment.StartsWith("<#") -and - $HelpComment.EndsWith("#>") + $Help.StartsWith("<#") -and + $Help.EndsWith("#>") )) { throw "Help does not appear to be a comment block" } @@ -66,7 +66,7 @@ function Convert-Help { '.EXTERNALHELP' # Split the single comment string into it's line components - $commentArray = ($HelpComment -split '\n').Trim() + $commentArray = ($Help -split '\n').Trim() # initialise an empty HashTable ready for the found help elements to be stored $foundElements = @{} @@ -91,10 +91,10 @@ function Convert-Help { # previous element to the found text so far, then reset it $lastElement = @($foundElements[$lastHelpElement]) - $lastElement[$lastElement.Count - 1].Text = $help + $lastElement[$lastElement.Count - 1].Text = $helpData $foundElements[$lastHelpElement] = $lastElement - $help = $null + $helpData = $null } # this should be an array of HashTables {LineNumber, Name & Text} @@ -124,7 +124,7 @@ function Convert-Help { if ($numFound -ge 1 -and $line -lt ($commentArray.Count - 1)) { - $help += $commentArray[$line] + $helpData += $commentArray[$line] } @@ -135,7 +135,7 @@ function Convert-Help { if ( -not ([string]::IsNullOrEmpty($lastHelpElement))) { # process the very last one $currentElement = @($foundElements[$lastHelpElement]) - $currentElement[$currentElement.Count - 1].Text = $help + $currentElement[$currentElement.Count - 1].Text = $helpData $foundElements[$lastHelpElement] = $currentElement } diff --git a/Source/PSQualityCheck.Functions/Get-FunctionCount.ps1 b/Source/PSQualityCheck.Functions/Get-FunctionCount.ps1 index 5e7c736..921a0df 100644 --- a/Source/PSQualityCheck.Functions/Get-FunctionCount.ps1 +++ b/Source/PSQualityCheck.Functions/Get-FunctionCount.ps1 @@ -7,28 +7,28 @@ function Get-FunctionCount { Return the count of functions in the Module and Manifest and whether they appear in their counterpart. e.g. Whether the functions in the manifest appear in the module and vice versa - .PARAMETER ModuleFile + .PARAMETER ModulePath A string containing the Module filename - .PARAMETER ManifestFile + .PARAMETER ManifestPath A string containing the Manifest filename .EXAMPLE - ($ExportedCommandsCount, $CommandFoundInModuleCount, $CommandInModuleCount, $CommandFoundInManifestCount) = Get-FunctionCount -ModuleFile $moduleFile -ManifestFile $manifestFile + ($ExportedCommandsCount, $CommandFoundInModuleCount, $CommandInModuleCount, $CommandFoundInManifestCount) = Get-FunctionCount -ModulePath $ModulePath -ManifestPath $ManifestPath #> [CmdletBinding()] [OutputType([Int[]])] param ( [parameter(Mandatory = $true)] - [string]$ModuleFile, + [string]$ModulePath, [parameter(Mandatory = $true)] - [string]$ManifestFile + [string]$ManifestPath ) try { - if (Test-Path -Path $ManifestFile) { - $ExportedCommands = (Test-ModuleManifest -Path $ManifestFile -ErrorAction Stop).ExportedCommands + if (Test-Path -Path $ManifestPath) { + $ExportedCommands = (Test-ModuleManifest -Path $ManifestPath -ErrorAction Stop).ExportedCommands $ExportedCommandsCount = $ExportedCommands.Count } else { @@ -41,8 +41,8 @@ function Get-FunctionCount { } try { - if (Test-Path -Path $ModuleFile) { - ($ParsedModule, $ParserErrors) = Get-ParsedFile -Path $ModuleFile + if (Test-Path -Path $ModulePath) { + ($ParsedModule, $ParserErrors) = Get-ParsedFile -Path $ModulePath } else { throw "Module file doesn't exist" diff --git a/Source/PSQualityCheck.Functions/Get-Token.ps1 b/Source/PSQualityCheck.Functions/Get-Token.ps1 index f544d60..4182e47 100644 --- a/Source/PSQualityCheck.Functions/Get-Token.ps1 +++ b/Source/PSQualityCheck.Functions/Get-Token.ps1 @@ -6,7 +6,7 @@ function Get-Token { .DESCRIPTION Get token(s) from the tokenized output matching the passed Type and Content - .PARAMETER ParsedFileContent + .PARAMETER ParsedContent A string array containing the Tokenized data .PARAMETER Type @@ -16,22 +16,22 @@ function Get-Token { The token content (or value) to be found .EXAMPLE - $outputTypeToken = (Get-Token -ParsedFileContent $ParsedFile -Type "Attribute" -Content "OutputType") + $outputTypeToken = (Get-Token -ParsedContent $ParsedFile -Type "Attribute" -Content "OutputType") #> [CmdletBinding()] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFileContent, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [string]$Type, [parameter(Mandatory = $true)] [string]$Content ) - $token = Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type $Type -Content $Content + $token = Get-TokenMarker -ParsedContent $ParsedContent -Type $Type -Content $Content - $tokens = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine $token.StartLine + $tokens = Get-TokenComponent -ParsedContent $ParsedContent -StartLine $token.StartLine return $tokens diff --git a/Source/PSQualityCheck.Functions/Get-TokenComponent.ps1 b/Source/PSQualityCheck.Functions/Get-TokenComponent.ps1 index b9c6fae..5e60985 100644 --- a/Source/PSQualityCheck.Functions/Get-TokenComponent.ps1 +++ b/Source/PSQualityCheck.Functions/Get-TokenComponent.ps1 @@ -6,20 +6,20 @@ function Get-TokenComponent { .DESCRIPTION Get all the tokens components from a single line in the tokenized content - .PARAMETER ParsedFileContent + .PARAMETER ParsedContent A string array containing the tokenized content .PARAMETER StartLine A integer of the starting line to parse .EXAMPLE - $tokens = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine 10 + $tokens = Get-TokenComponent -ParsedContent $ParsedContent -StartLine 10 #> [CmdletBinding()] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFileContent, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [int]$StartLine ) @@ -28,7 +28,7 @@ function Get-TokenComponent { #* which can't find the variables in the 'Where-Object' clause (even though it's valid) $StartLine = $StartLine - $tokenComponents = @($ParsedFileContent | Where-Object { $_.StartLine -eq $StartLine }) + $tokenComponents = @($ParsedContent | Where-Object { $_.StartLine -eq $StartLine }) return $tokenComponents diff --git a/Source/PSQualityCheck.Functions/Get-TokenMarker.ps1 b/Source/PSQualityCheck.Functions/Get-TokenMarker.ps1 index 5c62797..58a5814 100644 --- a/Source/PSQualityCheck.Functions/Get-TokenMarker.ps1 +++ b/Source/PSQualityCheck.Functions/Get-TokenMarker.ps1 @@ -6,7 +6,7 @@ function Get-TokenMarker { .DESCRIPTION Gets single token from the tokenized output matching the passed Type and Content - .PARAMETER ParsedFileContent + .PARAMETER ParsedContent A string array containing the Tokenized data .PARAMETER Type @@ -16,13 +16,13 @@ function Get-TokenMarker { The token content (or value) to be found .EXAMPLE - $token = Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type $Type -Content $Content + $token = Get-TokenMarker -ParsedContent $ParsedContent -Type $Type -Content $Content #> [CmdletBinding()] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFileContent, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [string]$Type, [parameter(Mandatory = $true)] @@ -34,7 +34,7 @@ function Get-TokenMarker { $Type = $Type $Content = $Content - $token = @($ParsedFileContent | Where-Object { $_.Type -eq $Type -and $_.Content -eq $Content }) + $token = @($ParsedContent | Where-Object { $_.Type -eq $Type -and $_.Content -eq $Content }) return $token diff --git a/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 b/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 index f9b4fc4..d7a2c4a 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 +++ b/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 @@ -7,7 +7,7 @@ function Test-HelpForRequiredTokens { Check that the help comments contain tokens that are specified in the external verification data file .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .EXAMPLE Test-HelpForRequiredTokens -HelpTokens $HelpTokens diff --git a/Source/PSQualityCheck.Functions/Test-HelpForUnspecifiedTokens.ps1 b/Source/PSQualityCheck.Functions/Test-HelpForUnspecifiedTokens.ps1 index 262b741..6013bee 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpForUnspecifiedTokens.ps1 +++ b/Source/PSQualityCheck.Functions/Test-HelpForUnspecifiedTokens.ps1 @@ -7,7 +7,7 @@ function Test-HelpForUnspecifiedTokens { Check that the help comments do not contain tokens that are not specified in the external verification data file .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .EXAMPLE Test-HelpForUnspecifiedTokens -HelpTokens $HelpTokens diff --git a/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 b/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 index c21ef2a..8897f0e 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 +++ b/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 @@ -7,7 +7,7 @@ function Test-HelpTokensCountIsValid { Check that the help tokens count is valid by making sure that they appear between Min and Max times .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .EXAMPLE Test-HelpTokensCountIsValid -HelpTokens $HelpTokens diff --git a/Source/PSQualityCheck.Functions/Test-HelpTokensParamsMatch.ps1 b/Source/PSQualityCheck.Functions/Test-HelpTokensParamsMatch.ps1 index 8cf8457..d66de68 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpTokensParamsMatch.ps1 +++ b/Source/PSQualityCheck.Functions/Test-HelpTokensParamsMatch.ps1 @@ -7,7 +7,7 @@ function Test-HelpTokensParamsMatch { Checks to see whether the parameters in the param block and in the help PARAMETER statements exist in both locations .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .PARAMETER ParameterVariables A object containing the parameters from the param block diff --git a/Source/PSQualityCheck.Functions/Test-HelpTokensTextIsValid.ps1 b/Source/PSQualityCheck.Functions/Test-HelpTokensTextIsValid.ps1 index a358163..982a201 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpTokensTextIsValid.ps1 +++ b/Source/PSQualityCheck.Functions/Test-HelpTokensTextIsValid.ps1 @@ -7,7 +7,7 @@ function Test-HelpTokensTextIsValid { Check that the Help Tokens text is valid by making sure that they its not empty .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .EXAMPLE Test-HelpTokensTextIsValid -HelpTokens $HelpTokens diff --git a/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 b/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 index fe107fd..2d4a470 100644 --- a/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 +++ b/Source/PSQualityCheck.Functions/Test-ImportModuleIsValid.ps1 @@ -6,20 +6,20 @@ function Test-ImportModuleIsValid { .DESCRIPTION Test that the Import-Module commands contain a -Name parameter, and one of RequiredVersion, MinimumVersion or MaximumVersion - .PARAMETER ParsedFile + .PARAMETER ParsedContent An object containing the source file parsed into its Tokenizer components .PARAMETER ImportModuleTokens - An object containing the Import-Module calls found + An object containing the Import-Module tokens found .EXAMPLE - TestImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + TestImportModuleIsValid -ParsedContent $ParsedContent -ImportModuleTokens $importModuleTokens #> [CmdletBinding()] [OutputType([System.Exception], [System.Void])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFile, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [System.Object[]]$ImportModuleTokens ) @@ -32,7 +32,7 @@ function Test-ImportModuleIsValid { foreach ($token in $importModuleTokens) { # Get the full details of the command - $importModuleStatement = Get-TokenComponent -ParsedFileContent $ParsedFile -StartLine $token.StartLine + $importModuleStatement = Get-TokenComponent -ParsedContent $ParsedContent -StartLine $token.StartLine # Get the name of the module to be imported (for logging only) $name = ($importModuleStatement | Where-Object { $_.Type -eq "CommandArgument" } | Select-Object -First 1).Content diff --git a/Source/Tests/Unit/Convert-Help.Tests.ps1 b/Source/Tests/Unit/Convert-Help.Tests.ps1 index 527e9f5..f1da2d0 100644 --- a/Source/Tests/Unit/Convert-Help.Tests.ps1 +++ b/Source/Tests/Unit/Convert-Help.Tests.ps1 @@ -3,7 +3,7 @@ Describe "Convert-Help.Tests" { Context "Parameter Tests" { $mandatoryParameters = @( - 'HelpComment' + 'Help' ) foreach ($parameter in $mandatoryParameters) { @@ -25,7 +25,7 @@ Describe "Convert-Help.Tests" { It "should HelpComment type be string" -TestCases @{ 'parameter' = $parameter } { - (Get-Command -Name 'Convert-Help').Parameters['HelpComment'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name 'Convert-Help').Parameters['Help'].ParameterType.Name | Should -Be 'String' } @@ -37,7 +37,7 @@ Describe "Convert-Help.Tests" { { - Convert-Help -HelpComment $null + Convert-Help -Help $null } | Should -Throw @@ -48,7 +48,7 @@ Describe "Convert-Help.Tests" { { $helpComment = '##InvalidHelp##' - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment } | Should -Throw @@ -59,7 +59,7 @@ Describe "Convert-Help.Tests" { { $helpComment = '' - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment } | Should -Throw @@ -91,7 +91,7 @@ Describe "Convert-Help.Tests" { $($token) #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.ContainsKey($token) | Should -BeTrue } @@ -104,7 +104,7 @@ Describe "Convert-Help.Tests" { .PARAMETER Path #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.ContainsKey(".PARAMETER") | Should -BeTrue @@ -119,7 +119,7 @@ Describe "Convert-Help.Tests" { .PARAMETER Source #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.ContainsKey(".PARAMETER") | Should -BeTrue @@ -136,7 +136,7 @@ Describe "Convert-Help.Tests" { Function -Source #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.ContainsKey(".EXAMPLE") | Should -BeTrue @@ -150,7 +150,7 @@ Describe "Convert-Help.Tests" { .DUMMY #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.ContainsKey(".DUMMY") | Should -BeFalse @@ -163,7 +163,7 @@ Describe "Convert-Help.Tests" { .NOTES #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.ContainsKey(".DUMMY") | Should -BeFalse $help.ContainsKey(".NOTES") | Should -BeTrue @@ -178,7 +178,7 @@ Describe "Convert-Help.Tests" { #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment ([string]::IsNullOrEmpty($help.".SYNOPSIS".Text)) | Should -BeTrue @@ -193,7 +193,7 @@ Describe "Convert-Help.Tests" { .SYNOPSIS #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment ([string]::IsNullOrEmpty($help.".SYNOPSIS".Text)) | Should -BeTrue @@ -213,7 +213,7 @@ Describe "Convert-Help.Tests" { The Path parameter #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.".SYNOPSIS".Text | Should -BeExactly "The SYNOPSIS property" $help.".DESCRIPTION".Text | Should -BeExactly "The DESCRIPTION property" @@ -235,7 +235,7 @@ Describe "Convert-Help.Tests" { The Path parameter #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.".SYNOPSIS".Text | Should -BeExactly "" $help.".DESCRIPTION".Text | Should -BeExactly "The DESCRIPTION property" @@ -256,7 +256,7 @@ Describe "Convert-Help.Tests" { The Path parameter #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.".SYNOPSIS".Text | Should -BeExactly $null $help.".DESCRIPTION".Text | Should -BeExactly "The DESCRIPTION property" @@ -278,7 +278,7 @@ Describe "Convert-Help.Tests" { #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.".SYNOPSIS".Text | Should -BeExactly "" $help.".DESCRIPTION".Text | Should -BeExactly "" @@ -297,7 +297,7 @@ Describe "Convert-Help.Tests" { .PARAMETER Path #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.".SYNOPSIS".Text | Should -BeExactly $null $help.".DESCRIPTION".Text | Should -BeExactly $null @@ -319,7 +319,7 @@ Describe "Convert-Help.Tests" { The Path parameter #>" - $help = Convert-Help -HelpComment $helpComment + $help = Convert-Help -Help $helpComment $help.".SYNOPSIS".LineNumber | Should -BeExactly 1 $help.".DESCRIPTION".LineNumber | Should -BeExactly 3 diff --git a/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 b/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 index 18bcf14..e3a2967 100644 --- a/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 +++ b/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 @@ -3,8 +3,8 @@ Describe "Get-FunctionCount.Tests" { Context "Parameter Tests" { $mandatoryParameters = @( - 'ModuleFile' - 'ManifestFile' + 'ModulePath' + 'ManifestPath' ) foreach ($parameter in $mandatoryParameters) { @@ -18,15 +18,15 @@ Describe "Get-FunctionCount.Tests" { } - It "should ModuleFile type be String" -TestCases @{ 'parameter' = $parameter } { + It "should ModulePath type be String" -TestCases @{ 'parameter' = $parameter } { - (Get-Command -Name 'Get-FunctionCount').Parameters['ModuleFile'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name 'Get-FunctionCount').Parameters['ModulePath'].ParameterType.Name | Should -Be 'String' } - It "should ManifestFile type be String" -TestCases @{ 'parameter' = $parameter } { + It "should ManifestPath type be String" -TestCases @{ 'parameter' = $parameter } { - (Get-Command -Name 'Get-FunctionCount').Parameters['ManifestFile'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name 'Get-FunctionCount').Parameters['ManifestPath'].ParameterType.Name | Should -Be 'String' } @@ -36,8 +36,8 @@ Describe "Get-FunctionCount.Tests" { BeforeAll { - $moduleFile = Join-Path -Path $TestDrive -ChildPath 'test1.psm1' - $manifestFile = Join-Path -Path $TestDrive -ChildPath 'test1.psd1' + $ModulePath = Join-Path -Path $TestDrive -ChildPath 'test1.psm1' + $ManifestPath = Join-Path -Path $TestDrive -ChildPath 'test1.psd1' } @@ -45,7 +45,7 @@ Describe "Get-FunctionCount.Tests" { { - Get-ParsedFile -FunctionCount $null -ManifestFile $null + Get-ParsedFile -FunctionCount $null -ManifestPath $null } | Should -Throw @@ -54,14 +54,14 @@ Describe "Get-FunctionCount.Tests" { It "should find one function with matching module and manifest" { $fileContent = "function Get-FileContent {}" - Set-Content -Path $moduleFile -Value $fileContent + Set-Content -Path $ModulePath -Value $fileContent - New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent') + New-ModuleManifest -Path $ManifestPath -FunctionsToExport @('Get-FileContent') - Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(1, 1, 1, 1) + Get-FunctionCount -Module $ModulePath -Manifest $ManifestPath | Should -BeExactly @(1, 1, 1, 1) - Remove-Item -Path $moduleFile -Force - Remove-Item -Path $manifestFile -Force + Remove-Item -Path $ModulePath -Force + Remove-Item -Path $ManifestPath -Force } @@ -69,56 +69,56 @@ Describe "Get-FunctionCount.Tests" { $fileContent = "function Get-FileContent {} function Get-FileContent2 {}" - Set-Content -Path $moduleFile -Value $fileContent + Set-Content -Path $ModulePath -Value $fileContent - New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent', 'Get-FileContent2') + New-ModuleManifest -Path $ManifestPath -FunctionsToExport @('Get-FileContent', 'Get-FileContent2') - Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(2, 2, 2, 2) + Get-FunctionCount -Module $ModulePath -Manifest $ManifestPath | Should -BeExactly @(2, 2, 2, 2) - Remove-Item -Path $moduleFile -Force - Remove-Item -Path $manifestFile -Force + Remove-Item -Path $ModulePath -Force + Remove-Item -Path $ManifestPath -Force } It "should not find any function in manifest or module with empty manifest" { $fileContent = "function Get-FileContent {}" - Set-Content -Path $moduleFile -Value $fileContent + Set-Content -Path $ModulePath -Value $fileContent - New-ModuleManifest -Path $manifestFile + New-ModuleManifest -Path $ManifestPath - Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(0, 0, 0, 0) + Get-FunctionCount -Module $ModulePath -Manifest $ManifestPath | Should -BeExactly @(0, 0, 0, 0) - Remove-Item -Path $moduleFile -Force - Remove-Item -Path $manifestFile -Force + Remove-Item -Path $ModulePath -Force + Remove-Item -Path $ManifestPath -Force } It "should not find function in manifest and module with mismatched functions between manifest and module" { $fileContent = "function Get-FileContent {}" - Set-Content -Path $moduleFile -Value $fileContent + Set-Content -Path $ModulePath -Value $fileContent - New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent2') + New-ModuleManifest -Path $ManifestPath -FunctionsToExport @('Get-FileContent2') - Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(1, 0, 1, 0) + Get-FunctionCount -Module $ModulePath -Manifest $ManifestPath | Should -BeExactly @(1, 0, 1, 0) - Remove-Item -Path $moduleFile -Force - Remove-Item -Path $manifestFile -Force + Remove-Item -Path $ModulePath -Force + Remove-Item -Path $ManifestPath -Force } It "should not find function in module with function in manifest and not in module" { $fileContent = "function Get-FileContent {}" - Set-Content -Path $moduleFile -Value $fileContent + Set-Content -Path $ModulePath -Value $fileContent - New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent', 'Get-FileContent2') + New-ModuleManifest -Path $ManifestPath -FunctionsToExport @('Get-FileContent', 'Get-FileContent2') - Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(2, 1, 1, 1) + Get-FunctionCount -Module $ModulePath -Manifest $ManifestPath | Should -BeExactly @(2, 1, 1, 1) - Remove-Item -Path $moduleFile -Force - Remove-Item -Path $manifestFile -Force + Remove-Item -Path $ModulePath -Force + Remove-Item -Path $ManifestPath -Force } @@ -126,14 +126,14 @@ Describe "Get-FunctionCount.Tests" { $fileContent = "function Get-FileContent {} function Get-FileContent2 {}" - Set-Content -Path $moduleFile -Value $fileContent + Set-Content -Path $ModulePath -Value $fileContent - New-ModuleManifest -Path $manifestFile -FunctionsToExport @('Get-FileContent') + New-ModuleManifest -Path $ManifestPath -FunctionsToExport @('Get-FileContent') - Get-FunctionCount -Module $moduleFile -Manifest $manifestFile | Should -BeExactly @(1, 1, 2, 1) + Get-FunctionCount -Module $ModulePath -Manifest $ManifestPath | Should -BeExactly @(1, 1, 2, 1) - Remove-Item -Path $moduleFile -Force - Remove-Item -Path $manifestFile -Force + Remove-Item -Path $ModulePath -Force + Remove-Item -Path $ManifestPath -Force } diff --git a/Source/Tests/Unit/Get-Token.Tests.ps1 b/Source/Tests/Unit/Get-Token.Tests.ps1 index ab5b0c9..9415374 100644 --- a/Source/Tests/Unit/Get-Token.Tests.ps1 +++ b/Source/Tests/Unit/Get-Token.Tests.ps1 @@ -3,7 +3,7 @@ Describe "Get-Token.Tests" { Context "Parameter Tests" { $mandatoryParameters = @( - 'ParsedFileContent' + 'ParsedContent' 'Type' 'Content' ) @@ -19,9 +19,9 @@ Describe "Get-Token.Tests" { } - It "should ParsedFileContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should ParsedContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { - (Get-Command -Name 'Get-Token').Parameters['ParsedFileContent'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name 'Get-Token').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' } @@ -45,7 +45,7 @@ Describe "Get-Token.Tests" { { - Get-Token -ParsedFileContent $null -Type $null -Content $null + Get-Token -ParsedContent $null -Type $null -Content $null } | Should -Throw @@ -55,7 +55,7 @@ Describe "Get-Token.Tests" { BeforeAll { - $parsedFileContent = @( + $ParsedContent = @( @{ "Content" = "function" "Type" = "Keyword" @@ -101,19 +101,19 @@ Describe "Get-Token.Tests" { It "should find token where parameters are valid" { - $token = Get-Token -ParsedFileContent $parsedFileContent -Type "Keyword" -Content "Function" + $token = Get-Token -ParsedContent $ParsedContent -Type "Keyword" -Content "Function" for ($x = 0; $x -lt $parsedModule.Count; $x++) { ( - ($token[$x].StartLine -eq $parsedFileContent[$x].StartLine) -and - ($token[$x].Content -eq $parsedFileContent[$x].Content) -and - ($token[$x].Type -eq $parsedFileContent[$x].Type) -and - ($token[$x].Start -eq $parsedFileContent[$x].Start) -and - ($token[$x].Length -eq $parsedFileContent[$x].Length) -and - ($token[$x].StartColumn -eq $parsedFileContent[$x].StartColumn) -and - ($token[$x].EndLine -eq $parsedFileContent[$x].EndLine) -and - ($token[$x].EndColumn -eq $parsedFileContent[$x].EndColumn) + ($token[$x].StartLine -eq $ParsedContent[$x].StartLine) -and + ($token[$x].Content -eq $ParsedContent[$x].Content) -and + ($token[$x].Type -eq $ParsedContent[$x].Type) -and + ($token[$x].Start -eq $ParsedContent[$x].Start) -and + ($token[$x].Length -eq $ParsedContent[$x].Length) -and + ($token[$x].StartColumn -eq $ParsedContent[$x].StartColumn) -and + ($token[$x].EndLine -eq $ParsedContent[$x].EndLine) -and + ($token[$x].EndColumn -eq $ParsedContent[$x].EndColumn) ) | Should -BeTrue } @@ -122,7 +122,7 @@ Describe "Get-Token.Tests" { It "should not find token where parameters are invalid" { - $token = (Get-Token -ParsedFileContent $parsedFileContent -Type "Unknown" -Content "Data") + $token = (Get-Token -ParsedContent $ParsedContent -Type "Unknown" -Content "Data") $token | Should -BeNullOrEmpty diff --git a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 index c2a96bd..d270f08 100644 --- a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 +++ b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 @@ -3,7 +3,7 @@ Describe "Get-TokenComponent.Tests" { Context "Parameter Tests" { $mandatoryParameters = @( - 'ParsedFileContent' + 'ParsedContent' 'StartLine' ) @@ -18,9 +18,9 @@ Describe "Get-TokenComponent.Tests" { } - It "should ParsedFileContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should ParsedContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { - (Get-Command -Name 'Get-TokenComponent').Parameters['ParsedFileContent'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name 'Get-TokenComponent').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' } @@ -38,14 +38,14 @@ Describe "Get-TokenComponent.Tests" { { - Get-TokenComponent -ParsedFileContent $null -StartLine $null + Get-TokenComponent -ParsedContent $null -StartLine $null } | Should -Throw } BeforeAll { - $parsedFileContent = @( + $ParsedContent = @( @{ "Content" = "function" "Type" = "Keyword" @@ -91,18 +91,18 @@ Describe "Get-TokenComponent.Tests" { It "should find token where 'StartLine' is valid" { - $token = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine 1 + $token = Get-TokenComponent -ParsedContent $ParsedContent -StartLine 1 - Compare-Object -ReferenceObject $token.Values -DifferenceObject $ParsedFileContent.values | Should -BeNullOrEmpty + Compare-Object -ReferenceObject $token.Values -DifferenceObject $ParsedContent.values | Should -BeNullOrEmpty } It "should not find token where 'StartLine' is invalid" { - $token = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine 3 + $token = Get-TokenComponent -ParsedContent $ParsedContent -StartLine 3 $token | Should -BeNullOrEmpty - $token = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine $null + $token = Get-TokenComponent -ParsedContent $ParsedContent -StartLine $null $token | Should -BeNullOrEmpty } diff --git a/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 b/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 index 0453baf..334be5a 100644 --- a/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 +++ b/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 @@ -3,7 +3,7 @@ Describe "Get-TokenMarker.Tests" { Context "Parameter Tests" { $mandatoryParameters = @( - 'ParsedFileContent' + 'ParsedContent' 'Type' 'Content' ) @@ -19,9 +19,9 @@ Describe "Get-TokenMarker.Tests" { } - It "should ParsedFileContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should ParsedContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { - (Get-Command -Name 'Get-TokenMarker').Parameters['ParsedFileContent'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name 'Get-TokenMarker').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' } @@ -45,13 +45,13 @@ Describe "Get-TokenMarker.Tests" { { - Get-TokenMarker -ParsedFileContent $null -Type $null -Content $null + Get-TokenMarker -ParsedContent $null -Type $null -Content $null } | Should -Throw } - $parsedFileContent = @( + $ParsedContent = @( @{ "Content" = "function" "Type" = "Keyword" @@ -105,35 +105,35 @@ Describe "Get-TokenMarker.Tests" { "EndColumn" = 25 } - It "should find 'CommandArgument' type with 'Get-FileContent' value" -TestCases @{ 'parsedFileContent' = $parsedFileContent; 'tokenMatch' = $tokenMatch } { + It "should find 'CommandArgument' type with 'Get-FileContent' value" -TestCases @{ 'ParsedContent' = $ParsedContent; 'tokenMatch' = $tokenMatch } { - $token = Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type "CommandArgument" -Content "Get-FileContent" + $token = Get-TokenMarker -ParsedContent $ParsedContent -Type "CommandArgument" -Content "Get-FileContent" Compare-Object -ReferenceObject $token.Values -DifferenceObject $tokenMatch.values | Should -BeNullOrEmpty } - It "should not find 'Dummy' type with 'Get-FileContent' value" -TestCases @{ 'parsedFileContent' = $parsedFileContent } { + It "should not find 'Dummy' type with 'Get-FileContent' value" -TestCases @{ 'ParsedContent' = $ParsedContent } { - $token = Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type "Dummy" -Content "Get-FileContent" + $token = Get-TokenMarker -ParsedContent $ParsedContent -Type "Dummy" -Content "Get-FileContent" $token | Should -BeNullOrEmpty } - It "should not find 'CommandArgument' type with 'Dummy' value" -TestCases @{ 'parsedFileContent' = $parsedFileContent } { + It "should not find 'CommandArgument' type with 'Dummy' value" -TestCases @{ 'ParsedContent' = $ParsedContent } { - $token = Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type "CommandArgument" -Content "Dummy" + $token = Get-TokenMarker -ParsedContent $ParsedContent -Type "CommandArgument" -Content "Dummy" $token | Should -BeNullOrEmpty } - It "should throw with 'null' type and 'null' value" -TestCases @{ 'parsedFileContent' = $parsedFileContent } { + It "should throw with 'null' type and 'null' value" -TestCases @{ 'ParsedContent' = $ParsedContent } { { - Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type $null -Content $null + Get-TokenMarker -ParsedContent $ParsedContent -Type $null -Content $null } | Should -Throw } diff --git a/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 b/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 index a12b1ec..677e8bc 100644 --- a/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 +++ b/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 @@ -3,7 +3,7 @@ Describe "Test-ImportModuleIsValid.Tests" { Context "Parameter Tests" { $mandatoryParameters = @( - 'ParsedFile' + 'ParsedContent' 'ImportModuleTokens' ) @@ -18,9 +18,9 @@ Describe "Test-ImportModuleIsValid.Tests" { } - It "should ParsedFile type be Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should ParsedContent type be Object[]" -TestCases @{ 'parameter' = $parameter } { - (Get-Command -Name 'Test-ImportModuleIsValid').Parameters['ParsedFile'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name 'Test-ImportModuleIsValid').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' } @@ -38,7 +38,7 @@ Describe "Test-ImportModuleIsValid.Tests" { { - Test-ImportModuleIsValid -ParsedFile $null -ImportModuleTokens $null + Test-ImportModuleIsValid -ParsedContent $null -ImportModuleTokens $null } | Should -Throw @@ -48,7 +48,7 @@ Describe "Test-ImportModuleIsValid.Tests" { { - $parsedFile = @( + $ParsedContent = @( @{ "Content" = "Import-Module" "Type" = "Command" @@ -101,9 +101,9 @@ Describe "Test-ImportModuleIsValid.Tests" { } ) - $importModuleTokens = $parsedFile + $importModuleTokens = $ParsedContent - Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + Test-ImportModuleIsValid -ParsedContent $ParsedContent -ImportModuleTokens $importModuleTokens } | Should -Not -Throw @@ -113,7 +113,7 @@ Describe "Test-ImportModuleIsValid.Tests" { { - $parsedFile = @( + $ParsedContent = @( @{ "Content" = "Import-Module" "Type" = "Command" @@ -136,11 +136,11 @@ Describe "Test-ImportModuleIsValid.Tests" { } ) - $importModuleTokens = $parsedFile + $importModuleTokens = $ParsedContent - Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + Test-ImportModuleIsValid -ParsedContent $ParsedContent -ImportModuleTokens $importModuleTokens - } | Should -Not -Throw + } | Should -Throw } @@ -148,7 +148,7 @@ Describe "Test-ImportModuleIsValid.Tests" { { - $parsedFile = @( + $ParsedContent = @( @{ "Content" = "Import-Module" "Type" = "Command" @@ -191,11 +191,11 @@ Describe "Test-ImportModuleIsValid.Tests" { } ) - $importModuleTokens = $parsedFile + $importModuleTokens = $ParsedContent - Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + Test-ImportModuleIsValid -ParsedContent $ParsedContent -ImportModuleTokens $importModuleTokens - } | Should -Not -Throw + } | Should -Throw } @@ -203,7 +203,7 @@ Describe "Test-ImportModuleIsValid.Tests" { { - $parsedFile = @( + $ParsedContent = @( @{ "Content" = "Import-Module" "Type" = "Command" @@ -236,11 +236,11 @@ Describe "Test-ImportModuleIsValid.Tests" { } ) - $importModuleTokens = $parsedFile + $importModuleTokens = $ParsedContent - Test-ImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + Test-ImportModuleIsValid -ParsedContent $ParsedContent -ImportModuleTokens $importModuleTokens - } | Should -Not -Throw + } | Should -Throw } From 7475b7b273e28a1a58ccac4b0fbdfa3286deff95 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 13:18:41 +0000 Subject: [PATCH 24/33] Updates to follow Pester 5 test guidelines --- Source/Tests/Unit/Convert-Help.Tests.ps1 | 79 ++++----- .../Unit/Export-FunctionsFromModule.Tests.ps1 | 30 ++-- Source/Tests/Unit/Get-FileContent.Tests.ps1 | 26 +-- Source/Tests/Unit/Get-FileList.Tests.ps1 | 30 ++-- Source/Tests/Unit/Get-FunctionCount.Tests.ps1 | 30 ++-- Source/Tests/Unit/Get-ParsedContent.Tests.ps1 | 27 +-- Source/Tests/Unit/Get-ParsedFile.Tests.ps1 | 26 +-- .../Tests/Unit/Get-ScriptParameters.Tests.ps1 | 26 +-- Source/Tests/Unit/Get-Token.Tests.ps1 | 165 +++++++++--------- .../Tests/Unit/Get-TokenComponent.Tests.ps1 | 50 +++--- Source/Tests/Unit/Get-TokenMarker.Tests.ps1 | 155 ++++++++-------- .../Unit/Invoke-PSQualityCheck.Tests.ps1 | 82 ++------- .../Unit/Test-HelpForRequiredTokens.Tests.ps1 | 26 +-- .../Test-HelpForUnspecifiedTokens.Tests.ps1 | 26 +-- .../Test-HelpTokensCountIsValid.Tests.ps1 | 26 +-- .../Unit/Test-HelpTokensParamsMatch.Tests.ps1 | 30 ++-- .../Unit/Test-HelpTokensTextIsValid.Tests.ps1 | 26 +-- .../Unit/Test-ImportModuleIsValid.Tests.ps1 | 30 ++-- .../Test-ParameterVariablesHaveType.Tests.ps1 | 30 ++-- 19 files changed, 432 insertions(+), 488 deletions(-) diff --git a/Source/Tests/Unit/Convert-Help.Tests.ps1 b/Source/Tests/Unit/Convert-Help.Tests.ps1 index f1da2d0..bcbbbdc 100644 --- a/Source/Tests/Unit/Convert-Help.Tests.ps1 +++ b/Source/Tests/Unit/Convert-Help.Tests.ps1 @@ -1,31 +1,29 @@ Describe "Convert-Help.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'Help'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'Help' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Convert-Help" + } - (Get-Command -Name 'Convert-Help').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Convert-Help').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - It "should $parameter not belong to a parameter set" -TestCases @{ 'parameter' = $parameter } { + } - (Get-Command -Name 'Convert-Help').Parameters[$parameter].ParameterSets.Keys | Should -Be '__AllParameterSets' + It "should $Name not belong to a parameter set" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should HelpComment type be string" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Convert-Help').Parameters['Help'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } @@ -65,36 +63,31 @@ Describe "Convert-Help.Tests" { } - $helpTokens = @( - '.SYNOPSIS' - '.DESCRIPTION' - '.PARAMETER' - '.EXAMPLE' - '.INPUTS' - '.OUTPUTS' - '.NOTES' - '.LINK' - '.COMPONENT' - '.ROLE' - '.FUNCTIONALITY' - '.FORWARDHELPTARGETNAME' - '.FORWARDHELPCATEGORY' - '.REMOTEHELPRUNSPACE' - '.EXTERNALHELP' - ) - - foreach ($token in $helpTokens) { - - It "should find $token in help" -TestCases @{ 'token' = $token } { + It "should find in help" -ForEach @( + @{ 'Token' = '.SYNOPSIS' } + @{ 'Token' = '.DESCRIPTION' } + @{ 'Token' = '.PARAMETER' } + @{ 'Token' = '.EXAMPLE' } + @{ 'Token' = '.INPUTS' } + @{ 'Token' = '.OUTPUTS' } + @{ 'Token' = '.NOTES' } + @{ 'Token' = '.LINK' } + @{ 'Token' = '.COMPONENT' } + @{ 'Token' = '.ROLE' } + @{ 'Token' = '.FUNCTIONALITY' } + @{ 'Token' = '.FORWARDHELPTARGETNAME' } + @{ 'Token' = '.FORWARDHELPCATEGORY' } + @{ 'Token' = '.REMOTEHELPRUNSPACE' } + @{ 'Token' = '.EXTERNALHELP' } + ) { - $helpComment = "<# - $($token) - #>" + $helpComment = "<# + $($token) + #>" - $help = Convert-Help -Help $helpComment + $help = Convert-Help -Help $helpComment - $help.ContainsKey($token) | Should -BeTrue - } + $help.ContainsKey($token) | Should -BeTrue } diff --git a/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 b/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 index 1eed392..84d895b 100644 --- a/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 +++ b/Source/Tests/Unit/Export-FunctionsFromModule.Tests.ps1 @@ -1,32 +1,30 @@ Describe "Export-FunctionsFromModule.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'Path'; 'Type' = 'String' } + @{ 'Name' = 'ExtractPath'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'Path' - 'ExtractPath' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Export-FunctionsFromModule" + } - (Get-Command -Name 'Export-FunctionsFromModule').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Export-FunctionsFromModule').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should Path type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Export-FunctionsFromModule').Parameters['Path'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should ExtractPath type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Export-FunctionsFromModule').Parameters['ExtractPath'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Get-FileContent.Tests.ps1 b/Source/Tests/Unit/Get-FileContent.Tests.ps1 index 047f8a3..93339c4 100644 --- a/Source/Tests/Unit/Get-FileContent.Tests.ps1 +++ b/Source/Tests/Unit/Get-FileContent.Tests.ps1 @@ -1,25 +1,29 @@ Describe "Get-FileContent.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'Path'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'Path' - ) + BeforeAll { + $commandletUnderTest = "Get-FileContent" + } + + It "should have $Name as a mandatory parameter" { - foreach ($parameter in $mandatoryParameters) { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + } - (Get-Command -Name 'Get-FileContent').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-FileContent').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should $Name not belong to a parameter set" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should Path type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-FileContent').Parameters['Path'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Get-FileList.Tests.ps1 b/Source/Tests/Unit/Get-FileList.Tests.ps1 index 67d625b..9395b59 100644 --- a/Source/Tests/Unit/Get-FileList.Tests.ps1 +++ b/Source/Tests/Unit/Get-FileList.Tests.ps1 @@ -1,32 +1,30 @@ Describe "Get-FileList.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -ForEach @( + @{ 'Name' = 'Path'; 'Type' = 'String' } + @{ 'Name' = 'Extension'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'Path' - 'Extension' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Get-FileList" + } - (Get-Command -Name 'Get-FileList').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-FileList').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should Path type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Get-FileList').Parameters['Path'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should Extension type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-FileList').Parameters['Extension'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 b/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 index e3a2967..c3e44f1 100644 --- a/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 +++ b/Source/Tests/Unit/Get-FunctionCount.Tests.ps1 @@ -1,32 +1,30 @@ Describe "Get-FunctionCount.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -ForEach @( + @{ 'Name' = 'ModulePath'; 'Type' = 'String' } + @{ 'Name' = 'ManifestPath'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'ModulePath' - 'ManifestPath' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Get-FunctionCount" + } - (Get-Command -Name 'Get-FunctionCount').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-FunctionCount').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should ModulePath type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Get-FunctionCount').Parameters['ModulePath'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should ManifestPath type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-FunctionCount').Parameters['ManifestPath'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 b/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 index fe95a40..083704a 100644 --- a/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 +++ b/Source/Tests/Unit/Get-ParsedContent.Tests.ps1 @@ -1,26 +1,29 @@ Describe "Get-ParsedContent.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'Content'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'Content' - ) + BeforeAll { + $commandletUnderTest = "Get-ParsedContent" + } - # TODO: This needs replacing with the correct Pester 5 way of doing things, but it does work - foreach ($parameter in $mandatoryParameters) { + It "should have $Name as a mandatory parameter" { - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - (Get-Command -Name 'Get-ParsedContent').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-ParsedContent').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + } - } + It "should $Name not belong to a parameter set" { + + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should Content type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-ParsedContent').Parameters['Content'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 b/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 index 6d6856f..8c2cd1f 100644 --- a/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 +++ b/Source/Tests/Unit/Get-ParsedFile.Tests.ps1 @@ -1,25 +1,29 @@ Describe "Get-ParsedFile.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'Path'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'Path' - ) + BeforeAll { + $commandletUnderTest = "Get-ParsedFile" + } - foreach ($parameter in $mandatoryParameters) { + It "should have $Name as a mandatory parameter" { - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - (Get-Command -Name 'Get-ParsedFile').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-ParsedFile').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + } - } + It "should $Name not belong to a parameter set" { + + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should Path type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-ParsedFile').Parameters['Path'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 b/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 index 03284fd..8e0995c 100644 --- a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 +++ b/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 @@ -1,25 +1,29 @@ Describe "Get-ScriptParameters.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -ForEach @( + @{ 'Name' = 'Content'; 'Type' = 'String' } + ) { - $mandatoryParameters = @( - 'Content' - ) + BeforeAll { + $commandletUnderTest = "Get-ScriptParameters" + } + + It "should have $Name as a mandatory parameter" { - foreach ($parameter in $mandatoryParameters) { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + } - (Get-Command -Name 'Get-ScriptParameters').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-ScriptParameters').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should $Name not belong to a parameter set" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should Content type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-ScriptParameters').Parameters['Content'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Get-Token.Tests.ps1 b/Source/Tests/Unit/Get-Token.Tests.ps1 index 9415374..94fe974 100644 --- a/Source/Tests/Unit/Get-Token.Tests.ps1 +++ b/Source/Tests/Unit/Get-Token.Tests.ps1 @@ -1,39 +1,31 @@ Describe "Get-Token.Tests" { - Context "Parameter Tests" { - - $mandatoryParameters = @( - 'ParsedContent' - 'Type' - 'Content' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { - - (Get-Command -Name 'Get-Token').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-Token').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue - - } - + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'ParsedContent'; 'Type' = 'Object[]' } + @{ 'Name' = 'Type'; 'Type' = 'String' } + @{ 'Name' = 'Content'; 'Type' = 'String' } + ) { + + BeforeAll { + $commandletUnderTest = "Get-Token" } - It "should ParsedContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should have $Name as a mandatory parameter" { - (Get-Command -Name 'Get-Token').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should Type type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Get-Token').Parameters['Type'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should Content type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-Token').Parameters['Content'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } @@ -41,6 +33,51 @@ Describe "Get-Token.Tests" { Context "Function tests" { + BeforeAll { + $ParsedContent = @( + @{ + "Content" = "function" + "Type" = "Keyword" + "Start" = 0 + "Length" = 8 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 9 + }, + @{ + "Content" = "Get-FileContent" + "Type" = "CommandArgument" + "Start" = 9 + "Length" = 15 + "StartLine" = 1 + "StartColumn" = 10 + "EndLine" = 1 + "EndColumn" = 25 + }, + @{ + "Content" = "{" + "Type" = "GroupStart" + "Start" = 25 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 26 + "EndLine" = 1 + "EndColumn" = 27 + }, + @{ + "Content" = "}" + "Type" = "GroupEnd" + "Start" = 26 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 27 + "EndLine" = 1 + "EndColumn" = 28 + } + ) + } + It "should throw when passing null parameters" { { @@ -51,80 +88,34 @@ Describe "Get-Token.Tests" { } - } - - - BeforeAll { - $ParsedContent = @( - @{ - "Content" = "function" - "Type" = "Keyword" - "Start" = 0 - "Length" = 8 - "StartLine" = 1 - "StartColumn" = 1 - "EndLine" = 1 - "EndColumn" = 9 - }, - @{ - "Content" = "Get-FileContent" - "Type" = "CommandArgument" - "Start" = 9 - "Length" = 15 - "StartLine" = 1 - "StartColumn" = 10 - "EndLine" = 1 - "EndColumn" = 25 - }, - @{ - "Content" = "{" - "Type" = "GroupStart" - "Start" = 25 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 26 - "EndLine" = 1 - "EndColumn" = 27 - }, - @{ - "Content" = "}" - "Type" = "GroupEnd" - "Start" = 26 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 27 - "EndLine" = 1 - "EndColumn" = 28 - } - ) - } + It "should find token where parameters are valid" { - It "should find token where parameters are valid" { + $token = Get-Token -ParsedContent $ParsedContent -Type "Keyword" -Content "Function" - $token = Get-Token -ParsedContent $ParsedContent -Type "Keyword" -Content "Function" + for ($x = 0; $x -lt $parsedModule.Count; $x++) { - for ($x = 0; $x -lt $parsedModule.Count; $x++) { + ( + ($token[$x].StartLine -eq $ParsedContent[$x].StartLine) -and + ($token[$x].Content -eq $ParsedContent[$x].Content) -and + ($token[$x].Type -eq $ParsedContent[$x].Type) -and + ($token[$x].Start -eq $ParsedContent[$x].Start) -and + ($token[$x].Length -eq $ParsedContent[$x].Length) -and + ($token[$x].StartColumn -eq $ParsedContent[$x].StartColumn) -and + ($token[$x].EndLine -eq $ParsedContent[$x].EndLine) -and + ($token[$x].EndColumn -eq $ParsedContent[$x].EndColumn) + ) | Should -BeTrue - ( - ($token[$x].StartLine -eq $ParsedContent[$x].StartLine) -and - ($token[$x].Content -eq $ParsedContent[$x].Content) -and - ($token[$x].Type -eq $ParsedContent[$x].Type) -and - ($token[$x].Start -eq $ParsedContent[$x].Start) -and - ($token[$x].Length -eq $ParsedContent[$x].Length) -and - ($token[$x].StartColumn -eq $ParsedContent[$x].StartColumn) -and - ($token[$x].EndLine -eq $ParsedContent[$x].EndLine) -and - ($token[$x].EndColumn -eq $ParsedContent[$x].EndColumn) - ) | Should -BeTrue + } } - } + It "should not find token where parameters are invalid" { - It "should not find token where parameters are invalid" { + $token = (Get-Token -ParsedContent $ParsedContent -Type "Unknown" -Content "Data") - $token = (Get-Token -ParsedContent $ParsedContent -Type "Unknown" -Content "Data") + $token | Should -BeNullOrEmpty - $token | Should -BeNullOrEmpty + } } diff --git a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 index d270f08..d41a94b 100644 --- a/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 +++ b/Source/Tests/Unit/Get-TokenComponent.Tests.ps1 @@ -1,32 +1,30 @@ Describe "Get-TokenComponent.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -ForEach @( + @{ 'Name' = 'ParsedContent'; 'Type' = 'Object[]' } + @{ 'Name' = 'StartLine'; 'Type' = 'Int32' } + ) { - $mandatoryParameters = @( - 'ParsedContent' - 'StartLine' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Get-TokenComponent" + } - (Get-Command -Name 'Get-TokenComponent').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-TokenComponent').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should ParsedContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Get-TokenComponent').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should StartLine type be Int" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-TokenComponent').Parameters['StartLine'].ParameterType.Name | Should -Be 'Int32' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } @@ -34,16 +32,6 @@ Describe "Get-TokenComponent.Tests" { Context "Function tests" { - It "should throw when passing null parameters" { - - { - - Get-TokenComponent -ParsedContent $null -StartLine $null - - } | Should -Throw - - } - BeforeAll { $ParsedContent = @( @{ @@ -89,6 +77,16 @@ Describe "Get-TokenComponent.Tests" { ) } + It "should throw when passing null parameters" { + + { + + Get-TokenComponent -ParsedContent $null -StartLine $null + + } | Should -Throw + + } + It "should find token where 'StartLine' is valid" { $token = Get-TokenComponent -ParsedContent $ParsedContent -StartLine 1 diff --git a/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 b/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 index 334be5a..dfd1032 100644 --- a/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 +++ b/Source/Tests/Unit/Get-TokenMarker.Tests.ps1 @@ -1,39 +1,31 @@ Describe "Get-TokenMarker.Tests" { - Context "Parameter Tests" { - - $mandatoryParameters = @( - 'ParsedContent' - 'Type' - 'Content' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { - - (Get-Command -Name 'Get-TokenMarker').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Get-TokenMarker').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue - - } - + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'ParsedContent'; 'Type' = 'Object[]' } + @{ 'Name' = 'Type'; 'Type' = 'String' } + @{ 'Name' = 'Content'; 'Type' = 'String' } + ) { + + BeforeAll { + $commandletUnderTest = "Get-TokenMarker" } - It "should ParsedContent type be System.Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should have $Name as a mandatory parameter" { - (Get-Command -Name 'Get-TokenMarker').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should Type type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Get-TokenMarker').Parameters['Type'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should Content type be String" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Get-TokenMarker').Parameters['Content'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } @@ -41,28 +33,51 @@ Describe "Get-TokenMarker.Tests" { Context "Function tests" { - It "should throw when passing null parameters" { - - { - - Get-TokenMarker -ParsedContent $null -Type $null -Content $null - - } | Should -Throw - - } - - $ParsedContent = @( - @{ - "Content" = "function" - "Type" = "Keyword" - "Start" = 0 - "Length" = 8 - "StartLine" = 1 - "StartColumn" = 1 - "EndLine" = 1 - "EndColumn" = 9 - }, - @{ + BeforeAll { + $ParsedContent = @( + @{ + "Content" = "function" + "Type" = "Keyword" + "Start" = 0 + "Length" = 8 + "StartLine" = 1 + "StartColumn" = 1 + "EndLine" = 1 + "EndColumn" = 9 + }, + @{ + "Content" = "Get-FileContent" + "Type" = "CommandArgument" + "Start" = 9 + "Length" = 15 + "StartLine" = 1 + "StartColumn" = 10 + "EndLine" = 1 + "EndColumn" = 25 + }, + @{ + "Content" = "{" + "Type" = "GroupStart" + "Start" = 25 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 26 + "EndLine" = 1 + "EndColumn" = 27 + }, + @{ + "Content" = "}" + "Type" = "GroupEnd" + "Start" = 26 + "Length" = 1 + "StartLine" = 1 + "StartColumn" = 27 + "EndLine" = 1 + "EndColumn" = 28 + } + ) + + $tokenMatch = @{ "Content" = "Get-FileContent" "Type" = "CommandArgument" "Start" = 9 @@ -71,41 +86,21 @@ Describe "Get-TokenMarker.Tests" { "StartColumn" = 10 "EndLine" = 1 "EndColumn" = 25 - }, - @{ - "Content" = "{" - "Type" = "GroupStart" - "Start" = 25 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 26 - "EndLine" = 1 - "EndColumn" = 27 - }, - @{ - "Content" = "}" - "Type" = "GroupEnd" - "Start" = 26 - "Length" = 1 - "StartLine" = 1 - "StartColumn" = 27 - "EndLine" = 1 - "EndColumn" = 28 } - ) - - $tokenMatch = @{ - "Content" = "Get-FileContent" - "Type" = "CommandArgument" - "Start" = 9 - "Length" = 15 - "StartLine" = 1 - "StartColumn" = 10 - "EndLine" = 1 - "EndColumn" = 25 + + } + + It "should throw when passing null parameters" { + + { + + Get-TokenMarker -ParsedContent $null -Type $null -Content $null + + } | Should -Throw + } - It "should find 'CommandArgument' type with 'Get-FileContent' value" -TestCases @{ 'ParsedContent' = $ParsedContent; 'tokenMatch' = $tokenMatch } { + It "should find 'CommandArgument' type with 'Get-FileContent' value" { $token = Get-TokenMarker -ParsedContent $ParsedContent -Type "CommandArgument" -Content "Get-FileContent" @@ -113,7 +108,7 @@ Describe "Get-TokenMarker.Tests" { } - It "should not find 'Dummy' type with 'Get-FileContent' value" -TestCases @{ 'ParsedContent' = $ParsedContent } { + It "should not find 'Dummy' type with 'Get-FileContent' value" { $token = Get-TokenMarker -ParsedContent $ParsedContent -Type "Dummy" -Content "Get-FileContent" @@ -121,7 +116,7 @@ Describe "Get-TokenMarker.Tests" { } - It "should not find 'CommandArgument' type with 'Dummy' value" -TestCases @{ 'ParsedContent' = $ParsedContent } { + It "should not find 'CommandArgument' type with 'Dummy' value" { $token = Get-TokenMarker -ParsedContent $ParsedContent -Type "CommandArgument" -Content "Dummy" @@ -129,7 +124,7 @@ Describe "Get-TokenMarker.Tests" { } - It "should throw with 'null' type and 'null' value" -TestCases @{ 'ParsedContent' = $ParsedContent } { + It "should throw with 'null' type and 'null' value" { { diff --git a/Source/Tests/Unit/Invoke-PSQualityCheck.Tests.ps1 b/Source/Tests/Unit/Invoke-PSQualityCheck.Tests.ps1 index e885c44..cc7c7d1 100644 --- a/Source/Tests/Unit/Invoke-PSQualityCheck.Tests.ps1 +++ b/Source/Tests/Unit/Invoke-PSQualityCheck.Tests.ps1 @@ -1,84 +1,32 @@ Describe "Invoke-PSQualityCheck.Tests" { - Context "Parameter Tests" { - - $mandatoryParameters = @( - 'Path' - 'File' - ) - - $optionalParameters = @( - 'SonarQubeRulesPath' - 'ShowCheckResults' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { - - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue - - } - - } - - foreach ($parameter in $optionalParameters) { - - It "should have $parameter as a optional parameter" -TestCases @{ 'parameter' = $parameter } { - - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters[$parameter].Attributes.Mandatory | Should -BeFalse - - } - - } - - It "should Path parameter belong to Path parameter set" { - - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['Path'].ParameterSets.Keys | Should -Contain 'Path' - - } - - It "should File parameter belong to File parameter set" { - - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['File'].ParameterSets.Keys | Should -Contain 'File' - - } - - It "should SonarQubeRulesPath parameter not belong to a parameter set" { - - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['SonarQubeRulesPath'].ParameterSets.Keys | Should -Be '__AllParameterSets' - - } - - It "should ShowCheckResults parameter not belong to a parameter set" { - - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['ShowCheckResults'].ParameterSets.Keys | Should -Be '__AllParameterSets' - - } - - It "should Path parameter type be string[]" { - - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['Path'].ParameterType.Name | Should -Be 'String[]' + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'Path'; 'Type' = 'String[]'; 'MandatoryFlag' = $true; 'ParameterSet' = 'Path' } + @{ 'Name' = 'File'; 'Type' = 'String[]'; 'MandatoryFlag' = $true; 'ParameterSet' = 'File' } + @{ 'Name' = 'SonarQubeRulesPath'; 'Type' = 'String'; 'MandatoryFlag' = $false; 'ParameterSet' = '__AllParameterSets' } + @{ 'Name' = 'ShowCheckResults'; 'Type' = 'SwitchParameter'; 'MandatoryFlag' = $false; 'ParameterSet' = '__AllParameterSets' } + ) { + BeforeAll { + $commandletUnderTest = "Invoke-PSQualityCheck" } - It "should File parameter type be string[]" { + It "should have $Name as a mandatory parameter property set to $MandatoryFlag" { - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['File'].ParameterType.Name | Should -Be 'String[]' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeExactly $MandatoryFlag } - It "should SonarQubeRulesPath parameter type be string" { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['SonarQubeRulesPath'].ParameterType.Name | Should -Be 'String' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be $ParameterSet } - It "should ShowCheckResults parameter type be switch" { + It "should $Name type be $Type" { - (Get-Command -Name 'Invoke-PSQualityCheck').Parameters['ShowCheckResults'].ParameterType.Name | Should -Be 'SwitchParameter' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 b/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 index 1dc0395..3ddde86 100644 --- a/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 @@ -1,25 +1,29 @@ Describe "Test-HelpForRequiredTokens.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'HelpTokens'; 'Type' = 'HashTable' } + ) { - $mandatoryParameters = @( - 'HelpTokens' - ) + BeforeAll { + $commandletUnderTest = "Test-HelpForRequiredTokens" + } - foreach ($parameter in $mandatoryParameters) { + It "should have $Name as a mandatory parameter" { - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - (Get-Command -Name 'Test-HelpForRequiredTokens').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Test-HelpForRequiredTokens').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + } - } + It "should $Name not belong to a parameter set" { + + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should HelpTokens type be HashTable" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Test-HelpForRequiredTokens').Parameters['HelpTokens'].ParameterType.Name | Should -Be 'HashTable' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 b/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 index 9781166..23c1ab3 100644 --- a/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 @@ -1,25 +1,29 @@ Describe "Test-HelpForUnspecifiedTokens.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'HelpTokens'; 'Type' = 'HashTable' } + ) { - $mandatoryParameters = @( - 'HelpTokens' - ) + BeforeAll { + $commandletUnderTest = "Test-HelpForUnspecifiedTokens" + } - foreach ($parameter in $mandatoryParameters) { + It "should have $Name as a mandatory parameter" { - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - (Get-Command -Name 'Test-HelpForUnspecifiedTokens').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Test-HelpForUnspecifiedTokens').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + } - } + It "should $Name not belong to a parameter set" { + + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should HelpTokens type be HashTable" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Test-HelpForUnspecifiedTokens').Parameters['HelpTokens'].ParameterType.Name | Should -Be 'HashTable' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 b/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 index 71ebe80..0ec609e 100644 --- a/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpTokensCountIsValid.Tests.ps1 @@ -1,25 +1,29 @@ Describe "Test-HelpTokensCountIsValid.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'HelpTokens'; 'Type' = 'HashTable' } + ) { - $mandatoryParameters = @( - 'HelpTokens' - ) + BeforeAll { + $commandletUnderTest = "Test-HelpTokensCountIsValid" + } - foreach ($parameter in $mandatoryParameters) { + It "should have $Name as a mandatory parameter" { - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - (Get-Command -Name 'Test-HelpTokensCountIsValid').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Test-HelpTokensCountIsValid').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + } - } + It "should $Name not belong to a parameter set" { + + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should HelpTokens type be HashTable" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Test-HelpTokensCountIsValid').Parameters['HelpTokens'].ParameterType.Name | Should -Be 'HashTable' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Test-HelpTokensParamsMatch.Tests.ps1 b/Source/Tests/Unit/Test-HelpTokensParamsMatch.Tests.ps1 index be5f0c8..091e39d 100644 --- a/Source/Tests/Unit/Test-HelpTokensParamsMatch.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpTokensParamsMatch.Tests.ps1 @@ -1,32 +1,30 @@ Describe "Test-HelpTokensParamsMatch.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -ForEach @( + @{ 'Name' = 'HelpTokens'; 'Type' = 'HashTable' } + @{ 'Name' = 'ParameterVariables'; 'Type' = 'PSObject' } + ) { - $mandatoryParameters = @( - 'HelpTokens' - 'ParameterVariables' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Test-HelpTokensParamsMatch" + } - (Get-Command -Name 'Test-HelpTokensParamsMatch').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Test-HelpTokensParamsMatch').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should HelpTokens type be HashTable" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Test-HelpTokensParamsMatch').Parameters['HelpTokens'].ParameterType.Name | Should -Be 'HashTable' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should ParameterVariables type be PSCustomObject" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Test-HelpTokensParamsMatch').Parameters['ParameterVariables'].ParameterType.Name | Should -Be 'PSObject' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Test-HelpTokensTextIsValid.Tests.ps1 b/Source/Tests/Unit/Test-HelpTokensTextIsValid.Tests.ps1 index 8f683bb..79f0d00 100644 --- a/Source/Tests/Unit/Test-HelpTokensTextIsValid.Tests.ps1 +++ b/Source/Tests/Unit/Test-HelpTokensTextIsValid.Tests.ps1 @@ -1,25 +1,29 @@ Describe "Test-HelpTokensTextIsValid.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'HelpTokens'; 'Type' = 'HashTable' } + ) { - $mandatoryParameters = @( - 'HelpTokens' - ) + BeforeAll { + $commandletUnderTest = "Test-HelpTokensTextIsValid" + } + + It "should have $Name as a mandatory parameter" { - foreach ($parameter in $mandatoryParameters) { + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + } - (Get-Command -Name 'Test-HelpTokensTextIsValid').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Test-HelpTokensTextIsValid').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should $Name not belong to a parameter set" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should HelpTokens type be HashTable" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Test-HelpTokensTextIsValid').Parameters['HelpTokens'].ParameterType.Name | Should -Be 'HashTable' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 b/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 index 677e8bc..699f001 100644 --- a/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 +++ b/Source/Tests/Unit/Test-ImportModuleIsValid.Tests.ps1 @@ -1,32 +1,30 @@ Describe "Test-ImportModuleIsValid.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'ParsedContent'; 'Type' = 'Object[]' } + @{ 'Name' = 'ImportModuleTokens'; 'Type' = 'Object[]' } + ) { - $mandatoryParameters = @( - 'ParsedContent' - 'ImportModuleTokens' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Test-ImportModuleIsValid" + } - (Get-Command -Name 'Test-ImportModuleIsValid').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Test-ImportModuleIsValid').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue } - It "should ParsedContent type be Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should $Name not belong to a parameter set" { - (Get-Command -Name 'Test-ImportModuleIsValid').Parameters['ParsedContent'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should ImportModuleTokens type be Object[]" -TestCases @{ 'parameter' = $parameter } { + It "should $Name type be $Type" { - (Get-Command -Name 'Test-ImportModuleIsValid').Parameters['ImportModuleTokens'].ParameterType.Name | Should -Be 'Object[]' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } diff --git a/Source/Tests/Unit/Test-ParameterVariablesHaveType.Tests.ps1 b/Source/Tests/Unit/Test-ParameterVariablesHaveType.Tests.ps1 index 8a0898d..d342363 100644 --- a/Source/Tests/Unit/Test-ParameterVariablesHaveType.Tests.ps1 +++ b/Source/Tests/Unit/Test-ParameterVariablesHaveType.Tests.ps1 @@ -1,31 +1,29 @@ Describe "Test-ParameterVariablesHaveType.Tests" { - Context "Parameter Tests" { + Context "Parameter Tests" -Foreach @( + @{ 'Name' = 'ParameterVariables'; 'Type' = 'HashTable' } + ) { - $mandatoryParameters = @( - 'ParameterVariables' - ) - - foreach ($parameter in $mandatoryParameters) { - - It "should have $parameter as a mandatory parameter" -TestCases @{ 'parameter' = $parameter } { + BeforeAll { + $commandletUnderTest = "Test-ParameterVariablesHaveType" + } - (Get-Command -Name 'Test-ParameterVariablesHaveType').Parameters[$parameter].Name | Should -BeExactly $parameter - (Get-Command -Name 'Test-ParameterVariablesHaveType').Parameters[$parameter].Attributes.Mandatory | Should -BeTrue + It "should have $Name as a mandatory parameter" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Name | Should -BeExactly $Name + (Get-Command -Name $commandletUnderTest).Parameters[$Name].Attributes.Mandatory | Should -BeTrue - It "should $parameter not belong to a parameter set" -TestCases @{ 'parameter' = $parameter } { + } - (Get-Command -Name 'Test-ParameterVariablesHaveType').Parameters[$parameter].ParameterSets.Keys | Should -Be '__AllParameterSets' + It "should $Name not belong to a parameter set" { - } + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterSets.Keys | Should -Be '__AllParameterSets' } - It "should ParameterVariables type be HashTable" { + It "should $Name type be $Type" { - (Get-Command -Name 'Test-ParameterVariablesHaveType').Parameters['ParameterVariables'].ParameterType.Name | Should -Be 'HashTable' + (Get-Command -Name $commandletUnderTest).Parameters[$Name].ParameterType.Name | Should -Be $Type } From a2de8b910c6ad2e91c05cea8a88f75610183aea2 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 15:30:06 +0000 Subject: [PATCH 25/33] Updated to match Pester 5 format guidelines --- Checks/Function-Extraction.Tests.ps1 | 50 ++++-- Checks/Module.Tests.ps1 | 83 +++++---- Checks/Script.Tests.ps1 | 246 ++++++++++++++------------- 3 files changed, 216 insertions(+), 163 deletions(-) diff --git a/Checks/Function-Extraction.Tests.ps1 b/Checks/Function-Extraction.Tests.ps1 index a166e73..6b1195e 100644 --- a/Checks/Function-Extraction.Tests.ps1 +++ b/Checks/Function-Extraction.Tests.ps1 @@ -6,30 +6,56 @@ param( [string]$ExtractPath ) -Describe "Function Extraction" { +BeforeDiscovery { - if ( Test-Path -Path $ExtractPath ) { - Get-ChildItem -Path $ExtractPath -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse - Remove-Item $ExtractPath -Force -ErrorAction SilentlyContinue - } + $moduleFiles = @() + + $Source | ForEach-Object { - New-Item -Path $ExtractPath -ItemType 'Directory' + $fileProperties = (Get-Item -Path $_) - foreach ($moduleFile in $Source) { + $moduleFiles += @{ + 'FullName' = $_ + 'Name' = $fileProperties.Name + 'Directory' = $fileProperties.Directory + + } - Context "Module : $moduleFile" { + } - It "function extraction should complete" -TestCases @{ 'moduleFile' = $moduleFile } { +} - { +Describe "Function Extraction" { - Export-FunctionsFromModule -Path $moduleFile -ExtractPath $ExtractPath + Context "Script: <_.Name> at <_.Directory>" -ForEach $moduleFiles { - } | Should -Not -Throw + BeforeAll { + if ( Test-Path -Path $ExtractPath ) { + Get-ChildItem -Path $ExtractPath -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse + Remove-Item $ExtractPath -Force -ErrorAction SilentlyContinue } + New-Item -Path $ExtractPath -ItemType 'Directory' + + } + + BeforeEach { + + $moduleFile = $_.FullName + + } + + It "function extraction should complete" { + + { + + Export-FunctionsFromModule -Path $moduleFile -ExtractPath $ExtractPath + + } | Should -Not -Throw + } } + } diff --git a/Checks/Module.Tests.ps1 b/Checks/Module.Tests.ps1 index 1e76d63..74e20c7 100644 --- a/Checks/Module.Tests.ps1 +++ b/Checks/Module.Tests.ps1 @@ -3,70 +3,79 @@ param( [string[]]$Source ) +BeforeDiscovery { + + $moduleFiles = @() + + $Source | ForEach-Object { + + $fileProperties = (Get-Item -Path $_) + + $moduleFiles += @{ + 'FullName' = $_ + 'Name' = $fileProperties.Name + 'Directory' = $fileProperties.Directory + + } + + } + +} + Describe "Module Tests" { - # TODO: Investigate whether the foreach can be put in the testcases block? - foreach ($moduleFile in $Source) { + Context "Script: <_.Name> at <_.Directory>" -ForEach $moduleFiles { - Context "Module : $moduleFile" { + BeforeEach { - $manifestFile = [Io.Path]::ChangeExtension($moduleFile, 'psd1') + $moduleFile = $_.FullName + $manifestFile = [Io.Path]::ChangeExtension($_.FullName, 'psd1') - It "Module should exist" -TestCases @{ 'moduleFile' = $moduleFile } { + ($ExportedCommandsCount, $CommandFoundInModuleCount, $CommandInModuleCount, $CommandFoundInManifestCount) = Get-FunctionCount -Module $moduleFile -Manifest $manifestFile - $moduleFile | Should -Exist + } - } + It "Module should exist" { - It "Manifest should exist" -TestCases @{ 'manifestFile' = $manifestFile } { + $moduleFile | Should -Exist - $manifestFile | Should -Exist + } - } + It "Manifest should exist" { - It "Manifest should be valid" -TestCases @{ 'manifestFile' = $manifestFile } { + $manifestFile | Should -Exist - $manifest = Test-ModuleManifest -Path $manifestFile -ErrorAction SilentlyContinue + } - $manifest | Should -BeOfType [System.Management.Automation.PSModuleInfo] + It "Manifest should be valid" { - } + $manifest = Test-ModuleManifest -Path $manifestFile -ErrorAction SilentlyContinue - ($ExportedCommandsCount, $CommandFoundInModuleCount, $CommandInModuleCount, $CommandFoundInManifestCount) = Get-FunctionCount -Module $moduleFile -Manifest $manifestFile + $manifest | Should -BeOfType [System.Management.Automation.PSModuleInfo] - It "Manifest should export Functions" -TestCases @{ - 'ExportedCommandsCount' = $ExportedCommandsCount - } { + } - ($ExportedCommandsCount) | Should -BeGreaterOrEqual 1 + It "Manifest should export Functions" { - } + ($ExportedCommandsCount) | Should -BeGreaterOrEqual 1 - It "Module should have Functions" -TestCases @{ - 'CommandInModuleCount' = $CommandInModuleCount - } { + } - ($CommandInModuleCount) | Should -BeGreaterOrEqual 1 + It "Module should have Functions" { - } + ($CommandInModuleCount) | Should -BeGreaterOrEqual 1 - It "all exported Functions from Manifest should exist in the Module" -TestCases @{ - 'ExportedCommandsCount' = $ExportedCommandsCount - 'CommandFoundInModuleCount' = $CommandFoundInModuleCount - } { + } - ($ExportedCommandsCount -eq $CommandFoundInModuleCount -and $ExportedCommandsCount -ge 1) | Should -BeTrue + It "all exported Functions from Manifest should exist in the Module" { - } + ($ExportedCommandsCount -eq $CommandFoundInModuleCount -and $ExportedCommandsCount -ge 1) | Should -BeTrue - It "all Functions in the Module should exist in Manifest " -TestCases @{ - 'CommandInModuleCount' = $CommandInModuleCount - 'CommandFoundInManifestCount' = $CommandFoundInManifestCount - } { + } - ($CommandInModuleCount -eq $CommandFoundInManifestCount -and $CommandFoundInManifestCount -ge 1 ) | Should -BeTrue + It "all Functions in the Module should exist in Manifest " { - } + ($CommandInModuleCount -eq $CommandFoundInManifestCount -and $CommandFoundInManifestCount -ge 1 ) | Should -BeTrue } diff --git a/Checks/Script.Tests.ps1 b/Checks/Script.Tests.ps1 index cd79892..361b29f 100644 --- a/Checks/Script.Tests.ps1 +++ b/Checks/Script.Tests.ps1 @@ -6,16 +6,34 @@ param( [string]$SonarQubeRules ) +BeforeDiscovery { + + $scriptFiles = @() + + $Source | ForEach-Object { + + $fileProperties = (Get-Item -Path $_) + + $scriptFiles += @{ + 'FullName' = $_ + 'Name' = $fileProperties.Name + 'Directory' = $fileProperties.Directory + + } + + } + +} + Describe "Script Tests" { - foreach ($scriptFile in $Source) { + Context "Script: <_.Name> at <_.Directory>" -ForEach $scriptFiles { - $scriptProperties = (Get-Item -Path $scriptFile) + BeforeEach { - Context "Script : $($scriptProperties.Name) at $($scriptProperties.Directory)" { + $scriptFile = $_.FullName - # This needs to get the content of the file or the content of the function inside the file - $fileContent = Get-FileContent -Path $scriptFile + $fileContent = Get-FileContent -Path $_.FullName if (-not([string]::IsNullOrEmpty($fileContent))) { ($ParsedFile, $ErrorCount) = Get-ParsedContent -Content $fileContent @@ -26,195 +44,195 @@ Describe "Script Tests" { $ErrorCount = 1 } - It "check script has valid PowerShell syntax" -TestCases @{ 'ErrorCount' = $ErrorCount } { + } - $ErrorCount | Should -Be 0 + It "check script has valid PowerShell syntax" { - } + $ErrorCount | Should -Be 0 - It "check help must contain required elements" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - { + It "check help must contain required elements" { - $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) - if ([string]::IsNullOrEmpty($helpComments)) { - throw "No help block found" - } - $helpTokens = Convert-Help -HelpComment $helpComments.Content - Test-HelpForRequiredTokens -HelpTokens $helpTokens + { - } | - Should -Not -Throw + $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) + if ([string]::IsNullOrEmpty($helpComments)) { + throw "No help block found" + } + $helpTokens = Convert-Help -Help $helpComments.Content + Test-HelpForRequiredTokens -HelpTokens $helpTokens - } - It "check help must not contain unspecified elements" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } | + Should -Not -Throw - { + } + It "check help must not contain unspecified elements" { - $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) - if ([string]::IsNullOrEmpty($helpComments)) { - throw "No help block found" - } - $helpTokens = Convert-Help -HelpComment $helpComments.Content - Test-HelpForUnspecifiedTokens -HelpTokens $helpTokens + { - } | - Should -Not -Throw + $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) + if ([string]::IsNullOrEmpty($helpComments)) { + throw "No help block found" + } + $helpTokens = Convert-Help -Help $helpComments.Content + Test-HelpForUnspecifiedTokens -HelpTokens $helpTokens - } + } | + Should -Not -Throw - It "check help elements text is not empty" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - { + It "check help elements text is not empty" { - $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) - if ([string]::IsNullOrEmpty($helpComments)) { - throw "No help block found" - } - $helpTokens = Convert-Help -HelpComment $helpComments.Content - Test-HelpTokensTextIsValid -HelpTokens $helpTokens + { - } | Should -Not -Throw + $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) + if ([string]::IsNullOrEmpty($helpComments)) { + throw "No help block found" + } + $helpTokens = Convert-Help -Help $helpComments.Content + Test-HelpTokensTextIsValid -HelpTokens $helpTokens - } + } | Should -Not -Throw - It "check help elements Min/Max counts are valid" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - { + It "check help elements Min/Max counts are valid" { - $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) - if ([string]::IsNullOrEmpty($helpComments)) { - throw "No help block found" - } - $helpTokens = Convert-Help -HelpComment $helpComments.Content - Test-HelpTokensCountIsValid -HelpTokens $helpTokens + { - } | Should -Not -Throw + $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) + if ([string]::IsNullOrEmpty($helpComments)) { + throw "No help block found" + } + $helpTokens = Convert-Help -Help $helpComments.Content + Test-HelpTokensCountIsValid -HelpTokens $helpTokens - } + } | Should -Not -Throw - It "check script contains [CmdletBinding] attribute" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - $cmdletBindingCount = (@(Get-TokenMarker -ParsedFileContent $ParsedFile -Type "Attribute" -Content "CmdletBinding")).Count + It "check script contains [CmdletBinding] attribute" { - $cmdletBindingCount | Should -Be 1 + $cmdletBindingCount = (@(Get-TokenMarker -ParsedContent $ParsedFile -Type "Attribute" -Content "CmdletBinding")).Count - } + $cmdletBindingCount | Should -Be 1 - It "check script contains [OutputType] attribute" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - $outputTypeCount = (@(Get-TokenMarker -ParsedFileContent $ParsedFile -Type "Attribute" -Content "OutputType")).Count + It "check script contains [OutputType] attribute" { - $outputTypeCount | Should -Be 1 + $outputTypeCount = (@(Get-TokenMarker -ParsedContent $ParsedFile -Type "Attribute" -Content "OutputType")).Count - } + $outputTypeCount | Should -Be 1 - It "check script [OutputType] attribute is not empty" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - $outputTypeToken = (Get-Token -ParsedFileContent $ParsedFile -Type "Attribute" -Content "OutputType") + It "check script [OutputType] attribute is not empty" { - $outputTypeValue = @($outputTypeToken | Where-Object { $_.Type -eq "Type" }) + $outputTypeToken = (Get-Token -ParsedContent $ParsedFile -Type "Attribute" -Content "OutputType") - $outputTypeValue | Should -Not -BeNullOrEmpty + $outputTypeValue = @($outputTypeToken | Where-Object { $_.Type -eq "Type" }) - } + $outputTypeValue | Should -Not -BeNullOrEmpty - It "check script contains param attribute" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - $paramCount = (@(Get-TokenMarker -ParsedFileContent $ParsedFile -Type "Keyword" -Content "param")).Count + It "check script contains param attribute" { - $paramCount | Should -Be 1 + $paramCount = (@(Get-TokenMarker -ParsedContent $ParsedFile -Type "Keyword" -Content "param")).Count - } + $paramCount | Should -Be 1 - It "check script param block variables have type" -TestCases @{ 'ParsedFile' = $ParsedFile; 'fileContent' = $fileContent } { + } - $parameterVariables = Get-ScriptParameters -Content $fileContent + It "check script param block variables have type" { - if ($parameterVariables.Count -eq 0) { + $parameterVariables = Get-ScriptParameters -Content $fileContent - Set-ItResult -Inconclusive -Because "No parameters found" + if ($parameterVariables.Count -eq 0) { - } + Set-ItResult -Inconclusive -Because "No parameters found" - { + } - Test-ParameterVariablesHaveType -ParameterVariables $parameterVariables + { - } | Should -Not -Throw + Test-ParameterVariablesHaveType -ParameterVariables $parameterVariables - } + } | Should -Not -Throw - It "check .PARAMETER help matches variables in param block" -TestCases @{ 'ParsedFile' = $ParsedFile; 'fileContent' = $fileContent } { + } - { + It "check .PARAMETER help matches variables in param block" { - $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) - if ([string]::IsNullOrEmpty($helpComments)) { - throw "No help block found" - } - $parameterVariables = Get-ScriptParameters -Content $fileContent - $helpTokens = Convert-Help -HelpComment $helpComments.Content + { - Test-HelpTokensParamsMatch -HelpTokens $helpTokens -ParameterVariables $parameterVariables + $helpComments = ($ParsedFile | Where-Object { $_.Type -eq "Comment" } | Select-Object -First 1) + if ([string]::IsNullOrEmpty($helpComments)) { + throw "No help block found" + } + $parameterVariables = Get-ScriptParameters -Content $fileContent + $helpTokens = Convert-Help -Help $helpComments.Content - } | Should -Not -Throw + Test-HelpTokensParamsMatch -HelpTokens $helpTokens -ParameterVariables $parameterVariables - } + } | Should -Not -Throw - It "check script contains no PSScriptAnalyzer suppressions" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - $suppressCount = (@(Get-TokenMarker -ParsedFileContent $ParsedFile -Type "Attribute" -Content "Diagnostics.CodeAnalysis.SuppressMessageAttribute")).Count + It "check script contains no PSScriptAnalyzer suppressions" { - $suppressCount | Should -Be 0 + $suppressCount = (@(Get-TokenMarker -ParsedContent $ParsedFile -Type "Attribute" -Content "Diagnostics.CodeAnalysis.SuppressMessageAttribute")).Count - } + $suppressCount | Should -Be 0 - It "check script contains no PSScriptAnalyzer failures" -TestCases @{ 'scriptFile' = $scriptProperties.FullName } { + } - $AnalyserFailures = @(Invoke-ScriptAnalyzer -Path $scriptFile) + It "check script contains no PSScriptAnalyzer failures" { - ($AnalyserFailures | ForEach-Object { $_.Message }) | Should -BeNullOrEmpty + $AnalyserFailures = @(Invoke-ScriptAnalyzer -Path $scriptFile) - } + ($AnalyserFailures | ForEach-Object { $_.Message }) | Should -BeNullOrEmpty - It "check script contains no PSScriptAnalyser SonarQube rule failures" -TestCases @{ 'scriptFile' = $scriptProperties.FullName } { + } - if ( [string]::IsNullOrEmpty($SonarQubeRules) ) { + It "check script contains no PSScriptAnalyser SonarQube rule failures" { - Set-ItResult -Inconclusive -Because "No SonarQube PSScriptAnalyzer rules folder specified" + if ( [string]::IsNullOrEmpty($SonarQubeRules) ) { - } + Set-ItResult -Inconclusive -Because "No SonarQube PSScriptAnalyzer rules folder specified" - if ( -not (Test-Path -Path $SonarQubeRules -ErrorAction SilentlyContinue)) { + } - Set-ItResult -Inconclusive -Because "SonarQube PSScriptAnalyzer rules not found" + if ( -not (Test-Path -Path $SonarQubeRules -ErrorAction SilentlyContinue)) { - } + Set-ItResult -Inconclusive -Because "SonarQube PSScriptAnalyzer rules not found" - $AnalyserFailures = @(Invoke-ScriptAnalyzer -Path $scriptFile -CustomRulePath $SonarQubeRules) + } - $AnalyserFailures | ForEach-Object { $_.Message } | Should -BeNullOrEmpty + $AnalyserFailures = @(Invoke-ScriptAnalyzer -Path $scriptFile -CustomRulePath $SonarQubeRules) - } + $AnalyserFailures | ForEach-Object { $_.Message } | Should -BeNullOrEmpty - It "check Import-Module statements have valid format" -TestCases @{ 'ParsedFile' = $ParsedFile } { + } - $importModuleTokens = @($ParsedFile | Where-Object { $_.Type -eq "Command" -and $_.Content -eq "Import-Module" }) + It "check Import-Module statements have valid format" { - if ($importModuleTokens.Count -eq 0) { + $importModuleTokens = @($ParsedFile | Where-Object { $_.Type -eq "Command" -and $_.Content -eq "Import-Module" }) - Set-ItResult -Inconclusive -Because "No Import-Module statements found" + if ($importModuleTokens.Count -eq 0) { - } + Set-ItResult -Inconclusive -Because "No Import-Module statements found" - { + } - Test-ImportModuleIsValid -ParsedFile $ParsedFile -ImportModuleTokens $importModuleTokens + { - } | Should -Not -Throw + Test-ImportModuleIsValid -ParsedContent $ParsedFile -ImportModuleTokens $importModuleTokens - } + } | Should -Not -Throw } From b143b5afc9433a6f720f156dfee3f389c21004de Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 15:57:36 +0000 Subject: [PATCH 26/33] Fixed noun pluralisation in functions --- Checks/Script.Tests.ps1 | 8 ++++---- ...criptParameters.ps1 => Get-ScriptParameter.ps1} | 4 ++-- ...orRequiredTokens.ps1 => Test-RequiredToken.ps1} | 4 ++-- ...ecifiedTokens.ps1 => Test-UnspecifiedToken.ps1} | 10 ++++++---- ...ers.Tests.ps1 => Get-ScriptParameter.Tests.ps1} | 14 +++++++------- ...kens.Tests.ps1 => Test-RequiredToken.Tests.ps1} | 14 +++++++------- ...s.Tests.ps1 => Test-UnspecifiedToken.Tests.ps1} | 12 ++++++------ 7 files changed, 34 insertions(+), 32 deletions(-) rename Source/PSQualityCheck.Functions/{Get-ScriptParameters.ps1 => Get-ScriptParameter.ps1} (94%) rename Source/PSQualityCheck.Functions/{Test-HelpForRequiredTokens.ps1 => Test-RequiredToken.ps1} (93%) rename Source/PSQualityCheck.Functions/{Test-HelpForUnspecifiedTokens.ps1 => Test-UnspecifiedToken.ps1} (79%) rename Source/Tests/Unit/{Get-ScriptParameters.Tests.ps1 => Get-ScriptParameter.Tests.ps1} (85%) rename Source/Tests/Unit/{Test-HelpForRequiredTokens.Tests.ps1 => Test-RequiredToken.Tests.ps1} (94%) rename Source/Tests/Unit/{Test-HelpForUnspecifiedTokens.Tests.ps1 => Test-UnspecifiedToken.Tests.ps1} (94%) diff --git a/Checks/Script.Tests.ps1 b/Checks/Script.Tests.ps1 index 361b29f..bab0a53 100644 --- a/Checks/Script.Tests.ps1 +++ b/Checks/Script.Tests.ps1 @@ -61,7 +61,7 @@ Describe "Script Tests" { throw "No help block found" } $helpTokens = Convert-Help -Help $helpComments.Content - Test-HelpForRequiredTokens -HelpTokens $helpTokens + Test-RequiredToken -HelpTokens $helpTokens } | Should -Not -Throw @@ -76,7 +76,7 @@ Describe "Script Tests" { throw "No help block found" } $helpTokens = Convert-Help -Help $helpComments.Content - Test-HelpForUnspecifiedTokens -HelpTokens $helpTokens + Test-UnspecifiedToken -HelpTokens $helpTokens } | Should -Not -Throw @@ -149,7 +149,7 @@ Describe "Script Tests" { It "check script param block variables have type" { - $parameterVariables = Get-ScriptParameters -Content $fileContent + $parameterVariables = Get-ScriptParameter -Content $fileContent if ($parameterVariables.Count -eq 0) { @@ -173,7 +173,7 @@ Describe "Script Tests" { if ([string]::IsNullOrEmpty($helpComments)) { throw "No help block found" } - $parameterVariables = Get-ScriptParameters -Content $fileContent + $parameterVariables = Get-ScriptParameter -Content $fileContent $helpTokens = Convert-Help -Help $helpComments.Content Test-HelpTokensParamsMatch -HelpTokens $helpTokens -ParameterVariables $parameterVariables diff --git a/Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 b/Source/PSQualityCheck.Functions/Get-ScriptParameter.ps1 similarity index 94% rename from Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 rename to Source/PSQualityCheck.Functions/Get-ScriptParameter.ps1 index 9afec95..8addfca 100644 --- a/Source/PSQualityCheck.Functions/Get-ScriptParameters.ps1 +++ b/Source/PSQualityCheck.Functions/Get-ScriptParameter.ps1 @@ -1,4 +1,4 @@ -function Get-ScriptParameters { +function Get-ScriptParameter { <# .SYNOPSIS Get a list of the parameters in the param block @@ -10,7 +10,7 @@ function Get-ScriptParameters { A string containing the text of the script .EXAMPLE - $parameterVariables = Get-ScriptParameters -Content $Content + $parameterVariables = Get-ScriptParameter -Content $Content #> [CmdletBinding()] [OutputType([System.Exception], [HashTable])] diff --git a/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 b/Source/PSQualityCheck.Functions/Test-RequiredToken.ps1 similarity index 93% rename from Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 rename to Source/PSQualityCheck.Functions/Test-RequiredToken.ps1 index d7a2c4a..5005a30 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpForRequiredTokens.ps1 +++ b/Source/PSQualityCheck.Functions/Test-RequiredToken.ps1 @@ -1,4 +1,4 @@ -function Test-HelpForRequiredTokens { +function Test-RequiredToken { <# .SYNOPSIS Check that help tokens contain required tokens @@ -10,7 +10,7 @@ function Test-HelpForRequiredTokens { A array of tokens containing the tokens of the Help Comment .EXAMPLE - Test-HelpForRequiredTokens -HelpTokens $HelpTokens + Test-RequiredToken -HelpTokens $HelpTokens #> [CmdletBinding()] [OutputType([System.Exception], [System.Void])] diff --git a/Source/PSQualityCheck.Functions/Test-HelpForUnspecifiedTokens.ps1 b/Source/PSQualityCheck.Functions/Test-UnspecifiedToken.ps1 similarity index 79% rename from Source/PSQualityCheck.Functions/Test-HelpForUnspecifiedTokens.ps1 rename to Source/PSQualityCheck.Functions/Test-UnspecifiedToken.ps1 index 6013bee..5e9927c 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpForUnspecifiedTokens.ps1 +++ b/Source/PSQualityCheck.Functions/Test-UnspecifiedToken.ps1 @@ -1,4 +1,4 @@ -function Test-HelpForUnspecifiedTokens { +function Test-UnspecifiedToken { <# .SYNOPSIS Check that help tokens do not contain unspecified tokens @@ -10,7 +10,7 @@ function Test-HelpForUnspecifiedTokens { A array of tokens containing the tokens of the Help Comment .EXAMPLE - Test-HelpForUnspecifiedTokens -HelpTokens $HelpTokens + Test-UnspecifiedToken -HelpTokens $HelpTokens #> [CmdletBinding()] [OutputType([System.Exception], [System.Void])] @@ -23,9 +23,11 @@ function Test-HelpForUnspecifiedTokens { $module = Get-Module -Name PSQualityCheck - if (Test-Path -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) { + $helpElementRulesPath = (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1") - $helpElementRules = (Import-PowerShellDataFile -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) + if (Test-Path -Path $helpElementRulesPath) { + + $helpElementRules = Import-PowerShellDataFile -Path $helpElementRulesPath } else { diff --git a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 b/Source/Tests/Unit/Get-ScriptParameter.Tests.ps1 similarity index 85% rename from Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 rename to Source/Tests/Unit/Get-ScriptParameter.Tests.ps1 index 8e0995c..177a482 100644 --- a/Source/Tests/Unit/Get-ScriptParameters.Tests.ps1 +++ b/Source/Tests/Unit/Get-ScriptParameter.Tests.ps1 @@ -1,6 +1,6 @@ Describe "Get-ScriptParameters.Tests" { - Context "Parameter Tests" -ForEach @( + Context "Parameter Tests" -Foreach @( @{ 'Name' = 'Content'; 'Type' = 'String' } ) { @@ -35,7 +35,7 @@ Describe "Get-ScriptParameters.Tests" { { - Get-ScriptParameters -Content $null + Get-ScriptParameter -Content $null } | Should -Throw @@ -46,7 +46,7 @@ Describe "Get-ScriptParameters.Tests" { { $fileContent = "function Get-FileContent { }" - $parameterVariables = Get-ScriptParameters -Content $fileContent + $parameterVariables = Get-ScriptParameter -Content $fileContent $parameterVariables | Should -BeNullOrEmpty @@ -58,7 +58,7 @@ Describe "Get-ScriptParameters.Tests" { $fileContent = 'param ( $parameterOne )' - $parameterVariables = Get-ScriptParameters -Content $fileContent + $parameterVariables = Get-ScriptParameter -Content $fileContent $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue $parameterVariables.('parameterOne') | Should -BeNullOrEmpty @@ -69,7 +69,7 @@ Describe "Get-ScriptParameters.Tests" { $fileContent = 'param ( [int]$parameterOne )' - $parameterVariables = Get-ScriptParameters -Content $fileContent + $parameterVariables = Get-ScriptParameter -Content $fileContent $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue $parameterVariables.('parameterOne') | Should -BeExactly '[int]' @@ -83,7 +83,7 @@ Describe "Get-ScriptParameters.Tests" { [string]$parameterTwo )' - $parameterVariables = Get-ScriptParameters -Content $fileContent + $parameterVariables = Get-ScriptParameter -Content $fileContent $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue $parameterVariables.('parameterOne') | Should -BeExactly '[int]' @@ -100,7 +100,7 @@ Describe "Get-ScriptParameters.Tests" { $parameterTwo )' - $parameterVariables = Get-ScriptParameters -Content $fileContent + $parameterVariables = Get-ScriptParameter -Content $fileContent $parameterVariables.ContainsKey('parameterOne') | Should -BeTrue $parameterVariables.('parameterOne') | Should -BeExactly '[int]' diff --git a/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 b/Source/Tests/Unit/Test-RequiredToken.Tests.ps1 similarity index 94% rename from Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 rename to Source/Tests/Unit/Test-RequiredToken.Tests.ps1 index 3ddde86..7e3f691 100644 --- a/Source/Tests/Unit/Test-HelpForRequiredTokens.Tests.ps1 +++ b/Source/Tests/Unit/Test-RequiredToken.Tests.ps1 @@ -1,11 +1,11 @@ -Describe "Test-HelpForRequiredTokens.Tests" { +Describe "Test-RequiredToken.Tests" { - Context "Parameter Tests" -Foreach @( + Context "Parameter Tests" -ForEach @( @{ 'Name' = 'HelpTokens'; 'Type' = 'HashTable' } ) { BeforeAll { - $commandletUnderTest = "Test-HelpForRequiredTokens" + $commandletUnderTest = "Test-RequiredToken" } It "should have $Name as a mandatory parameter" { @@ -97,7 +97,7 @@ Describe "Test-HelpForRequiredTokens.Tests" { { - Test-HelpForRequiredTokens -HelpTokens $null + Test-RequiredToken -HelpTokens $null } | Should -Throw @@ -137,7 +137,7 @@ Describe "Test-HelpForRequiredTokens.Tests" { ) } - Test-HelpForRequiredTokens -HelpTokens $helpTokens + Test-RequiredToken -HelpTokens $helpTokens Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } @@ -188,7 +188,7 @@ Describe "Test-HelpForRequiredTokens.Tests" { } - Test-HelpForRequiredTokens -HelpTokens $helpTokens + Test-RequiredToken -HelpTokens $helpTokens Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } @@ -223,7 +223,7 @@ Describe "Test-HelpForRequiredTokens.Tests" { ) } - Test-HelpForRequiredTokens -HelpTokens $helpTokens + Test-RequiredToken -HelpTokens $helpTokens Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } diff --git a/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 b/Source/Tests/Unit/Test-UnspecifiedToken.Tests.ps1 similarity index 94% rename from Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 rename to Source/Tests/Unit/Test-UnspecifiedToken.Tests.ps1 index 23c1ab3..38280db 100644 --- a/Source/Tests/Unit/Test-HelpForUnspecifiedTokens.Tests.ps1 +++ b/Source/Tests/Unit/Test-UnspecifiedToken.Tests.ps1 @@ -1,6 +1,6 @@ -Describe "Test-HelpForUnspecifiedTokens.Tests" { +Describe "Test-UnspecifiedToken.Tests" { - Context "Parameter Tests" -Foreach @( + Context "Parameter Tests" -ForEach @( @{ 'Name' = 'HelpTokens'; 'Type' = 'HashTable' } ) { @@ -97,7 +97,7 @@ Describe "Test-HelpForUnspecifiedTokens.Tests" { { - Test-HelpForUnspecifiedTokens -HelpTokens $null + Test-UnspecifiedToken -HelpTokens $null } | Should -Throw @@ -137,7 +137,7 @@ Describe "Test-HelpForUnspecifiedTokens.Tests" { ) } - Test-HelpForRequiredTokens -HelpTokens $helpTokens + Test-UnspecifiedToken -HelpTokens $helpTokens Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } @@ -188,7 +188,7 @@ Describe "Test-HelpForUnspecifiedTokens.Tests" { } - Test-HelpForRequiredTokens -HelpTokens $helpTokens + Test-UnspecifiedToken -HelpTokens $helpTokens Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } @@ -209,7 +209,7 @@ Describe "Test-HelpForUnspecifiedTokens.Tests" { ) } - Test-HelpForRequiredTokens -HelpTokens $helpTokens + Test-UnspecifiedToken -HelpTokens $helpTokens Assert-MockCalled -CommandName Get-Module -Times 1 -ParameterFilter { $Name -eq "PSQualityCheck" } From e7dd86df4c0a100f4e4abd09fd66413553f08a22 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 15:58:15 +0000 Subject: [PATCH 27/33] Fixed loading HelpElementRules.psd1 consistently as per other functions --- .../Test-HelpTokensCountIsValid.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 b/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 index 8897f0e..86db588 100644 --- a/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 +++ b/Source/PSQualityCheck.Functions/Test-HelpTokensCountIsValid.ps1 @@ -26,9 +26,11 @@ function Test-HelpTokensCountIsValid { $module = Get-Module -Name PSQualityCheck - if (Test-Path -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) { + $helpElementRulesPath = (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1") - $helpElementRules = (Import-PowerShellDataFile -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) + if (Test-Path -Path $helpElementRulesPath) { + + $helpElementRules = Import-PowerShellDataFile -Path $helpElementRulesPath } else { From 4e5d3da58ddc1b5d5ee65073f231540e1f0a7142 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 15:59:02 +0000 Subject: [PATCH 28/33] Release 1.0.10 build --- PSQualityCheck.Functions.psd1 | 175 +++++----- PSQualityCheck.Functions.psm1 | 599 +++++++++++++++++++--------------- PSQualityCheck.psd1 | 162 ++++----- 3 files changed, 503 insertions(+), 433 deletions(-) diff --git a/PSQualityCheck.Functions.psd1 b/PSQualityCheck.Functions.psd1 index 46b8cd2..7373004 100644 --- a/PSQualityCheck.Functions.psd1 +++ b/PSQualityCheck.Functions.psd1 @@ -3,137 +3,138 @@ # # Generated by: Andrew Davidson # -# Generated on: 07/01/2021 +# Generated on: 11/01/2021 # @{ - # Script module or binary module file associated with this manifest. - RootModule = 'PSQualityCheck.Functions.psm1' +# Script module or binary module file associated with this manifest. +RootModule = 'PSQualityCheck.Functions.psm1' - # Version number of this module. - ModuleVersion = '1.0.10' +# Version number of this module. +ModuleVersion = '1.0.10' - # Supported PSEditions - # CompatiblePSEditions = @() +# Supported PSEditions +# CompatiblePSEditions = @() - # ID used to uniquely identify this module - GUID = '5ddfdef7-3985-476d-92d8-e7db35bf960b' +# ID used to uniquely identify this module +GUID = '5ddfdef7-3985-476d-92d8-e7db35bf960b' - # Author of this module - Author = 'Andrew Davidson' +# Author of this module +Author = 'Andrew Davidson' - # Company or vendor of this module - CompanyName = 'Andrew Davidson' +# Company or vendor of this module +CompanyName = 'Andrew Davidson' - # Copyright statement for this module - Copyright = '(c) Andrew Davidson. All rights reserved.' +# Copyright statement for this module +Copyright = '(c) Andrew Davidson. All rights reserved.' - # Description of the functionality provided by this module - Description = 'This module contains supporting functions for PSQualityCheck.' +# Description of the functionality provided by this module +Description = 'This module contains supporting functions for PSQualityCheck.' - # Minimum version of the PowerShell engine required by this module - PowerShellVersion = '5.0' +# Minimum version of the PowerShell engine required by this module +PowerShellVersion = '5.0' - # Name of the PowerShell host required by this module - # PowerShellHostName = '' +# Name of the PowerShell host required by this module +# PowerShellHostName = '' - # Minimum version of the PowerShell host required by this module - # PowerShellHostVersion = '' +# Minimum version of the PowerShell host required by this module +# PowerShellHostVersion = '' - # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. - # DotNetFrameworkVersion = '' +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# DotNetFrameworkVersion = '' - # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. - # ClrVersion = '' +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# ClrVersion = '' - # Processor architecture (None, X86, Amd64) required by this module - # ProcessorArchitecture = '' +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' - # Modules that must be imported into the global environment prior to importing this module - # RequiredModules = @() +# Modules that must be imported into the global environment prior to importing this module +# RequiredModules = @() - # Assemblies that must be loaded prior to importing this module - # RequiredAssemblies = @() +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() - # Script files (.ps1) that are run in the caller's environment prior to importing this module. - # ScriptsToProcess = @() +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() - # Type files (.ps1xml) to be loaded when importing this module - # TypesToProcess = @() +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() - # Format files (.ps1xml) to be loaded when importing this module - # FormatsToProcess = @() +# Format files (.ps1xml) to be loaded when importing this module +# FormatsToProcess = @() - # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess - # NestedModules = @() +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +# NestedModules = @() - # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. - FunctionsToExport = 'Convert-Help', 'Export-FunctionsFromModule', 'Get-FileContent', - 'Get-FileList', 'Get-FunctionCount', 'Get-ParsedContent', - 'Get-ParsedFile', 'Get-ScriptParameters', 'Get-Token', - 'Get-TokenComponent', 'Get-TokenMarker', 'Test-HelpForRequiredTokens', - 'Test-HelpForUnspecifiedTokens', 'Test-HelpTokensCountIsValid', - 'Test-HelpTokensParamsMatch', 'Test-HelpTokensTextIsValid', - 'Test-ImportModuleIsValid', 'Test-ParameterVariablesHaveType' +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Convert-Help', 'Export-FunctionsFromModule', 'Get-FileContent', + 'Get-FileList', 'Get-FunctionCount', 'Get-ParsedContent', + 'Get-ParsedFile', 'Get-ScriptParameter', 'Get-Token', + 'Get-TokenComponent', 'Get-TokenMarker', + 'Test-HelpTokensCountIsValid', 'Test-HelpTokensParamsMatch', + 'Test-HelpTokensTextIsValid', 'Test-ImportModuleIsValid', + 'Test-ParameterVariablesHaveType', 'Test-RequiredToken', + 'Test-UnspecifiedToken' - # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. - CmdletsToExport = @() +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() - # Variables to export from this module - # VariablesToExport = @() +# Variables to export from this module +# VariablesToExport = @() - # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. - AliasesToExport = @() +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() - # DSC resources to export from this module - # DscResourcesToExport = @() +# DSC resources to export from this module +# DscResourcesToExport = @() - # List of all modules packaged with this module - # ModuleList = @() +# List of all modules packaged with this module +# ModuleList = @() - # List of all files packaged with this module - FileList = 'Checks\HelpElementRules.psd1' +# List of all files packaged with this module +FileList = 'Checks\HelpElementRules.psd1' - # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. - PrivateData = @{ +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ - PSData = @{ + PSData = @{ - # Tags applied to this module. These help with module discovery in online galleries. - Tags = 'powershell', 'powershell-module', 'tests', 'quality', 'quality-check', - 'pester', 'pester-tests' + # Tags applied to this module. These help with module discovery in online galleries. + Tags = 'powershell', 'powershell-module', 'tests', 'quality', 'quality-check', + 'pester', 'pester-tests' - # A URL to the license for this module. - LicenseUri = 'https://github.com/andrewrdavidson/PSQualityCheck/blob/main/LICENSE' + # A URL to the license for this module. + LicenseUri = 'https://github.com/andrewrdavidson/PSQualityCheck/blob/main/LICENSE' - # A URL to the main website for this project. - ProjectUri = 'https://github.com/andrewrdavidson/PSQualityCheck' + # A URL to the main website for this project. + ProjectUri = 'https://github.com/andrewrdavidson/PSQualityCheck' - # A URL to an icon representing this module. - # IconUri = '' + # A URL to an icon representing this module. + # IconUri = '' - # ReleaseNotes of this module - # ReleaseNotes = '' + # ReleaseNotes of this module + # ReleaseNotes = '' - # Prerelease string of this module - Prerelease = 'alpha2' + # Prerelease string of this module + # Prerelease = '' - # Flag to indicate whether the module requires explicit user acceptance for install/update/save - # RequireLicenseAcceptance = $false + # Flag to indicate whether the module requires explicit user acceptance for install/update/save + # RequireLicenseAcceptance = $false - # External dependent modules of this module - # ExternalModuleDependencies = @() + # External dependent modules of this module + # ExternalModuleDependencies = @() - } # End of PSData hashtable + } # End of PSData hashtable - } # End of PrivateData hashtable +} # End of PrivateData hashtable - # HelpInfo URI of this module - HelpInfoURI = 'https://github.com/andrewrdavidson/PSQualityCheck/wiki' +# HelpInfo URI of this module +HelpInfoURI = 'https://github.com/andrewrdavidson/PSQualityCheck/wiki' - # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. - # DefaultCommandPrefix = '' +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' } diff --git a/PSQualityCheck.Functions.psm1 b/PSQualityCheck.Functions.psm1 index 2f4c3f1..d754615 100644 --- a/PSQualityCheck.Functions.psm1 +++ b/PSQualityCheck.Functions.psm1 @@ -6,17 +6,17 @@ function Convert-Help { .DESCRIPTION Convert the help comment into an object containing all the elements from the help comment - .PARAMETER HelpComment + .PARAMETER Help A string containing the Help Comment .EXAMPLE - $helpObject = Convert-Help -HelpComment $helpComment + $helpObject = Convert-Help -Help $Help #> [CmdletBinding()] [OutputType([HashTable], [System.Exception])] param ( [parameter(Mandatory = $true)] - [string]$HelpComment + [string]$Help ) # These are the possible Help Comment elements that the script will look for @@ -41,8 +41,8 @@ function Convert-Help { try { if (-not( - $HelpComment.StartsWith("<#") -and - $HelpComment.EndsWith("#>") + $Help.StartsWith("<#") -and + $Help.EndsWith("#>") )) { throw "Help does not appear to be a comment block" } @@ -66,7 +66,7 @@ function Convert-Help { '.EXTERNALHELP' # Split the single comment string into it's line components - $commentArray = ($HelpComment -split '\n').Trim() + $commentArray = ($Help -split '\n').Trim() # initialise an empty HashTable ready for the found help elements to be stored $foundElements = @{} @@ -91,10 +91,10 @@ function Convert-Help { # previous element to the found text so far, then reset it $lastElement = @($foundElements[$lastHelpElement]) - $lastElement[$lastElement.Count - 1].Text = $help + $lastElement[$lastElement.Count - 1].Text = $helpData $foundElements[$lastHelpElement] = $lastElement - $help = $null + $helpData = $null } # this should be an array of HashTables {LineNumber, Name & Text} @@ -124,7 +124,7 @@ function Convert-Help { if ($numFound -ge 1 -and $line -lt ($commentArray.Count - 1)) { - $help += $commentArray[$line] + $helpData += $commentArray[$line] } @@ -135,7 +135,7 @@ function Convert-Help { if ( -not ([string]::IsNullOrEmpty($lastHelpElement))) { # process the very last one $currentElement = @($foundElements[$lastHelpElement]) - $currentElement[$currentElement.Count - 1].Text = $help + $currentElement[$currentElement.Count - 1].Text = $helpData $foundElements[$lastHelpElement] = $currentElement } @@ -176,85 +176,97 @@ function Export-FunctionsFromModule { [string]$ExtractPath ) - # Get the file properties of our module - $fileProperties = (Get-Item -LiteralPath $Path) - $moduleName = $fileProperties.BaseName + try { + # Get the file properties of our module + $fileProperties = (Get-Item -LiteralPath $Path) + + if ($fileProperties.Extension -ne ".psm1") { + throw "Passed file does not appear to be a PowerShell module" + } - # Generate a new temporary output path for our extracted functions - $FunctionOutputPath = Join-Path -Path $ExtractPath -ChildPath $moduleName - New-Item $FunctionOutputPath -ItemType 'Directory' + $moduleName = $fileProperties.BaseName - # Get the plain content of the module file - $ModuleFileContent = Get-Content -Path $Path -ErrorAction Stop + # Get the plain content of the module file + $ModuleFileContent = Get-Content -Path $Path -ErrorAction Stop - # Parse the PowerShell module using PSParser - $ParserErrors = $null - $ParsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($ModuleFileContent, [ref]$ParserErrors) + # Parse the PowerShell module using PSParser + $ParserErrors = $null + $ParsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($ModuleFileContent, [ref]$ParserErrors) + + # Create an array of where each reference of the keyword 'function' is + $ParsedFunctions = ($ParsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) - # Create an array of where each reference of the keyword 'function' is - $ParsedFunctions = ($ParsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) + # Initialise the $parsedFunction tracking variable + $parsedFunction = 0 - # Initialise the $parsedFunction tracking variable - $parsedFunction = 0 + if ($ParsedFunctions.Count -ge 1) { - if ($ParsedFunctions.Count -ge 1) { + # Generate a new temporary output path for our extracted functions + $FunctionOutputPath = Join-Path -Path $ExtractPath -ChildPath $moduleName - foreach ($Function in $ParsedFunctions) { + if (-not (Test-Path -Path $FunctionOutputPath)) { + New-Item $FunctionOutputPath -ItemType 'Directory' + } - # Counter for the array $ParsedFunction to help find the 'next' function - $parsedFunction++ + foreach ($Function in $ParsedFunctions) { - # Get the name of the current function - # Cheat: Simply getting all properties with the same line number as the 'function' statement - $FunctionProperties = $ParsedFileFunctions | Where-Object { $_.StartLine -eq $Function.StartLine } - $FunctionName = ($FunctionProperties | Where-Object { $_.Type -eq "CommandArgument" }).Content + # Counter for the array $ParsedFunction to help find the 'next' function + $parsedFunction++ - # Establish the Start and End lines for the function in the main module file - if ($parsedFunction -eq $ParsedFunctions.Count) { + # Get the name of the current function + # Cheat: Simply getting all properties with the same line number as the 'function' statement + $FunctionProperties = $ParsedFileFunctions | Where-Object { $_.StartLine -eq $Function.StartLine } + $FunctionName = ($FunctionProperties | Where-Object { $_.Type -eq "CommandArgument" }).Content - # This is the last function in the module so set the last line of this function to be the last line in the module file + # Establish the Start and End lines for the function in the main module file + if ($parsedFunction -eq $ParsedFunctions.Count) { - $StartLine = ($Function.StartLine) - for ($line = $ModuleFileContent.Count; $line -gt $Function.StartLine; $line--) { - if ($ModuleFileContent[$line] -like "}") { - $EndLine = $line - break + # This is the last function in the module so set the last line of this function to be the last line in the module file + + $StartLine = ($Function.StartLine) + for ($line = $ModuleFileContent.Count; $line -gt $Function.StartLine; $line--) { + if ($ModuleFileContent[$line] -like "}") { + $EndLine = $line + break + } } } - } - else { + else { - $StartLine = ($Function.StartLine) + $StartLine = ($Function.StartLine) - # EndLine needs to be where the last } is - for ($line = $ParsedFunctions[$parsedFunction].StartLine; $line -gt $Function.StartLine; $line--) { - if ($ModuleFileContent[$line] -like "}") { - $EndLine = $line - break + # EndLine needs to be where the last } is + for ($line = $ParsedFunctions[$parsedFunction].StartLine; $line -gt $Function.StartLine; $line--) { + if ($ModuleFileContent[$line] -like "}") { + $EndLine = $line + break + } } + } - } + # Setup the FunctionOutputFile for the function file + $FunctionOutputFileName = "{0}\{1}{2}" -f $FunctionOutputPath, $FunctionName, ".ps1" - # Setup the FunctionOutputFile for the function file - $FunctionOutputFileName = "{0}\{1}{2}" -f $FunctionOutputPath, $FunctionName, ".ps1" + # If the file doesn't exist create an empty file so that we can Add-Content to it + if (-not (Test-Path -Path $FunctionOutputFileName)) { + Out-File -FilePath $FunctionOutputFileName + } - # If the file doesn't exist create an empty file so that we can Add-Content to it - if (-not (Test-Path -Path $FunctionOutputFileName)) { - Out-File -FilePath $FunctionOutputFileName - } + # Output the lines of the function to the FunctionOutputFile + for ($line = $StartLine; $line -lt $EndLine; $line++) { + Add-Content -Path $FunctionOutputFileName -Value $ModuleFileContent[$line] + } - # Output the lines of the function to the FunctionOutputFile - for ($line = $StartLine; $line -lt $EndLine; $line++) { - Add-Content -Path $FunctionOutputFileName -Value $ModuleFileContent[$line] } - + } + else { + throw "File contains no functions" } } - else { - Write-Warning "Module contains no functions, skipping" + catch { + throw } - } function Get-FileContent { @@ -278,55 +290,97 @@ function Get-FileContent { [string]$Path ) - $fileContent = Get-Content -Path $Path + try { - $parserErrors = $null + $fileContent = Get-Content -Path $Path - # If the file content is null (an empty file) then generate an empty parsedFileFunctions array to allow the function to complete - if ([string]::IsNullOrEmpty($fileContent)) { - $parsedFileFunctions = @() - } - else { - $parsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($fileContent, [ref]$parserErrors) - } + $parserErrors = $null + + # If the file content is null (an empty file) then generate an empty parsedFileFunctions array to allow the function to complete + if ([string]::IsNullOrEmpty($fileContent)) { + $parsedFileFunctions = @() + } + else { + $parsedFileFunctions = [System.Management.Automation.PSParser]::Tokenize($fileContent, [ref]$parserErrors) + } - # Create an array of where each reference of the keyword 'function' is - $parsedFunctions = ($parsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) + # Create an array of where each reference of the keyword 'function' is + $parsedFunctions = ($parsedFileFunctions | Where-Object { $_.Type -eq "Keyword" -and $_.Content -like 'function' }) - if ($parsedFunctions) { + if ($parsedFunctions.Count -gt 1) { + throw "Too many functions in file, file is invalid" + } - foreach ($function in $parsedFunctions) { + if ($parsedFunctions.Count -eq 1) { - $startLine = ($function.StartLine) + if ($fileContent.Count -gt 1) { - for ($line = $fileContent.Count; $line -gt $function.StartLine; $line--) { + foreach ($function in $parsedFunctions) { - if ($fileContent[$line] -like "}") { + $startLine = ($function.StartLine) - $endLine = $line - break + for ($line = $fileContent.Count; $line -gt $function.StartLine; $line--) { + + if ($fileContent[$line] -like "*}*") { + + $endLine = $line + break + + } + + } + + # Output the lines of the function to the FunctionOutputFile + for ($line = $startLine; $line -lt $endLine; $line++) { + + $parsedFileContent += $fileContent[$line] + + if ($line -ne ($fileContent.Count - 1)) { + $parsedFileContent += "`r`n" + } + + } } } + else { - # Output the lines of the function to the FunctionOutputFile - for ($line = $startLine; $line -lt $endLine; $line++) { - $parsedFileContent += $fileContent[$line] - $parsedFileContent += "`n" - } + # if there is only one line then the content should be on the line between { and } + [int]$startBracket = $fileContent.IndexOf('{') + [int]$endBracket = $fileContent.LastIndexOf('}') + $parsedFileContent = $fileContent.substring($startBracket + 1, $endBracket - 1 - $startBracket) + + } } + else { - } - else { + if ($fileContent.Count -gt 1) { + + for ($line = 0; $line -lt $fileContent.Count; $line++) { + + $parsedFileContent += $fileContent[$line] + + if ($line -ne ($fileContent.Count - 1)) { + $parsedFileContent += "`r`n" + } + + } + + } + else { + + $parsedFileContent = $fileContent + + } - for ($line = 0; $line -lt $fileContent.Count; $line++) { - $parsedFileContent += $fileContent[$line] - $parsedFileContent += "`n" } } + catch { + throw + } return $parsedFileContent @@ -384,28 +438,28 @@ function Get-FunctionCount { Return the count of functions in the Module and Manifest and whether they appear in their counterpart. e.g. Whether the functions in the manifest appear in the module and vice versa - .PARAMETER ModuleFile + .PARAMETER ModulePath A string containing the Module filename - .PARAMETER ManifestFile + .PARAMETER ManifestPath A string containing the Manifest filename .EXAMPLE - ($ExportedCommandsCount, $CommandFoundInModuleCount, $CommandInModuleCount, $CommandFoundInManifestCount) = Get-FunctionCount -ModuleFile $moduleFile -ManifestFile $manifestFile + ($ExportedCommandsCount, $CommandFoundInModuleCount, $CommandInModuleCount, $CommandFoundInManifestCount) = Get-FunctionCount -ModulePath $ModulePath -ManifestPath $ManifestPath #> [CmdletBinding()] [OutputType([Int[]])] param ( [parameter(Mandatory = $true)] - [string]$ModuleFile, + [string]$ModulePath, [parameter(Mandatory = $true)] - [string]$ManifestFile + [string]$ManifestPath ) try { - if (Test-Path -Path $ManifestFile) { - $ExportedCommands = (Test-ModuleManifest -Path $ManifestFile -ErrorAction Stop).ExportedCommands + if (Test-Path -Path $ManifestPath) { + $ExportedCommands = (Test-ModuleManifest -Path $ManifestPath -ErrorAction Stop).ExportedCommands $ExportedCommandsCount = $ExportedCommands.Count } else { @@ -418,8 +472,8 @@ function Get-FunctionCount { } try { - if (Test-Path -Path $ModuleFile) { - ($ParsedModule, $ParserErrors) = Get-ParsedFile -Path $ModuleFile + if (Test-Path -Path $ModulePath) { + ($ParsedModule, $ParserErrors) = Get-ParsedFile -Path $ModulePath } else { throw "Module file doesn't exist" @@ -545,7 +599,7 @@ function Get-ParsedFile { } -function Get-ScriptParameters { +function Get-ScriptParameter { <# .SYNOPSIS Get a list of the parameters in the param block @@ -557,7 +611,7 @@ function Get-ScriptParameters { A string containing the text of the script .EXAMPLE - $parameterVariables = Get-ScriptParameters -Content $Content + $parameterVariables = Get-ScriptParameter -Content $Content #> [CmdletBinding()] [OutputType([System.Exception], [HashTable])] @@ -570,6 +624,10 @@ function Get-ScriptParameters { $parsedScript = [System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$null, [ref]$null) + if ([string]::IsNullOrEmpty($parsedScript.ParamBlock)) { + throw "No parameters found" + } + [string]$paramBlock = $parsedScript.ParamBlock ($ParsedContent, $ParserErrorCount) = Get-ParsedContent -Content $paramBlock @@ -630,7 +688,7 @@ function Get-Token { .DESCRIPTION Get token(s) from the tokenized output matching the passed Type and Content - .PARAMETER ParsedFileContent + .PARAMETER ParsedContent A string array containing the Tokenized data .PARAMETER Type @@ -640,22 +698,22 @@ function Get-Token { The token content (or value) to be found .EXAMPLE - $outputTypeToken = (Get-Token -ParsedFileContent $ParsedFile -Type "Attribute" -Content "OutputType") + $outputTypeToken = (Get-Token -ParsedContent $ParsedFile -Type "Attribute" -Content "OutputType") #> [CmdletBinding()] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFileContent, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [string]$Type, [parameter(Mandatory = $true)] [string]$Content ) - $token = Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type $Type -Content $Content + $token = Get-TokenMarker -ParsedContent $ParsedContent -Type $Type -Content $Content - $tokens = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine $token.StartLine + $tokens = Get-TokenComponent -ParsedContent $ParsedContent -StartLine $token.StartLine return $tokens @@ -669,20 +727,20 @@ function Get-TokenComponent { .DESCRIPTION Get all the tokens components from a single line in the tokenized content - .PARAMETER ParsedFileContent + .PARAMETER ParsedContent A string array containing the tokenized content .PARAMETER StartLine A integer of the starting line to parse .EXAMPLE - $tokens = Get-TokenComponent -ParsedFileContent $ParsedFileContent -StartLine 10 + $tokens = Get-TokenComponent -ParsedContent $ParsedContent -StartLine 10 #> [CmdletBinding()] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFileContent, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [int]$StartLine ) @@ -691,7 +749,7 @@ function Get-TokenComponent { #* which can't find the variables in the 'Where-Object' clause (even though it's valid) $StartLine = $StartLine - $tokenComponents = @($ParsedFileContent | Where-Object { $_.StartLine -eq $StartLine }) + $tokenComponents = @($ParsedContent | Where-Object { $_.StartLine -eq $StartLine }) return $tokenComponents @@ -705,7 +763,7 @@ function Get-TokenMarker { .DESCRIPTION Gets single token from the tokenized output matching the passed Type and Content - .PARAMETER ParsedFileContent + .PARAMETER ParsedContent A string array containing the Tokenized data .PARAMETER Type @@ -715,13 +773,13 @@ function Get-TokenMarker { The token content (or value) to be found .EXAMPLE - $token = Get-TokenMarker -ParsedFileContent $ParsedFileContent -Type $Type -Content $Content + $token = Get-TokenMarker -ParsedContent $ParsedContent -Type $Type -Content $Content #> [CmdletBinding()] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFileContent, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [string]$Type, [parameter(Mandatory = $true)] @@ -733,151 +791,12 @@ function Get-TokenMarker { $Type = $Type $Content = $Content - $token = @($ParsedFileContent | Where-Object { $_.Type -eq $Type -and $_.Content -eq $Content }) + $token = @($ParsedContent | Where-Object { $_.Type -eq $Type -and $_.Content -eq $Content }) return $token } -function Test-HelpForRequiredTokens { - <# - .SYNOPSIS - Check that help tokens contain required tokens - - .DESCRIPTION - Check that the help comments contain tokens that are specified in the external verification data file - - .PARAMETER HelpTokens - A string containing the text of the Help Comment - - .EXAMPLE - Test-HelpForRequiredTokens -HelpTokens $HelpTokens - #> - [CmdletBinding()] - [OutputType([System.Exception], [System.Void])] - param ( - [parameter(Mandatory = $true)] - [HashTable]$HelpTokens - ) - - try { - - $module = Get-Module -Name PSQualityCheck - - if (Test-Path -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) { - - $helpElementRules = (Import-PowerShellDataFile -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) - - } - else { - - throw "Unable to load Checks\HelpElementRules.psd1" - - } - - $tokenErrors = @() - - for ($order = 1; $order -le $helpElementRules.Count; $order++) { - - $token = $helpElementRules."$order" - - if ($token.Key -notin $HelpTokens.Keys ) { - - if ($token.Required -eq $true) { - - $tokenErrors += $token.Key - - } - - } - - } - - if ($tokenErrors.Count -ge 1) { - throw "Missing required token(s): $tokenErrors" - } - - } - catch { - - throw $_.Exception.Message - - } - -} - -function Test-HelpForUnspecifiedTokens { - <# - .SYNOPSIS - Check that help tokens do not contain unspecified tokens - - .DESCRIPTION - Check that the help comments do not contain tokens that are not specified in the external verification data file - - .PARAMETER HelpTokens - A string containing the text of the Help Comment - - .EXAMPLE - Test-HelpForUnspecifiedTokens -HelpTokens $HelpTokens - #> - [CmdletBinding()] - [OutputType([System.Exception], [System.Void])] - param ( - [parameter(Mandatory = $true)] - [HashTable]$HelpTokens - ) - - try { - - $module = Get-Module -Name PSQualityCheck - - if (Test-Path -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) { - - $helpElementRules = (Import-PowerShellDataFile -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) - - } - else { - - throw "Unable to load Checks\HelpElementRules.psd1" - - } - - $tokenErrors = @() - $helpTokensKeys = @() - - # Create an array of the help element rules elements - for ($order = 1; $order -le $helpElementRules.Count; $order++) { - - $token = $helpElementRules."$order" - - $helpTokensKeys += $token.key - - } - - # search through the found tokens and match them against the rules - foreach ($key in $HelpTokens.Keys) { - - if ( $key -notin $helpTokensKeys ) { - - $tokenErrors += $key - - } - - } - - if ($tokenErrors.Count -ge 1) { - throw "Found extra, non-specified, token(s): $tokenErrors" - } - - } - catch { - - throw $_.Exception.Message - - } - -} - function Test-HelpTokensCountIsValid { <# .SYNOPSIS @@ -887,7 +806,7 @@ function Test-HelpTokensCountIsValid { Check that the help tokens count is valid by making sure that they appear between Min and Max times .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .EXAMPLE Test-HelpTokensCountIsValid -HelpTokens $HelpTokens @@ -906,9 +825,11 @@ function Test-HelpTokensCountIsValid { $module = Get-Module -Name PSQualityCheck - if (Test-Path -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) { + $helpElementRulesPath = (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1") + + if (Test-Path -Path $helpElementRulesPath) { - $helpElementRules = (Import-PowerShellDataFile -Path (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1")) + $helpElementRules = Import-PowerShellDataFile -Path $helpElementRulesPath } else { @@ -979,7 +900,7 @@ function Test-HelpTokensParamsMatch { Checks to see whether the parameters in the param block and in the help PARAMETER statements exist in both locations .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .PARAMETER ParameterVariables A object containing the parameters from the param block @@ -1076,7 +997,7 @@ function Test-HelpTokensTextIsValid { Check that the Help Tokens text is valid by making sure that they its not empty .PARAMETER HelpTokens - A string containing the text of the Help Comment + A array of tokens containing the tokens of the Help Comment .EXAMPLE Test-HelpTokensTextIsValid -HelpTokens $HelpTokens @@ -1134,20 +1055,20 @@ function Test-ImportModuleIsValid { .DESCRIPTION Test that the Import-Module commands contain a -Name parameter, and one of RequiredVersion, MinimumVersion or MaximumVersion - .PARAMETER ParsedFile + .PARAMETER ParsedContent An object containing the source file parsed into its Tokenizer components .PARAMETER ImportModuleTokens - An object containing the Import-Module calls found + An object containing the Import-Module tokens found .EXAMPLE - TestImportModuleIsValid -ParsedFile $parsedFile -ImportModuleTokens $importModuleTokens + TestImportModuleIsValid -ParsedContent $ParsedContent -ImportModuleTokens $importModuleTokens #> [CmdletBinding()] [OutputType([System.Exception], [System.Void])] param ( [parameter(Mandatory = $true)] - [System.Object[]]$ParsedFile, + [System.Object[]]$ParsedContent, [parameter(Mandatory = $true)] [System.Object[]]$ImportModuleTokens ) @@ -1160,10 +1081,15 @@ function Test-ImportModuleIsValid { foreach ($token in $importModuleTokens) { # Get the full details of the command - $importModuleStatement = Get-TokenComponent -ParsedFileContent $ParsedFile -StartLine $token.StartLine + $importModuleStatement = Get-TokenComponent -ParsedContent $ParsedContent -StartLine $token.StartLine # Get the name of the module to be imported (for logging only) - $name = ($importModuleStatement | Where-Object { $_.Type -eq "String" } | Select-Object -First 1).Content + $name = ($importModuleStatement | Where-Object { $_.Type -eq "CommandArgument" } | Select-Object -First 1).Content + if ($null -eq $name) { + + $name = ($importModuleStatement | Where-Object { $_.Type -eq "String" } | Select-Object -First 1).Content + + } # if the -Name parameter is not found if (-not($importModuleStatement | Where-Object { $_.Type -eq "CommandParameter" -and $_.Content -eq "-Name" })) { @@ -1248,3 +1174,146 @@ function Test-ParameterVariablesHaveType { } +function Test-RequiredToken { + <# + .SYNOPSIS + Check that help tokens contain required tokens + + .DESCRIPTION + Check that the help comments contain tokens that are specified in the external verification data file + + .PARAMETER HelpTokens + A array of tokens containing the tokens of the Help Comment + + .EXAMPLE + Test-RequiredToken -HelpTokens $HelpTokens + #> + [CmdletBinding()] + [OutputType([System.Exception], [System.Void])] + param ( + [parameter(Mandatory = $true)] + [HashTable]$HelpTokens + ) + + try { + + $module = Get-Module -Name PSQualityCheck + + $helpElementRulesPath = (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1") + + if (Test-Path -Path $helpElementRulesPath) { + + $helpElementRules = Import-PowerShellDataFile -Path $helpElementRulesPath + + } + else { + + throw "Unable to load Checks\HelpElementRules.psd1" + + } + + $tokenErrors = @() + + for ($order = 1; $order -le $helpElementRules.Count; $order++) { + + $token = $helpElementRules."$order" + + if ($token.Key -notin $HelpTokens.Keys ) { + + if ($token.Required -eq $true) { + + $tokenErrors += $token.Key + + } + + } + + } + + if ($tokenErrors.Count -ge 1) { + throw "Missing required token(s): $tokenErrors" + } + + } + catch { + + throw $_.Exception.Message + + } + +} + +function Test-UnspecifiedToken { + <# + .SYNOPSIS + Check that help tokens do not contain unspecified tokens + + .DESCRIPTION + Check that the help comments do not contain tokens that are not specified in the external verification data file + + .PARAMETER HelpTokens + A array of tokens containing the tokens of the Help Comment + + .EXAMPLE + Test-UnspecifiedToken -HelpTokens $HelpTokens + #> + [CmdletBinding()] + [OutputType([System.Exception], [System.Void])] + param ( + [parameter(Mandatory = $true)] + [HashTable]$HelpTokens + ) + + try { + + $module = Get-Module -Name PSQualityCheck + + $helpElementRulesPath = (Join-Path -Path $module.ModuleBase -ChildPath "Checks\HelpElementRules.psd1") + + if (Test-Path -Path $helpElementRulesPath) { + + $helpElementRules = Import-PowerShellDataFile -Path $helpElementRulesPath + + } + else { + + throw "Unable to load Checks\HelpElementRules.psd1" + + } + + $tokenErrors = @() + $helpTokensKeys = @() + + # Create an array of the help element rules elements + for ($order = 1; $order -le $helpElementRules.Count; $order++) { + + $token = $helpElementRules."$order" + + $helpTokensKeys += $token.key + + } + + # search through the found tokens and match them against the rules + foreach ($key in $HelpTokens.Keys) { + + if ( $key -notin $helpTokensKeys ) { + + $tokenErrors += $key + + } + + } + + if ($tokenErrors.Count -ge 1) { + throw "Found extra, non-specified, token(s): $tokenErrors" + } + + } + catch { + + throw $_.Exception.Message + + } + +} + diff --git a/PSQualityCheck.psd1 b/PSQualityCheck.psd1 index fcaa695..3a18c91 100644 --- a/PSQualityCheck.psd1 +++ b/PSQualityCheck.psd1 @@ -3,131 +3,131 @@ # # Generated by: Andrew Davidson # -# Generated on: 07/01/2021 +# Generated on: 11/01/2021 # @{ - # Script module or binary module file associated with this manifest. - RootModule = 'PSQualityCheck.psm1' +# Script module or binary module file associated with this manifest. +RootModule = 'PSQualityCheck.psm1' - # Version number of this module. - ModuleVersion = '1.0.10' +# Version number of this module. +ModuleVersion = '1.0.10' - # Supported PSEditions - # CompatiblePSEditions = @() +# Supported PSEditions +# CompatiblePSEditions = @() - # ID used to uniquely identify this module - GUID = '9daebff2-9a44-48e4-9d4b-bed18c3c8e4b' +# ID used to uniquely identify this module +GUID = '9daebff2-9a44-48e4-9d4b-bed18c3c8e4b' - # Author of this module - Author = 'Andrew Davidson' +# Author of this module +Author = 'Andrew Davidson' - # Company or vendor of this module - CompanyName = 'Andrew Davidson' +# Company or vendor of this module +CompanyName = 'Andrew Davidson' - # Copyright statement for this module - Copyright = '(c) Andrew Davidson. All rights reserved.' +# Copyright statement for this module +Copyright = '(c) Andrew Davidson. All rights reserved.' - # Description of the functionality provided by this module - Description = 'This module interfaces to a set of Pester tests that enable the enforcement of quality controls rules on PowerShell scripts and modules.' +# Description of the functionality provided by this module +Description = 'This module interfaces to a set of Pester tests that enable the enforcement of quality controls rules on PowerShell scripts and modules.' - # Minimum version of the PowerShell engine required by this module - PowerShellVersion = '5.0' +# Minimum version of the PowerShell engine required by this module +PowerShellVersion = '5.0' - # Name of the PowerShell host required by this module - # PowerShellHostName = '' +# Name of the PowerShell host required by this module +# PowerShellHostName = '' - # Minimum version of the PowerShell host required by this module - # PowerShellHostVersion = '' +# Minimum version of the PowerShell host required by this module +# PowerShellHostVersion = '' - # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. - # DotNetFrameworkVersion = '' +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# DotNetFrameworkVersion = '' - # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. - # ClrVersion = '' +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# ClrVersion = '' - # Processor architecture (None, X86, Amd64) required by this module - # ProcessorArchitecture = '' +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' - # Modules that must be imported into the global environment prior to importing this module - # RequiredModules = @() +# Modules that must be imported into the global environment prior to importing this module +# RequiredModules = @() - # Assemblies that must be loaded prior to importing this module - # RequiredAssemblies = @() +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() - # Script files (.ps1) that are run in the caller's environment prior to importing this module. - # ScriptsToProcess = @() +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() - # Type files (.ps1xml) to be loaded when importing this module - # TypesToProcess = @() +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() - # Format files (.ps1xml) to be loaded when importing this module - # FormatsToProcess = @() +# Format files (.ps1xml) to be loaded when importing this module +# FormatsToProcess = @() - # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess - NestedModules = @('PSQualityCheck.Functions.psd1') +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +NestedModules = @('PSQualityCheck.Functions.psd1') - # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. - FunctionsToExport = 'Invoke-PSQualityCheck' +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Invoke-PSQualityCheck' - # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. - CmdletsToExport = @() +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() - # Variables to export from this module - # VariablesToExport = @() +# Variables to export from this module +# VariablesToExport = @() - # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. - AliasesToExport = @() +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() - # DSC resources to export from this module - # DscResourcesToExport = @() +# DSC resources to export from this module +# DscResourcesToExport = @() - # List of all modules packaged with this module - # ModuleList = @() +# List of all modules packaged with this module +# ModuleList = @() - # List of all files packaged with this module - # FileList = @() +# List of all files packaged with this module +# FileList = @() - # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. - PrivateData = @{ +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ - PSData = @{ + PSData = @{ - # Tags applied to this module. These help with module discovery in online galleries. - Tags = 'powershell', 'powershell-module', 'tests', 'quality', 'quality-check', - 'pester', 'pester-tests' + # Tags applied to this module. These help with module discovery in online galleries. + Tags = 'powershell', 'powershell-module', 'tests', 'quality', 'quality-check', + 'pester', 'pester-tests' - # A URL to the license for this module. - LicenseUri = 'https://github.com/andrewrdavidson/PSQualityCheck/blob/main/LICENSE' + # A URL to the license for this module. + LicenseUri = 'https://github.com/andrewrdavidson/PSQualityCheck/blob/main/LICENSE' - # A URL to the main website for this project. - ProjectUri = 'https://github.com/andrewrdavidson/PSQualityCheck' + # A URL to the main website for this project. + ProjectUri = 'https://github.com/andrewrdavidson/PSQualityCheck' - # A URL to an icon representing this module. - # IconUri = '' + # A URL to an icon representing this module. + # IconUri = '' - # ReleaseNotes of this module - # ReleaseNotes = '' + # ReleaseNotes of this module + # ReleaseNotes = '' - # Prerelease string of this module - Prerelease = 'alpha2' + # Prerelease string of this module + # Prerelease = '' - # Flag to indicate whether the module requires explicit user acceptance for install/update/save - # RequireLicenseAcceptance = $false + # Flag to indicate whether the module requires explicit user acceptance for install/update/save + # RequireLicenseAcceptance = $false - # External dependent modules of this module - # ExternalModuleDependencies = @() + # External dependent modules of this module + # ExternalModuleDependencies = @() - } # End of PSData hashtable + } # End of PSData hashtable - } # End of PrivateData hashtable +} # End of PrivateData hashtable - # HelpInfo URI of this module - HelpInfoURI = 'https://github.com/andrewrdavidson/PSQualityCheck/wiki' +# HelpInfo URI of this module +HelpInfoURI = 'https://github.com/andrewrdavidson/PSQualityCheck/wiki' - # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. - # DefaultCommandPrefix = '' +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' } From 775b2178dd25141770d02a8964af8d34837904b4 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 16:04:00 +0000 Subject: [PATCH 29/33] Update README.md --- README.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7f5528f..6463743 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,7 @@ The quality standards are summarised here: [Quality Standards Summary](https://g **Commits** -[![commits since 1.0.9](https://img.shields.io/github/commits-since/andrewrdavidson/psqualitycheck/1.0.9/main?include_prereleases)](https://github.com/andrewrdavidson/PSQualityCheck/releases/1.0.9) -[![commits since 1.0.10-alpha2](https://img.shields.io/github/commits-since/andrewrdavidson/psqualitycheck/latest/release-1.0.10?include_prereleases)](https://github.com/andrewrdavidson/PSQualityCheck/releases/1.0.10-alpha1) +[![commits since 1.0.10](https://img.shields.io/github/commits-since/andrewrdavidson/psqualitycheck/1.0.10/main?include_prereleases)](https://github.com/andrewrdavidson/PSQualityCheck/releases/1.0.10) #### Issues @@ -131,13 +130,13 @@ A quick description of the available Pester tests |PowerShell Version|PSQualityCheck Version|Operating System Result |:---|:---|:---| -|7.1.0|1.0.9|

![Windows 10 - Pass](https://img.shields.io/badge/windows%2010-pass-brightgreen) ![Server 2019 - Pass](https://img.shields.io/badge/server%202019-pass-brightgreen) ![Server 2016 - Pass](https://img.shields.io/badge/server%202016-pass-brightgreen) ![Ubuntu 20.04 - Fail](https://img.shields.io/badge/ubuntu%2020.04-fail-red)

| -|5.1|1.0.9|![Windows 10 - Fail](https://img.shields.io/badge/windows%2010-pass-brightgreen) ![Server 2019 - Pass](https://img.shields.io/badge/server%202019-pass-brightgreen) ![Server 2016 - Pass](https://img.shields.io/badge/server%202016-pass-brightgreen)|n/a| +|7.1.0|1.0.10|

![Windows 10 - Pass](https://img.shields.io/badge/windows%2010-pass-brightgreen) ![Server 2019 - Pass](https://img.shields.io/badge/server%202019-pass-brightgreen) ![Server 2016 - Pass](https://img.shields.io/badge/server%202016-pass-brightgreen) ![Ubuntu 20.04 - Pass](https://img.shields.io/badge/ubuntu%2020.04-pass-brightgreen)

| +|5.1|1.0.10|![Windows 10 - Fail](https://img.shields.io/badge/windows%2010-pass-brightgreen) ![Server 2019 - Pass](https://img.shields.io/badge/server%202019-pass-brightgreen) ![Server 2016 - Pass](https://img.shields.io/badge/server%202016-pass-brightgreen)|n/a| #### RuleSet/PowerShell version/PSQualityCheck testing matrix |RuleSet|PSQualityCheck Version|PowerShell Result| |:---|:---|:---| -|None|1.0.9|![PowerShell 7.1.0 - Pass](https://img.shields.io/badge/powershell%207.1.0-pass-brightgreen) ![PowerShell 5.1 - Pass](https://img.shields.io/badge/powershell%205.1-pass-brightgreen)| -|[indented-automation](https://github.com/indented-automation/ScriptAnalyzerRules)
(used by SonarQube)|1.0.9|![PowerShell 7.1.0 - Pass](https://img.shields.io/badge/powershell%207.1.0-pass-brightgreen) ![PowerShell 5.1 - Pass](https://img.shields.io/badge/powershell%205.1-pass-brightgreen)| +|None|1.0.10|![PowerShell 7.1.0 - Pass](https://img.shields.io/badge/powershell%207.1.0-pass-brightgreen) ![PowerShell 5.1 - Pass](https://img.shields.io/badge/powershell%205.1-pass-brightgreen)| +|[indented-automation](https://github.com/indented-automation/ScriptAnalyzerRules)
(used by SonarQube)|1.0.10|![PowerShell 7.1.0 - Pass](https://img.shields.io/badge/powershell%207.1.0-pass-brightgreen) ![PowerShell 5.1 - Pass](https://img.shields.io/badge/powershell%205.1-pass-brightgreen)| |[PSScriptAnalyzer](https://github.com/PowerShell/PSScriptAnalyzer/tree/master/Tests/Engine/CommunityAnalyzerRules)
(used by VSCode)|1.0.9|![PowerShell 7.1.0 - Fail](https://img.shields.io/badge/powershell%207.1.0-fail-red) ![PowerShell 5.1 - Further Testing To Be Performed](https://img.shields.io/badge/powershell%205.1-not%20run-lightgrey)| From fb79676ced3f30f7e1c0126d65ff6ec151a33af4 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 16:07:04 +0000 Subject: [PATCH 30/33] Release 1.0.10 build --- PSQualityCheck.psm1 | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/PSQualityCheck.psm1 b/PSQualityCheck.psm1 index 078d8df..52e30d2 100644 --- a/PSQualityCheck.psm1 +++ b/PSQualityCheck.psm1 @@ -90,10 +90,10 @@ function Invoke-PSQualityCheck { Set-StrictMode -Version Latest # External Modules - Import-Module -Name "Pester" -MinimumVersion "5.1.0" -Force - Import-Module -Name "PSScriptAnalyzer" -MinimumVersion "1.19.1" -Force + Import-Module -Name 'Pester' -MinimumVersion '5.1.0' -Force + Import-Module -Name 'PSScriptAnalyzer' -MinimumVersion '1.19.1' -Force - $modulePath = (Get-Module -Name PSQualityCheck).ModuleBase + $modulePath = (Get-Module -Name 'PSQualityCheck').ModuleBase # Analyse the incoming Path and File parameters and produce a list of Modules and Scripts @@ -111,8 +111,8 @@ function Invoke-PSQualityCheck { # Test whether the item is a directory (also tells us if it exists) if (Test-Path -Path $item -PathType Container) { - $scriptsToTest += Get-FileList -Path $item -Extension ".ps1" - $modulesToTest += Get-FileList -Path $item -Extension ".psm1" + $scriptsToTest += Get-FileList -Path $item -Extension '.ps1' + $modulesToTest += Get-FileList -Path $item -Extension '.psm1' } else { @@ -165,7 +165,7 @@ function Invoke-PSQualityCheck { $configuration = [PesterConfiguration]::Default $configuration.Run.Exit = $false $configuration.CodeCoverage.Enabled = $false - $configuration.Output.Verbosity = "Detailed" + $configuration.Output.Verbosity = 'Detailed' $configuration.Run.PassThru = $true $configuration.Should.ErrorAction = 'Stop' @@ -180,12 +180,12 @@ function Invoke-PSQualityCheck { $extractPath = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath (New-Guid).Guid # Run the Module tests on all the valid module files found - $container1 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Module.Tests.ps1") -Data @{ Source = $modulesToTest } + $container1 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Module.Tests.ps1') -Data @{ Source = $modulesToTest } $configuration.Run.Container = $container1 $moduleResults = Invoke-Pester -Configuration $configuration # Extract all the functions from the modules into individual .ps1 files ready for testing - $container2 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Function-Extraction.Tests.ps1") -Data @{ Source = $modulesToTest; ExtractPath = $extractPath } + $container2 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Function-Extraction.Tests.ps1') -Data @{ Source = $modulesToTest; ExtractPath = $extractPath } $configuration.Run.Container = $container2 $extractionResults = Invoke-Pester -Configuration $configuration @@ -193,7 +193,7 @@ function Invoke-PSQualityCheck { $extractedScriptsToTest = Get-ChildItem -Path $extractPath -Include '*.ps1' -Recurse # Run the Script tests against all the extracted functions .ps1 files - $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Script.Tests.ps1") -Data @{ Source = $extractedScriptsToTest; SonarQubeRules = $SonarQubeRulesPath } + $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Script.Tests.ps1') -Data @{ Source = $extractedScriptsToTest; SonarQubeRules = $SonarQubeRulesPath } $configuration.Run.Container = $container3 $extractedScriptResults = Invoke-Pester -Configuration $configuration @@ -202,7 +202,7 @@ function Invoke-PSQualityCheck { if ($scriptsToTest.Count -ge 1) { # Run the Script tests against all the valid script files found - $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Script.Tests.ps1") -Data @{ Source = $scriptsToTest; SonarQubeRules = $SonarQubeRulesPath } + $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Script.Tests.ps1') -Data @{ Source = $scriptsToTest; SonarQubeRules = $SonarQubeRulesPath } $configuration.Run.Container = $container3 $scriptResults = Invoke-Pester -Configuration $configuration @@ -290,7 +290,7 @@ function Invoke-PSQualityCheck { 'Skipped' = $skipped } - # This works on PS5 + # This works on PS5 and PS7 $qualityCheckResults | ForEach-Object { [PSCustomObject]@{ 'Test' = $_.Test From 74be7b5d3fa82bd0732126be037802c901b6246b Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 16:10:37 +0000 Subject: [PATCH 31/33] Release 1.0.10 build --- .../PSQualityCheck/Invoke-PSQualityCheck.ps1 | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Source/PSQualityCheck/Invoke-PSQualityCheck.ps1 b/Source/PSQualityCheck/Invoke-PSQualityCheck.ps1 index 0785ff9..7abde27 100644 --- a/Source/PSQualityCheck/Invoke-PSQualityCheck.ps1 +++ b/Source/PSQualityCheck/Invoke-PSQualityCheck.ps1 @@ -90,10 +90,10 @@ function Invoke-PSQualityCheck { Set-StrictMode -Version Latest # External Modules - Import-Module -Name "Pester" -MinimumVersion "5.1.0" -Force - Import-Module -Name "PSScriptAnalyzer" -MinimumVersion "1.19.1" -Force + Import-Module -Name 'Pester' -MinimumVersion '5.1.0' -Force + Import-Module -Name 'PSScriptAnalyzer' -MinimumVersion '1.19.1' -Force - $modulePath = (Get-Module -Name PSQualityCheck).ModuleBase + $modulePath = (Get-Module -Name 'PSQualityCheck').ModuleBase # Analyse the incoming Path and File parameters and produce a list of Modules and Scripts @@ -111,8 +111,8 @@ function Invoke-PSQualityCheck { # Test whether the item is a directory (also tells us if it exists) if (Test-Path -Path $item -PathType Container) { - $scriptsToTest += Get-FileList -Path $item -Extension ".ps1" - $modulesToTest += Get-FileList -Path $item -Extension ".psm1" + $scriptsToTest += Get-FileList -Path $item -Extension '.ps1' + $modulesToTest += Get-FileList -Path $item -Extension '.psm1' } else { @@ -165,7 +165,7 @@ function Invoke-PSQualityCheck { $configuration = [PesterConfiguration]::Default $configuration.Run.Exit = $false $configuration.CodeCoverage.Enabled = $false - $configuration.Output.Verbosity = "Detailed" + $configuration.Output.Verbosity = 'Detailed' $configuration.Run.PassThru = $true $configuration.Should.ErrorAction = 'Stop' @@ -180,12 +180,12 @@ function Invoke-PSQualityCheck { $extractPath = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath (New-Guid).Guid # Run the Module tests on all the valid module files found - $container1 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Module.Tests.ps1") -Data @{ Source = $modulesToTest } + $container1 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Module.Tests.ps1') -Data @{ Source = $modulesToTest } $configuration.Run.Container = $container1 $moduleResults = Invoke-Pester -Configuration $configuration # Extract all the functions from the modules into individual .ps1 files ready for testing - $container2 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Function-Extraction.Tests.ps1") -Data @{ Source = $modulesToTest; ExtractPath = $extractPath } + $container2 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Function-Extraction.Tests.ps1') -Data @{ Source = $modulesToTest; ExtractPath = $extractPath } $configuration.Run.Container = $container2 $extractionResults = Invoke-Pester -Configuration $configuration @@ -193,7 +193,7 @@ function Invoke-PSQualityCheck { $extractedScriptsToTest = Get-ChildItem -Path $extractPath -Include '*.ps1' -Recurse # Run the Script tests against all the extracted functions .ps1 files - $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Script.Tests.ps1") -Data @{ Source = $extractedScriptsToTest; SonarQubeRules = $SonarQubeRulesPath } + $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Script.Tests.ps1') -Data @{ Source = $extractedScriptsToTest; SonarQubeRules = $SonarQubeRulesPath } $configuration.Run.Container = $container3 $extractedScriptResults = Invoke-Pester -Configuration $configuration @@ -202,7 +202,7 @@ function Invoke-PSQualityCheck { if ($scriptsToTest.Count -ge 1) { # Run the Script tests against all the valid script files found - $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath "Checks\Script.Tests.ps1") -Data @{ Source = $scriptsToTest; SonarQubeRules = $SonarQubeRulesPath } + $container3 = New-PesterContainer -Path (Join-Path -Path $modulePath -ChildPath 'Checks\Script.Tests.ps1') -Data @{ Source = $scriptsToTest; SonarQubeRules = $SonarQubeRulesPath } $configuration.Run.Container = $container3 $scriptResults = Invoke-Pester -Configuration $configuration @@ -290,7 +290,7 @@ function Invoke-PSQualityCheck { 'Skipped' = $skipped } - # This works on PS5 + # This works on PS5 and PS7 $qualityCheckResults | ForEach-Object { [PSCustomObject]@{ 'Test' = $_.Test From 54897a91f9eaf297edaecd3e62fa831f63296860 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 16:12:06 +0000 Subject: [PATCH 32/33] Release 1.0.10 build --- Source/Build.Properties.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Build.Properties.json b/Source/Build.Properties.json index 8ed0942..8c25c5e 100644 --- a/Source/Build.Properties.json +++ b/Source/Build.Properties.json @@ -28,9 +28,9 @@ "Tags": [ "powershell", "powershell-module", - "tests", "quality", "quality-check", + "tests", "pester", "pester-tests" ] From ffc451ce2c70bbaac547c4cd77eabfc2f0c87134 Mon Sep 17 00:00:00 2001 From: Andrew Davidson Date: Mon, 11 Jan 2021 16:13:28 +0000 Subject: [PATCH 33/33] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6463743..f214d8d 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ A quick description of the available Pester tests |7.1.0|1.0.10|

![Windows 10 - Pass](https://img.shields.io/badge/windows%2010-pass-brightgreen) ![Server 2019 - Pass](https://img.shields.io/badge/server%202019-pass-brightgreen) ![Server 2016 - Pass](https://img.shields.io/badge/server%202016-pass-brightgreen) ![Ubuntu 20.04 - Pass](https://img.shields.io/badge/ubuntu%2020.04-pass-brightgreen)

| |5.1|1.0.10|![Windows 10 - Fail](https://img.shields.io/badge/windows%2010-pass-brightgreen) ![Server 2019 - Pass](https://img.shields.io/badge/server%202019-pass-brightgreen) ![Server 2016 - Pass](https://img.shields.io/badge/server%202016-pass-brightgreen)|n/a| -#### RuleSet/PowerShell version/PSQualityCheck testing matrix +#### RuleSet/PSQualityCheck/PowerShell version testing matrix |RuleSet|PSQualityCheck Version|PowerShell Result| |:---|:---|:---|