diff --git a/.github/workflows/quality-gates.yml b/.github/workflows/quality-gates.yml index 5a18362..41ffb01 100644 --- a/.github/workflows/quality-gates.yml +++ b/.github/workflows/quality-gates.yml @@ -1,14 +1,20 @@ # Quality gates for IntuneScriptLab. # -# Four jobs, because the module makes claims that can only fail on different hosts: +# Five jobs, because the module makes claims that can only fail on different hosts: # # tests Windows, PowerShell 7. PSScriptAnalyzer at Error and Warning over the module, the # kit and the tests, the 115-character line limit, then the whole Pester suite (the -# module's unit and integration suites and the validation kit's unit suite) shuffled, -# with an 80% coverage gate over Public/ and Private/. Nothing here reaches a tenant: -# every Graph call in the suites goes through the mocked Invoke-IslGraphRequest seam, -# and the suites that need an elevated session, a lab account or a Graph connection -# skip themselves. +# module's unit and integration suites and the validation kit's unit suite) with an +# 80% coverage gate over Public/ and Private/. Nothing here +# reaches a tenant: every Graph call in the suites goes through the mocked +# Invoke-IslGraphRequest seam, and the suites that need an elevated session, a lab +# account or a Graph connection skip themselves. +# +# Every Pester run goes through Tests/Invoke-Tests.ps1, the script a developer runs as well. It +# shuffles the order, so a test that only passes because of what ran before it fails here +# rather than on somebody's machine, and it fails when Pester's result is not Passed, which +# covers a failed BeforeAll or AfterAll and a file that failed discovery, or when no tests ran. +# The seed is in the failure message and in the job summary; -ShuffleSeed repeats that order. # # desktop Windows PowerShell 5.1. The scripts the module analyzes run under 5.1 on the # device, and so does the module: the manifest declares CompatiblePSEditions Desktop @@ -32,6 +38,11 @@ # reference matches the rules, and Get-Help serves every command's full help on a # case-sensitive filesystem - the only place the -Help.xml capital H can fail. # +# rehearsal Windows. The release as far as the upload: Build/Publish-Module.ps1 -WhatIf builds +# the help, measures the manifest against the Gallery's limits, stages the allowlist +# and imports the staged copy in a new process. A release that would fail at the tag +# fails at the pull request instead. +# # There is no Linux test job on purpose: the harness launches Windows PowerShell hosts, reads # the registry and registers scheduled tasks, and the rules are about what happens on a Windows # device. The module imports on Linux, which the help job proves. @@ -45,6 +56,11 @@ on: branches: [main] workflow_dispatch: + # Nightly, so that a change outside the repository shows up within a day: a new runner image, + # a Windows update that adds an in-box module, a Gallery that stops serving a pinned tool. + schedule: + - cron: '30 4 * * *' + # Callable so release.yml can run these exact gates before publishing. A tag can be pushed # at any commit, including one that never passed a pull request, so the release re-runs the # gates rather than trusting that they ran at some point. @@ -54,7 +70,7 @@ permissions: contents: read env: - # Style limit from .github/instructions/style-enforcement.instructions.md + # Style limit, STY-03 in .github/instructions/powershell-style.instructions.md MAX_LINE_LENGTH: '115' jobs: @@ -69,15 +85,21 @@ jobs: - name: Install build modules shell: pwsh run: | - # Runners ship Pester 5.x. Pester 6 must be installed explicitly, and the version - # range keeps a future Pester 7 from silently changing the assertion surface. The - # floor is 6.2 to match the #Requires line every suite carries. - Install-PSResource -Name Pester -Version '[6.2.0,7.0.0)' -Scope CurrentUser -TrustRepository - Install-PSResource -Name PSScriptAnalyzer -Scope CurrentUser -TrustRepository + $ErrorActionPreference = 'Stop' + # Runners ship Pester 5.x. Both tools are installed at one fixed version: a newer + # release can change what an assertion or a rule means, and with it what a passing + # build means. 6.2.0 is the version the #Requires line of every suite names. + Install-PSResource -Name Pester -Version 6.2.0 -Scope CurrentUser -TrustRepository + Install-PSResource -Name PSScriptAnalyzer -Version 1.25.0 -Scope CurrentUser -TrustRepository $PSVersionTable | ConvertTo-Json -Depth 3 - # The mirrored standards folder holds examples that are not this module's code; the - # module, the kit, the build scripts and the tests are what is gated. + # The module, the kit, the build scripts and the tests are what is gated. The default + # rules at Error and Warning include the five of PSScriptAnalyzer's ScriptSecurity preset + # (plain-text passwords, user name and password parameters, ConvertTo-SecureString + # -AsPlainText, hard-coded computer names and PSCredential parameters), so this step is + # also the static analysis of a security gate. There is no credential scan and no + # dependency scan in this workflow: the module has no dependency, secret scanning is a + # repository setting, and whether a scanner belongs here is an open decision (#74). - name: PSScriptAnalyzer and line length shell: pwsh run: | @@ -103,58 +125,20 @@ jobs: } Write-Host "PSScriptAnalyzer clean, no line over $env:MAX_LINE_LENGTH characters, in $($files.Count) files." + # Every suite, shuffled, with the 80% coverage gate. The reports are written before the + # checks run, so a failed run still leaves both files to upload. - name: Pester with coverage shell: pwsh run: | $ErrorActionPreference = 'Stop' - Import-Module Pester -MinimumVersion 6.2.0 - $cfg = New-PesterConfiguration - $cfg.Run.Path = './Tests', './Validation/Tests' - $cfg.Run.PassThru = $true - $cfg.Output.Verbosity = 'Detailed' - $cfg.Should.DisableV5 = $true - # Shuffled, so a test that only passes because of what ran before it fails here rather - # than on somebody's machine. The seed is printed so a failing order can be replayed - # locally with $cfg.Run.ShuffleSeed. - $seed = Get-Random -Minimum 1 -Maximum 2147483647 - $cfg.Run.Shuffle = $true - $cfg.Run.ShuffleSeed = $seed - Write-Host "Pester shuffle seed: $seed" - - $cfg.CodeCoverage.Enabled = $true - $cfg.CodeCoverage.Path = './Public/*.ps1', './Private/*.ps1', './Private/Rules/*.ps1' - # CoveragePercentTarget only reports; the gate below is what enforces it. - $cfg.CodeCoverage.CoveragePercentTarget = 80 - # Written before the gates below run, so a failed run still leaves both files to upload - $cfg.CodeCoverage.OutputPath = 'coverage.xml' - $cfg.TestResult.Enabled = $true - $cfg.TestResult.OutputPath = 'testResults.xml' - - $result = Invoke-Pester -Configuration $cfg - - # A file that fails discovery contributes nothing to FailedCount, so both are checked. - if ($result.FailedCount -gt 0 -or $result.FailedContainersCount -gt 0) { - throw ("$($result.FailedCount) test(s) and $($result.FailedContainersCount) " + - "container(s) failed under shuffle seed $seed.") - } - - $coverage = [math]::Round($result.CodeCoverage.CoveragePercent, 2) - Write-Host "Code coverage: $coverage%" - "## Pester`n`nPassed $($result.PassedCount), failed $($result.FailedCount), skipped " + - "$($result.SkippedCount); coverage $coverage% (seed $seed)." | - Out-File -Append -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 - if ($coverage -lt 80) { - throw "Code coverage $coverage% is below the 80% gate." - } + ./Tests/Invoke-Tests.ps1 -CodeCoverage -OutputPath ./reports -Output Detailed -SummaryPath $env:GITHUB_STEP_SUMMARY - name: Upload test results and coverage if: always() uses: actions/upload-artifact@v7 with: name: tests-and-analysis - path: | - testResults.xml - coverage.xml + path: reports/ if-no-files-found: warn desktop: @@ -190,44 +174,31 @@ jobs: if ($noHelp) { throw "Commands serving no help under 5.1: $($noHelp -join ', ')" } Write-Host "All $($actual.Count) commands exported with help under Windows PowerShell 5.1." - # Pester 6 declares PowerShellVersion 5.1 and runs the suite unchanged. + # Pester 6 declares PowerShellVersion 5.1 and runs the suite unchanged. Windows PowerShell + # has no PSResourceGet, so PowerShellGet installs the same fixed version the other jobs use. - name: Install Pester shell: powershell run: | $ErrorActionPreference = 'Stop' - Install-Module -Name Pester -MinimumVersion 6.2.0 -MaximumVersion 6.99.99 -Scope CurrentUser -Force -SkipPublisherCheck -AllowClobber - Import-Module Pester -MinimumVersion 6.2.0 + Install-Module -Name Pester -RequiredVersion 6.2.0 -Scope CurrentUser -Force -SkipPublisherCheck -AllowClobber + Import-Module Pester -RequiredVersion 6.2.0 "Pester $((Get-Module Pester).Version) on PowerShell $($PSVersionTable.PSVersion)" | Write-Host + # The integration suite as well: it launches the 5.1 hosts the harness uses on a device. + # The hosted runner's token is not elevated (IsInRole Administrator is false), so the + # SYSTEM-context tests skip here as they do under pwsh; they run on the lab devices - name: Pester under Windows PowerShell 5.1 shell: powershell run: | $ErrorActionPreference = 'Stop' - Import-Module Pester -MinimumVersion 6.2.0 - $cfg = New-PesterConfiguration - # The integration suite as well: it launches the 5.1 hosts the harness uses on a device. - # The hosted runner's token is not elevated (IsInRole Administrator is false), so the - # SYSTEM-context tests skip here as they do under pwsh; they run on the lab devices - $cfg.Run.Path = './Tests/Unit', './Tests/Integration', './Validation/Tests/Unit' - $cfg.Run.PassThru = $true - $cfg.Output.Verbosity = 'Normal' - $cfg.Should.DisableV5 = $true - $cfg.TestResult.Enabled = $true - $cfg.TestResult.OutputPath = 'testResults-desktop.xml' - $result = Invoke-Pester -Configuration $cfg - "## Pester under Windows PowerShell 5.1`n`nPassed $($result.PassedCount), failed $($result.FailedCount), " + - "skipped $($result.SkippedCount)." | Out-File -Append -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 - if ($result.FailedCount -gt 0 -or $result.FailedContainersCount -gt 0) { - throw "$($result.FailedCount) test(s) and $($result.FailedContainersCount) container(s) failed under Windows PowerShell 5.1." - } - Write-Host "Passed $($result.PassedCount), skipped $($result.SkippedCount) under Windows PowerShell 5.1." + ./Tests/Invoke-Tests.ps1 -OutputPath ./reports -SummaryPath $env:GITHUB_STEP_SUMMARY - name: Upload test results if: always() uses: actions/upload-artifact@v7 with: name: windows-powershell-5-1 - path: testResults-desktop.xml + path: reports/ if-no-files-found: warn arm64: @@ -241,8 +212,9 @@ jobs: - name: Install Pester shell: pwsh run: | - Install-PSResource -Name Pester -Version '[6.2.0,7.0.0)' -Scope CurrentUser -TrustRepository - Import-Module Pester -MinimumVersion 6.2.0 + $ErrorActionPreference = 'Stop' + Install-PSResource -Name Pester -Version 6.2.0 -Scope CurrentUser -TrustRepository + Import-Module Pester -RequiredVersion 6.2.0 "Pester $((Get-Module Pester).Version) on $([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)" | Write-Host @@ -250,27 +222,14 @@ jobs: shell: pwsh run: | $ErrorActionPreference = 'Stop' - Import-Module Pester -MinimumVersion 6.2.0 - $cfg = New-PesterConfiguration - $cfg.Run.Path = './Tests/Unit', './Validation/Tests/Unit' - $cfg.Run.PassThru = $true - $cfg.Output.Verbosity = 'Normal' - $cfg.Should.DisableV5 = $true - $cfg.TestResult.Enabled = $true - $cfg.TestResult.OutputPath = 'testResults-arm64.xml' - $result = Invoke-Pester -Configuration $cfg - "## Pester on Windows on ARM`n`nPassed $($result.PassedCount), failed $($result.FailedCount), " + - "skipped $($result.SkippedCount)." | Out-File -Append -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 - if ($result.FailedCount -gt 0 -or $result.FailedContainersCount -gt 0) { - throw "$($result.FailedCount) test(s) and $($result.FailedContainersCount) container(s) failed on ARM64." - } + ./Tests/Invoke-Tests.ps1 -TestType Unit -OutputPath ./reports -SummaryPath $env:GITHUB_STEP_SUMMARY - name: Upload test results if: always() uses: actions/upload-artifact@v7 with: name: windows-on-arm - path: testResults-arm64.xml + path: reports/ if-no-files-found: warn help: @@ -288,6 +247,7 @@ jobs: - name: Install PlatyPS shell: pwsh run: | + $ErrorActionPreference = 'Stop' Install-PSResource -Name Microsoft.PowerShell.PlatyPS -Version '1.0.3' -Scope CurrentUser -TrustRepository $PSVersionTable | ConvertTo-Json -Depth 3 @@ -399,3 +359,27 @@ jobs: throw 'Test-IntuneScript did not analyze the fixtures on Linux.' } Write-Host 'Test-IntuneScript analyzed both fixtures on Linux with the expected findings.' + + rehearsal: + name: 'Release rehearsal' + runs-on: windows-latest + + steps: + - name: Checkout + uses: actions/checkout@v7 + + # The same pin as the help job: the rehearsal rebuilds the MAML, and a different PlatyPS + # version would emit different XML than the committed help. + - name: Install PlatyPS + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + Install-PSResource -Name Microsoft.PowerShell.PlatyPS -Version '1.0.3' -Scope CurrentUser -TrustRepository + + # Everything the release does except the upload, which -WhatIf holds back. No API key is + # read under -WhatIf, so the job needs no secret. + - name: Stage and verify the package + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + ./Build/Publish-Module.ps1 -WhatIf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 436578b..99f444d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,7 +38,7 @@ permissions: jobs: # The same gates a pull request runs: analysis, the suites on Windows PowerShell 7 and 5.1 - # and on ARM64, and the command help gate on a case-sensitive filesystem. + # and on ARM64, the command help gate on a case-sensitive filesystem, and the release rehearsal. gates: name: 'Quality gates' uses: ./.github/workflows/quality-gates.yml @@ -57,7 +57,9 @@ jobs: # that was just verified. - name: Install PlatyPS shell: pwsh - run: Install-PSResource -Name Microsoft.PowerShell.PlatyPS -Version '1.0.3' -Scope CurrentUser -TrustRepository + run: | + $ErrorActionPreference = 'Stop' + Install-PSResource -Name Microsoft.PowerShell.PlatyPS -Version '1.0.3' -Scope CurrentUser -TrustRepository # A tag that disagrees with the manifest publishes a version nobody can correlate to # a commit, and the Gallery version cannot be corrected afterwards. Checked before diff --git a/CHANGELOG.md b/CHANGELOG.md index 8004a91..71e919e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,15 @@ entries are carried over from the manifest's release notes. or wrong for others). `.github/workflows/gallery-downloads.yml` reads every version from the v2 feed daily and publishes a shields.io endpoint file on the `badges` branch when the number moves; it is reusable from another module's repository through `workflow_call` with the package name. +- `Tests/Invoke-Tests.ps1`, the one script that runs the suites, on a developer's computer and in + every CI job. It shuffles the order, puts the seed in its failure message and takes it back with + `-ShuffleSeed`, and fails when Pester's result is not `Passed` or when no test passed or failed, + as when a filter leaves every test out. The CI jobs checked the failed tests and the failed + files only, so a failed `BeforeAll` passed, and the Windows PowerShell 5.1 and ARM64 jobs were + not shuffled. +- A `rehearsal` job in `quality-gates.yml` that runs `Build/Publish-Module.ps1 -WhatIf` on every + pull request, so that a release which would fail at the tag fails before the merge. The same + workflow now also runs every night. ### Changed @@ -44,6 +53,8 @@ entries are carried over from the manifest's release notes. build refuses any placeholder in double braces, where it looked for `{{ Fill` only. - The manifest no longer sets `CompanyName` to an empty string. The package's metadata is the same without the key. +- CI installs Pester 6.2.0 and PSScriptAnalyzer 1.25.0 exactly, where it took any Pester 6 from + 6.2.0 on and the newest PSScriptAnalyzer. ### Removed diff --git a/CLAUDE.md b/CLAUDE.md index 4f050a0..809d968 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -99,8 +99,9 @@ on `mobileApps/{id}` is refused (derived-type property) - fetch the app without A `Mock` defined in `BeforeEach` is not active in a Context's `BeforeAll`; define mocks in the Describe's `BeforeAll`. `Should-Invoke` for a call made in `BeforeAll` needs `-Scope Context`. -CI shuffles the suite and prints the seed; a test that only passes in declaration order fails -there first. +`Tests/Invoke-Tests.ps1` shuffles every run, locally and in each CI job, and puts the seed in its +failure message; a test that only passes in declaration order fails there first, and +`-ShuffleSeed` runs that order again. ### The MAML filename carries a capital H @@ -158,15 +159,21 @@ vault is searched, and the secret stays a `SecureString` until the publish call. ## Checks ```powershell -Invoke-Pester ./Tests, ./Validation/Tests # suites that need elevation, a lab account or PSScriptAnalyzer skip themselves +./Tests/Invoke-Tests.ps1 # every suite, shuffled; suites that need elevation, a lab account or PSScriptAnalyzer skip themselves +./Tests/Invoke-Tests.ps1 -CodeCoverage # the same with the 80% coverage gate, as the tests job runs it Invoke-ScriptAnalyzer -Path . -Recurse -Severity Error, Warning -ExcludeRule PSAvoidLongLines ./Build/Build-Help.ps1 # rebuild MAML after editing docs/ ./Build/Build-RuleReference.ps1 # rebuild docs/Rules.md after changing a rule ./Build/Publish-Module.ps1 -WhatIf # full release rehearsal, publishes nothing ``` -Run the unit suites under Windows PowerShell 5.1 as well before pushing: +`Tests/Invoke-Tests.ps1` is the one way the suites are run: it fails when Pester's result is not +`Passed` or when no tests ran, which a check of `FailedCount` alone does not. Run the unit suites +under Windows PowerShell 5.1 as well before pushing: ```powershell -powershell -NoProfile -Command "Invoke-Pester ./Tests/Unit, ./Validation/Tests/Unit" +powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit ``` + +The script sets strict mode for itself and turns it off around the Pester run, because the suites, +the validation kit and the module are not written for strict mode yet. Remove that when they are. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3027a46..f5f8ad6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,7 +40,7 @@ Everything specific to this module is in `CLAUDE.md`. The ones most often trippe ## The checks ```powershell -Invoke-Pester ./Tests, ./Validation/Tests # a few minutes; suites needing elevation, +./Tests/Invoke-Tests.ps1 # a few minutes, shuffled; suites needing elevation, # a lab account or PSScriptAnalyzer skip themselves Invoke-ScriptAnalyzer -Path . -Recurse -Severity Error, Warning -ExcludeRule PSAvoidLongLines ./Build/Build-Help.ps1 # after editing docs/ @@ -51,9 +51,12 @@ Invoke-ScriptAnalyzer -Path . -Recurse -Severity Error, Warning -ExcludeRule PSA Run the unit suites under Windows PowerShell 5.1 as well: ```powershell -powershell -NoProfile -Command "Invoke-Pester ./Tests/Unit, ./Validation/Tests/Unit" +powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit ``` +A failure message of `Invoke-Tests.ps1` carries the shuffle seed; `-ShuffleSeed ` runs the +same order again. + The suites reach no tenant: every Graph call goes through a mocked seam. A change to what a rule or the harness claims about Intune should also be run against a device you own, and the pull request should say what you ran and what it did. The validation kit under `Validation/` is how @@ -66,4 +69,5 @@ explains the rounds. - Add or update the tests that pin the behaviour, and a line in `CHANGELOG.md` under `[Unreleased]`. - The quality gates run on every pull request on PowerShell 7, Windows PowerShell 5.1, Windows on - ARM, and a case-sensitive filesystem for the help. + ARM, and a case-sensitive filesystem for the help, and they rehearse the release as far as the + upload. diff --git a/README.md b/README.md index 63ca97a..be2b8c8 100644 --- a/README.md +++ b/README.md @@ -696,11 +696,15 @@ tests skipped unless elevated. On Pester 5, assert on the result properties dire ## Tests ```powershell -Invoke-Pester .\Tests\Unit # fast: mocked launches, static analysis -Invoke-Pester .\Tests -Output Detailed # everything, including the real-process suites -Invoke-Pester .\Tests -ExcludeTagFilter Elevated # skip the SYSTEM-context tests explicitly +.\Tests\Invoke-Tests.ps1 -TestType Unit # mocked launches, static analysis +.\Tests\Invoke-Tests.ps1 -Output Detailed # everything, including the real-process suites +.\Tests\Invoke-Tests.ps1 -ExcludeTag Elevated # skip the SYSTEM-context tests explicitly ``` +`Tests\Invoke-Tests.ps1` runs the suites in shuffled order and fails unless every test, every +setup block and every file passed. Its failure message carries the seed, and `-ShuffleSeed` runs +that order again. + | Folder | What it holds | |---|---| | `Tests/Unit/Public` | One suite per exported function. The runtime commands are tested with the process launch mocked, so the status mapping runs in milliseconds. | @@ -710,10 +714,10 @@ Invoke-Pester .\Tests -ExcludeTagFilter Elevated # skip the SYSTEM-context tests Host coverage is split, not overlapping: the integration suites exercise the x64 runtime path on the x64 CI runner and the arm64 path on an ARM64 development machine (each refuses the other's -64-bit host), and the x86 path on both. The Unit suites pass with PowerShell 7 and with Windows -PowerShell 5.1 as the module host: CI runs the whole suite on PowerShell 7, shuffled and with an -80% coverage gate, and the unit suites again on Windows PowerShell 5.1 and on the Windows on ARM -runner. +64-bit host), and the x86 path on both. The suites pass with PowerShell 7 and with Windows +PowerShell 5.1 as the module host: CI runs the whole suite on PowerShell 7 with an 80% coverage +gate, the whole suite again on Windows PowerShell 5.1, and the unit suites on the Windows on ARM +runner, each through the same script and each shuffled. ## Help diff --git a/Tests/Invoke-Tests.ps1 b/Tests/Invoke-Tests.ps1 new file mode 100644 index 0000000..4103300 --- /dev/null +++ b/Tests/Invoke-Tests.ps1 @@ -0,0 +1,246 @@ +#Requires -Version 5.1 +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# +.SYNOPSIS +Runs the Pester suites of this repository in shuffled order and fails when they do not pass. + +.DESCRIPTION +The one way the suites are run, on a developer's computer and in every CI job, so that both get +the same answer. The run is shuffled, and the seed is printed and is part of the failure +message, so that an order which fails can be run again. The script fails when Pester's result +is not Passed, which also covers a failed BeforeAll or AfterAll and a file that failed +discovery, when no test passed or failed, and, with -CodeCoverage, when coverage of Public and +Private is below -MinimumCoverage. A run in which a filter left every test out, or in which +every test was skipped, has run nothing and fails for that reason. + +Suites that need an elevated session, a lab account or PSScriptAnalyzer skip themselves, so the +script needs neither elevation nor a tenant. It runs on PowerShell 7 and on Windows PowerShell +5.1. + +.PARAMETER TestType +Which suites to run. Unit is Tests/Unit and Validation/Tests/Unit. Integration is +Tests/Integration, the suites that start real Windows PowerShell processes. All, the default, +is both. + +.PARAMETER ExcludeTag +Tags of tests to leave out, for example Elevated for the tests that run as SYSTEM. Those tests +skip themselves in a session that is not elevated; the tag leaves them out of an elevated one. + +.PARAMETER CodeCoverage +Measures the coverage of Public, Private and Private/Rules, and fails below -MinimumCoverage. + +.PARAMETER MinimumCoverage +The lowest acceptable coverage, as a percentage of commands. The default is 80. + +.PARAMETER ShuffleSeed +The seed of the shuffled order. The default, 0, takes a new seed for each run. Pass the seed +from a failure message to run that order again. + +.PARAMETER OutputPath +A folder for the reports: testResults.xml in NUnit format and, with -CodeCoverage, +coverage.xml in JaCoCo format. Left out, no report is written. + +.PARAMETER Output +The detail Pester prints: None, Normal, Detailed or Diagnostic. The default is Normal. + +.PARAMETER SummaryPath +A Markdown file to which a summary of the run is appended: the counts, the shuffle seed and, +with -CodeCoverage, the coverage. It is written before the checks, so a failed run has one +too. CI passes the file that GITHUB_STEP_SUMMARY names. + +.PARAMETER PassThru +Returns the Pester result object after the checks have passed. + +.EXAMPLE +./Tests/Invoke-Tests.ps1 + +Runs every suite in a new shuffled order. + +.EXAMPLE +./Tests/Invoke-Tests.ps1 -TestType Unit -ShuffleSeed 1741705376 + +Runs the unit suites in the order that seed gives, to repeat a failure. + +.EXAMPLE +./Tests/Invoke-Tests.ps1 -ExcludeTag Elevated + +Runs every suite except the tests that run as SYSTEM. + +.EXAMPLE +./Tests/Invoke-Tests.ps1 -CodeCoverage -OutputPath ./out/reports -Output Detailed + +Runs every suite with the coverage gate and writes both reports, as the tests job of CI does. + +.INPUTS +None. + +.OUTPUTS +None, or with -PassThru the Pester.Run object of the run. +#> +[CmdletBinding()] +[OutputType([object])] +param( + [Parameter()] + [ValidateSet('Unit', 'Integration', 'All')] + [string]$TestType = 'All', + + [Parameter()] + [ValidateNotNullOrEmpty()] + [string[]]$ExcludeTag, + + [Parameter()] + [switch]$CodeCoverage, + + [Parameter()] + [ValidateRange(0, 100)] + [int]$MinimumCoverage = 80, + + [Parameter()] + [ValidateRange(0, 2147483647)] + [int]$ShuffleSeed = 0, + + [Parameter()] + [ValidateNotNullOrEmpty()] + [string]$OutputPath, + + [Parameter()] + [ValidateSet('None', 'Normal', 'Detailed', 'Diagnostic')] + [string]$Output = 'Normal', + + [Parameter()] + [ValidateNotNullOrEmpty()] + [string]$SummaryPath, + + [Parameter()] + [switch]$PassThru +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$repositoryRoot = Split-Path -Path $PSScriptRoot -Parent +$validationRoot = Join-Path -Path $repositoryRoot -ChildPath 'Validation' +$validationTests = Join-Path -Path $validationRoot -ChildPath 'Tests' +$suites = @{ + Unit = @( + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit') + (Join-Path -Path $validationTests -ChildPath 'Unit') + ) + Integration = @( + (Join-Path -Path $PSScriptRoot -ChildPath 'Integration') + ) +} +$testPaths = if ($TestType -eq 'All') { $suites['Unit'] + $suites['Integration'] } else { $suites[$TestType] } + +$configuration = New-PesterConfiguration +$configuration.Run.Path = $testPaths +$configuration.Run.PassThru = $true +$configuration.Run.Shuffle = $true +$configuration.Run.ShuffleSeed = $ShuffleSeed +$configuration.Output.Verbosity = $Output +# Every test file uses the Pester 6 assertions, so the Pester 5 form can stay off +$configuration.Should.DisableV5 = $true +if ($ExcludeTag) { + $configuration.Filter.ExcludeTag = $ExcludeTag +} + +$reportFolder = $null +if ($OutputPath) { + $reportFolder = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($OutputPath) + $null = New-Item -Path $reportFolder -ItemType Directory -Force + $configuration.TestResult.Enabled = $true + $configuration.TestResult.OutputPath = Join-Path -Path $reportFolder -ChildPath 'testResults.xml' +} + +if ($CodeCoverage) { + $privateFolder = Join-Path -Path $repositoryRoot -ChildPath 'Private' + $coverageFolders = @( + (Join-Path -Path $repositoryRoot -ChildPath 'Public') + $privateFolder + (Join-Path -Path $privateFolder -ChildPath 'Rules') + ) + # Every entry must exist: Pester reports 0 percent, and still passes, for a path that matches + # nothing + $coveragePaths = foreach ($coverageFolder in $coverageFolders) { + if (-not (Test-Path -LiteralPath $coverageFolder -PathType Container)) { + throw "The coverage folder '$coverageFolder' does not exist." + } + Join-Path -Path $coverageFolder -ChildPath '*.ps1' + } + $configuration.CodeCoverage.Enabled = $true + $configuration.CodeCoverage.Path = $coveragePaths + # CoveragePercentTarget only sets the figure Pester reports against; the check below enforces it + $configuration.CodeCoverage.CoveragePercentTarget = $MinimumCoverage + if ($null -ne $reportFolder) { + $configuration.CodeCoverage.OutputPath = Join-Path -Path $reportFolder -ChildPath 'coverage.xml' + } else { + $coverageFile = "IntuneScriptLab-coverage-$([guid]::NewGuid().ToString('N')).xml" + $temporaryFolder = [System.IO.Path]::GetTempPath() + $configuration.CodeCoverage.OutputPath = Join-Path -Path $temporaryFolder -ChildPath $coverageFile + } +} + +# Pester runs the test files in scopes below this one, so they would inherit this script's strict +# mode, and when the script is started with -File this scope is the global one, which the +# module's functions see as well. The suites, the validation kit and the module are not yet +# written for strict mode (#63, #70, #71), so it is off for the run and on again after it. +Set-StrictMode -Off +try { + $result = Invoke-Pester -Configuration $configuration +} finally { + Set-StrictMode -Version Latest +} + +if ($null -eq $result) { + throw "Pester returned no result for '$TestType': it found no test files." +} + +$seed = $result.Configuration.Run.ShuffleSeed.Value +$counts = "passed $($result.PassedCount), failed $($result.FailedCount), skipped $($result.SkippedCount)" +$summary = "Pester: $counts. Shuffle seed $seed." +$coverage = $null +if ($CodeCoverage) { + $coverage = [math]::Round($result.CodeCoverage.CoveragePercent, 2) + $summary = "$summary Code coverage $coverage percent." +} +Write-Information -InformationAction Continue -MessageData $summary + +if ($SummaryPath) { + # Written before the checks below, so that a run which fails them still leaves its summary + $summaryFile = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($SummaryPath) + $architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture + $heading = "## Pester, $TestType tests, PowerShell $($PSVersionTable.PSVersion) on $architecture" + $markdown = "$heading`n`n$summary`n`n" + [System.IO.File]::AppendAllText($summaryFile, $markdown, [System.Text.UTF8Encoding]::new($false)) +} + +if ($result.Result -ne 'Passed') { + $failures = "Failed tests: $($result.FailedCount). Failed blocks: $($result.FailedBlocksCount)." + $failures = "$failures Failed files: $($result.FailedContainersCount)." + throw "Pester result is '$($result.Result)'. $failures Run the same order with -ShuffleSeed $seed." +} + +# TotalCount also counts the tests that a filter left out and the tests that were skipped, and +# Pester's result for a run of only those is Passed. The tests that ran are counted instead: a +# run that executed nothing has proved nothing. +$ranCount = $result.PassedCount + $result.FailedCount +if ($ranCount -eq 0) { + $found = "$($result.TotalCount) found, $($result.SkippedCount) skipped" + throw "Pester ran no tests for '$TestType': $found, $($result.NotRunCount) left out by a filter." +} + +if ($CodeCoverage -and $coverage -lt $MinimumCoverage) { + $missedByFile = @($result.CodeCoverage.CommandsMissed | + Group-Object -Property File | + Sort-Object -Property Name) + foreach ($file in $missedByFile) { + $line = " $($file.Name): $($file.Count) uncovered command(s)" + Write-Information -InformationAction Continue -MessageData $line + } + throw "Code coverage is $coverage percent. The minimum is $MinimumCoverage." +} + +if ($PassThru) { + $result +} diff --git a/Tests/Unit/Build/Invoke-Tests.Tests.ps1 b/Tests/Unit/Build/Invoke-Tests.Tests.ps1 new file mode 100644 index 0000000..2c683fc --- /dev/null +++ b/Tests/Unit/Build/Invoke-Tests.Tests.ps1 @@ -0,0 +1,44 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The runner's own gate: a run that executed nothing must fail. Pester's result for a run in which + a filter left every test out is Passed, and its TotalCount still counts those tests, so the + runner counts the tests that passed or failed. The runner is started in a new process with a + filter that leaves out every unit test, this file's included. +#> + +BeforeDiscovery { + # The run started below discovers this file too. Its tag leaves the test out there; this is + # the second guard, so that a change of tags cannot make the runner start itself without end + $script:InsideRunner = [bool]$env:ISL_RUNNER_SELF_TEST +} + +BeforeAll { + $repositoryRoot = Split-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -Parent + $testsFolder = Join-Path -Path $repositoryRoot -ChildPath 'Tests' + $script:runner = Join-Path -Path $testsFolder -ChildPath 'Invoke-Tests.ps1' + $script:shell = (Get-Process -Id $PID).Path +} + +Describe 'Invoke-Tests.ps1' -Tag 'Unit', 'Build' { + + Context 'Error Handling' { + It 'fails when a filter leaves every test out' -Skip:$script:InsideRunner { + # The child reports on its output: its error stream, read under an error preference + # of Stop, which a CI step sets, would end this test instead + $run = "& '$script:runner' -TestType Unit -ExcludeTag Unit -Output None 6>`$null" + $command = "try { $run; 'passed' } catch { 'failed: ' + `$_.Exception.Message; exit 1 }" + $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', $command) + $env:ISL_RUNNER_SELF_TEST = '1' + try { + $output = & $script:shell @arguments + $exitCode = $LASTEXITCODE + } finally { + Remove-Item -Path Env:ISL_RUNNER_SELF_TEST + } + + "$output" | Should-BeLikeString 'failed: Pester ran no tests for*left out by a filter.' + $exitCode | Should-Be 1 + } + } +}