diff --git a/.github/workflows/quality-gates.yml b/.github/workflows/quality-gates.yml index ac511db..886cbfb 100644 --- a/.github/workflows/quality-gates.yml +++ b/.github/workflows/quality-gates.yml @@ -33,7 +33,8 @@ # arm64 Windows on ARM. The runtime harness picks a PowerShell host per architecture, and # on an ARM64 device the answers differ from x64: the System32 host is native ARM64, # the SysWOW64 host is emulated x86, and there is no x64 host at all. The x64 runner -# cannot exercise those branches, so the unit suites run again on GitHub's ARM64 image. +# cannot exercise those branches, so the unit suites run again on GitHub's ARM64 image, +# with the tests of the unit folders that start processes in a second run. # # help Ubuntu. The command help gate: the PlatyPS Markdown under docs/ is valid and # complete, the committed MAML in en-US/ was built from it, the generated rule @@ -222,6 +223,9 @@ jobs: run: | $ErrorActionPreference = 'Stop' ./Tests/Invoke-Tests.ps1 -TestType Unit -OutputPath ./reports -SummaryPath $env:GITHUB_STEP_SUMMARY + # The tests of the unit folders that start processes: the arm64 host and the x86 one that + # Windows on ARM emulates are what they cover here + ./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Integration -OutputPath ./reports/process -SummaryPath $env:GITHUB_STEP_SUMMARY - name: Upload test results if: always() diff --git a/Build/Invoke-Build.ps1 b/Build/Invoke-Build.ps1 index 15b3668..c71eaa4 100644 --- a/Build/Invoke-Build.ps1 +++ b/Build/Invoke-Build.ps1 @@ -13,9 +13,9 @@ 3. Build/Test-MarkdownLink.ps1: the anchors and relative links of the Markdown. 4. Build/Invoke-Analysis.ps1: PSScriptAnalyzer with the repository's settings, in a new process. - 5. Tests/Invoke-Tests.ps1 with -TestType in this host. - 6. Tests/Invoke-Tests.ps1 -TestType Unit under Windows PowerShell 5.1, on Windows, unless - -SkipWindowsPowerShell. + 5. Tests/Invoke-Tests.ps1 with -TestType in this host. With Unit, the default, the tests of the + unit folders tagged Integration, which start processes, run after the unit tests. + 6. The same under Windows PowerShell 5.1, on Windows, unless -SkipWindowsPowerShell. Steps 1 and 2 rewrite en-US/IntuneScriptLab-Help.xml and docs/Rules.md. A change to either belongs in the same commit as its cause. The script ends with the list of the two files whose @@ -172,16 +172,28 @@ if ($LASTEXITCODE -ne 0) { } if (-not $SkipTests) { - Write-BuildStep -Text "Tests ($TestType) in PowerShell $($PSVersionTable.PSVersion)" - & $runner -TestType $TestType + # The unit run leaves out the tests of the unit folders that start processes (TST-47); the + # build runs them after it, so it checks what it checked before they were tagged + $runs = @(@{ TestType = $TestType }) + if ($TestType -eq 'Unit') { + $runs += @{ TestType = 'Unit'; Tag = 'Integration' } + } + foreach ($run in $runs) { + Write-BuildStep -Text "Tests ($($run.TestType) $($run['Tag'])) in PowerShell $($PSVersionTable.PSVersion)" + & $runner @run + } $onWindows = $PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows $inDesktop = $PSVersionTable.PSEdition -eq 'Desktop' if ($onWindows -and -not $inDesktop -and -not $SkipWindowsPowerShell) { - Write-BuildStep -Text 'Unit tests under Windows PowerShell 5.1' - & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $runner -TestType Unit - if ($LASTEXITCODE -ne 0) { - throw "The unit tests failed under Windows PowerShell 5.1 (exit code $LASTEXITCODE)." + $desktopRuns = @(, @('-TestType', 'Unit')) + @(, @('-TestType', 'Unit', '-Tag', 'Integration')) + foreach ($desktopArguments in $desktopRuns) { + $described = @($desktopArguments | Select-Object -Skip 1) -join ' ' + Write-BuildStep -Text "Tests ($described) under Windows PowerShell 5.1" + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $runner @desktopArguments + if ($LASTEXITCODE -ne 0) { + throw "The tests failed under Windows PowerShell 5.1 (exit code $LASTEXITCODE)." + } } } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 41187f0..e2624b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,10 @@ entries are carried over from the manifest's release notes. ### Changed +- A test that starts a process, reads the real machine or runs a script as a caller would is + tagged `Integration`, and `Tests/Invoke-Tests.ps1 -TestType Unit` leaves it out: the unit run + takes 69 seconds instead of 157 on a Windows 11 laptop. `-TestType Integration` runs those tests + with the integration suites, and the build and the ARM job run them in a run of their own (#70). - The test suites run under strict mode, as the module does: `Tests/Invoke-Tests.ps1` no longer turns it off around the Pester run (ERR-03, #70). - `SECURITY.md` classifies the data the module handles and lists the threats to it by STRIDE diff --git a/CLAUDE.md b/CLAUDE.md index 49ff6b6..b1633c1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -164,6 +164,12 @@ 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`. +A test that starts a process, reads the real machine (CIM, the registry of the host, a logon +session) or runs a script as a caller would, through `Invoke-CallerScript`, is tagged +`Integration`, wherever its file is. `-TestType Unit` leaves those out, so that the unit run stays +within seconds (TST-47); `-TestType Integration` runs them with `Tests/Integration`, and the build, +the 5.1 job and the ARM job run them too. A unit test mocks the clock rather than waiting on it. + `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. @@ -256,12 +262,13 @@ vault is searched, and the secret stays a `SecureString` until the publish call. ## Checks ```powershell -./Build/Invoke-Build.ps1 # all of it in order: help, rule reference, links, analysis, unit suites on 7 and 5.1 +./Build/Invoke-Build.ps1 # all of it in order: help, rule reference, links, analysis, unit and process tests on 7 and 5.1 ./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 ./Tests/Invoke-Tests.ps1 -TestType Performance # the log readers on a generated log, not part of the default run ./Build/Test-PerformanceBaseline.ps1 -ResultPath -Record # baselines from ISL_PERFORMANCE_RESULTS, see the tests job ./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Security # where a -Credential password goes, and the checks on input +./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Integration # the tests of the unit folders that start processes ./Build/Invoke-Analysis.ps1 # PSScriptAnalyzer with the settings file, as the tests job runs it ./Build/Build-Help.ps1 -SkipUpdate # rebuild MAML after editing docs/, the form CI compares ./Build/Build-RuleReference.ps1 # rebuild docs/Rules.md after changing a rule @@ -281,10 +288,13 @@ module's `Should-*` aliases and reports every Pester assertion as an alias. `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: +and the tagged tests of the unit folders under Windows PowerShell 5.1 as well before pushing, or +`./Build/Invoke-Build.ps1`, which runs both in both hosts. The second run holds the 5.1 checks that +matter most: the child imports, the module loading under 5.1, the host comparisons: ```powershell powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit +powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Integration ``` The script sets strict mode, and the suites and the validation kit run under it, as the module diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cf64025..7c02010 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -45,6 +45,7 @@ Everything specific to this module is in `CLAUDE.md`. The ones most often trippe # a lab account or PSScriptAnalyzer skip themselves ./Tests/Invoke-Tests.ps1 -TestType Performance # the log readers on a generated log, with the limits CI holds ./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Security # where a -Credential password goes, and the checks on input +./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Integration # the tests of the unit folders that start processes ./Build/Invoke-Analysis.ps1 # PSScriptAnalyzer, as CI runs it ./Build/Build-Help.ps1 -SkipUpdate # after editing docs/ ./Build/Build-RuleReference.ps1 # after changing a rule @@ -58,10 +59,12 @@ file out that way. `Invoke-Analysis.ps1` checks `Validation/Probe.ps1`, `Validation/Win32Install.ps1` and `Validation/Fixtures.ps1` with the default rules only: they keep the layout they ran with in the experiments. -`Invoke-Build.ps1` also runs the unit suites under Windows PowerShell 5.1. To run them by hand: +`Invoke-Build.ps1` also runs the unit suites, and the tests of the unit folders that start +processes, under Windows PowerShell 5.1. To run them by hand: ```powershell powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit +powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Integration ``` A failure message of `Invoke-Tests.ps1` carries the shuffle seed; `-ShuffleSeed ` runs the diff --git a/Tests/Invoke-Tests.ps1 b/Tests/Invoke-Tests.ps1 index 2331460..9ca4196 100644 --- a/Tests/Invoke-Tests.ps1 +++ b/Tests/Invoke-Tests.ps1 @@ -19,14 +19,20 @@ script needs neither elevation nor a tenant. It runs on PowerShell 7 and on Wind 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. Performance is Tests/Performance, which measures the log readers on a generated log; it -is not part of All, and its files keep their declared order (#pester:no-shuffle). +Which tests to run. A test that starts a process, reads the real machine or runs a script as a +caller would is tagged Integration, wherever its file is; the rest is a unit test. + +Unit is the tests of Tests/Unit and Validation/Tests/Unit without the Integration tag, the ones +that run in seconds (TST-47). Integration is every test tagged Integration: the suites of +Tests/Integration and the tagged tests of the unit folders; with -Tag, only the tests of +Tests/Integration that have one of those tags. All, the default, is both. +Performance is Tests/Performance, which measures the log readers on a generated log; it is not +part of All, and its files keep their declared order (#pester:no-shuffle). .PARAMETER Tag Tags of the tests to run, for example Security for the tests of credential handling and input -validation. Left out, every test of the suites runs. +validation. Left out, every test of the suites runs. With -TestType Unit, -Tag Integration runs +the tagged tests of the unit folders, which the unit run otherwise leaves out. .PARAMETER ExcludeTag Tags of tests to leave out, for example Elevated for the tests that run as SYSTEM. Those tests @@ -67,6 +73,11 @@ Runs every suite in a new shuffled order. Runs the unit suites in the order that seed gives, to repeat a failure. +.EXAMPLE +./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Integration + +Runs the tests of the unit folders that start processes, which the unit run leaves out. + .EXAMPLE ./Tests/Invoke-Tests.ps1 -TestType Unit -Tag Security @@ -153,7 +164,26 @@ $suites = @{ (Join-Path -Path $PSScriptRoot -ChildPath 'Performance') ) } -$testPaths = if ($TestType -eq 'All') { $suites['Unit'] + $suites['Integration'] } else { $suites[$TestType] } +# The Integration tag decides what is a unit test, not the folder: a test in Tests/Unit that starts +# a process belongs to the integration run +$includeTags = @($Tag | Where-Object { $_ }) +$testPaths = switch ($TestType) { + 'All' { $suites['Unit'] + $suites['Integration'] } + # Pester's tag filter takes a test with any one of the tags, so with tags of the caller's own + # the unit folders would bring their tests with those tags too: the run keeps to + # Tests/Integration then, as it did before the tag decided + 'Integration' { + if ($includeTags.Count -eq 0) { $suites['Unit'] + $suites['Integration'] } else { $suites['Integration'] } + } + default { $suites[$TestType] } +} +$excludeTags = @($ExcludeTag | Where-Object { $_ }) +if ($TestType -eq 'Unit' -and $includeTags -notcontains 'Integration') { + $excludeTags += 'Integration' +} +if ($TestType -eq 'Integration' -and $includeTags.Count -eq 0) { + $includeTags = @('Integration') +} $configuration = New-PesterConfiguration $configuration.Run.Path = $testPaths @@ -163,11 +193,11 @@ $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 ($Tag) { - $configuration.Filter.Tag = $Tag +if ($includeTags.Count -gt 0) { + $configuration.Filter.Tag = $includeTags } -if ($ExcludeTag) { - $configuration.Filter.ExcludeTag = $ExcludeTag +if ($excludeTags.Count -gt 0) { + $configuration.Filter.ExcludeTag = $excludeTags } $reportFolder = $null @@ -235,7 +265,9 @@ 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" + # The tags tell two runs of one type apart, such as the unit run and the run of its tagged tests + $tagged = if ($Tag) { " tagged $($Tag -join ', ')" } else { '' } + $heading = "## Pester, $TestType tests$tagged, PowerShell $($PSVersionTable.PSVersion) on $architecture" $markdown = "$heading`n`n$summary`n`n" [System.IO.File]::AppendAllText($summaryFile, $markdown, [System.Text.UTF8Encoding]::new($false)) } diff --git a/Tests/Unit/Build/Invoke-Tests.Tests.ps1 b/Tests/Unit/Build/Invoke-Tests.Tests.ps1 index 2c683fc..ebea8ba 100644 --- a/Tests/Unit/Build/Invoke-Tests.Tests.ps1 +++ b/Tests/Unit/Build/Invoke-Tests.Tests.ps1 @@ -5,6 +5,10 @@ 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. + + And what each test type selects, on a repository of its own: a copy of the runner, a module that + is only a manifest, and one fixture file in Tests/Unit and one in Tests/Integration, with a + test of each kind. The Integration tag, not the folder, decides what the unit run leaves out. #> BeforeDiscovery { @@ -18,9 +22,47 @@ BeforeAll { $testsFolder = Join-Path -Path $repositoryRoot -ChildPath 'Tests' $script:runner = Join-Path -Path $testsFolder -ChildPath 'Invoke-Tests.ps1' $script:shell = (Get-Process -Id $PID).Path + + # The fixture repository: the runner imports the manifest at its root and runs these suites + $script:FixtureRoot = Join-Path -Path $TestDrive -ChildPath 'repository' + $fixtureTests = Join-Path -Path $script:FixtureRoot -ChildPath 'Tests' + $fixtureValidation = Join-Path -Path $script:FixtureRoot -ChildPath 'Validation' + $fixtureValidation = Join-Path -Path $fixtureValidation -ChildPath 'Tests' + $folders = @( + (Join-Path -Path $fixtureTests -ChildPath 'Unit') + (Join-Path -Path $fixtureTests -ChildPath 'Integration') + (Join-Path -Path $fixtureValidation -ChildPath 'Unit') + ) + foreach ($folder in $folders) { + $null = New-Item -ItemType Directory -Path $folder -Force + } + Copy-Item -LiteralPath $script:runner -Destination $fixtureTests + $utf8 = [System.Text.UTF8Encoding]::new($false) + $rootModule = Join-Path -Path $script:FixtureRoot -ChildPath 'IntuneScriptLab.psm1' + [System.IO.File]::WriteAllText($rootModule, '', $utf8) + $manifest = "@{ RootModule = 'IntuneScriptLab.psm1'; ModuleVersion = '1.0.0'; FunctionsToExport = @() }" + $manifestPath = Join-Path -Path $script:FixtureRoot -ChildPath 'IntuneScriptLab.psd1' + [System.IO.File]::WriteAllText($manifestPath, $manifest, $utf8) + $unitFixture = @( + "Describe 'Fixture unit' -Tag 'Unit' {" + " It 'unit' { }" + " It 'process' -Tag 'Integration' { }" + " It 'unit security' -Tag 'Security' { }" + '}' + ) -join "`n" + $unitFile = Join-Path -Path $folders[0] -ChildPath 'Fixture.Tests.ps1' + [System.IO.File]::WriteAllText($unitFile, $unitFixture, $utf8) + $integrationFixture = @( + "Describe 'Fixture integration' -Tag 'Integration' {" + " It 'integration' { }" + " It 'integration security' -Tag 'Security' { }" + '}' + ) -join "`n" + $integrationFile = Join-Path -Path $folders[1] -ChildPath 'Fixture.Tests.ps1' + [System.IO.File]::WriteAllText($integrationFile, $integrationFixture, $utf8) } -Describe 'Invoke-Tests.ps1' -Tag 'Unit', 'Build' { +Describe 'Invoke-Tests.ps1' -Tag 'Integration', 'Build' { Context 'Error Handling' { It 'fails when a filter leaves every test out' -Skip:$script:InsideRunner { @@ -41,4 +83,29 @@ Describe 'Invoke-Tests.ps1' -Tag 'Unit', 'Build' { $exitCode | Should-Be 1 } } + + Context 'What each test type runs' { + It '-TestType runs ' -Skip:$script:InsideRunner -ForEach @( + @{ TestType = 'Unit'; Arguments = ''; Expected = 'unit, unit security' } + @{ TestType = 'Unit'; Arguments = '-Tag Integration'; Expected = 'process' } + @{ TestType = 'Unit'; Arguments = '-Tag Security'; Expected = 'unit security' } + @{ TestType = 'Integration'; Arguments = ''; Expected = 'integration, integration security, process' } + @{ TestType = 'Integration'; Arguments = '-Tag Security'; Expected = 'integration security' } + @{ + TestType = 'All'; Arguments = '' + Expected = 'integration, integration security, process, unit, unit security' + } + ) { + $fixtureTests = Join-Path -Path $script:FixtureRoot -ChildPath 'Tests' + $fixtureRunner = Join-Path -Path $fixtureTests -ChildPath 'Invoke-Tests.ps1' + $run = "& '$fixtureRunner' -TestType $TestType $Arguments -Output None -PassThru 6>`$null" + $names = "($run).Tests | Where-Object { `$_.Result -eq 'Passed' } | ForEach-Object { `$_.Name }" + $command = "(@($names) | Sort-Object) -join ', '" + $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', $command) + $output = & $script:shell @arguments + + "$output" | Should-Be $Expected + $LASTEXITCODE | Should-Be 0 + } + } } diff --git a/Tests/Unit/Module.Contract.Tests.ps1 b/Tests/Unit/Module.Contract.Tests.ps1 index 8130be9..6c6580c 100644 --- a/Tests/Unit/Module.Contract.Tests.ps1 +++ b/Tests/Unit/Module.Contract.Tests.ps1 @@ -195,7 +195,7 @@ Describe 'IntuneScriptLab module contract' -Tag 'Unit', 'Contract' { Should-Throw -ExceptionMessage '*neverAssignedAnywhere*' } - Context 'When a part of the module cannot be loaded' { + Context 'When a part of the module cannot be loaded' -Tag 'Integration' { BeforeAll { # Each copy is imported in a new process: a second module of this name imported here # would stand beside the one under test for the rest of the run @@ -317,7 +317,7 @@ Describe 'IntuneScriptLab module contract' -Tag 'Unit', 'Contract' { } } - It 'loads on Windows PowerShell 5.1 as well as PowerShell 7' { + It 'loads on Windows PowerShell 5.1 as well as PowerShell 7' -Tag 'Integration' { # The rules reference PowerShell 7 AST types by name only; a hard type reference would # break import on 5.1, which is where many admins will run this. $manifest = Test-ModuleManifest -Path $script:ManifestPath diff --git a/Tests/Unit/Module.WhatIf.Tests.ps1 b/Tests/Unit/Module.WhatIf.Tests.ps1 index 74bb710..afe6a1d 100644 --- a/Tests/Unit/Module.WhatIf.Tests.ps1 +++ b/Tests/Unit/Module.WhatIf.Tests.ps1 @@ -66,7 +66,7 @@ BeforeAll { Describe 'What -WhatIf does across the module' -Tag 'Unit', 'Contract' { Context 'The fixture' { - It 'leaves its marker when the script does run' { + It 'leaves its marker when the script does run' -Tag 'Integration' { $probe = New-MarkerScript -Name 'Sanity' $result = Invoke-IntuneDetectionTest -Path $probe.Script -TimeoutSeconds 60 @@ -164,7 +164,7 @@ Describe 'What -WhatIf does across the module' -Tag 'Unit', 'Contract' { } Context 'A WhatIf preference in the caller''s session' { - It 'previews the run as -WhatIf does, and does not start the host on a missing copy' { + It 'previews the run as -WhatIf does, and does not start the host on a missing copy' -Tag 'Integration' { $probe = New-MarkerScript -Name 'Preference' $run = Invoke-CallerScript -Statement @( "`$WhatIfPreference = `$true" @@ -217,8 +217,15 @@ Describe 'What -WhatIf does across the module' -Tag 'Unit', 'Contract' { }) $commandType = [System.Management.Automation.Language.CommandAst] # Whether a command has -WhatIf, looked up once for each name: the trees hold thousands - # of calls to a few hundred commands, and Get-Command for each call took most of a minute + # of calls to a few hundred commands, and Get-Command for each call took most of a minute. + # The module's own functions are read from inside it: from here Get-Command cannot see a + # private one, and looking for it searched every module on the path, 9 of the test's 10 + # seconds $hasWhatIf = @{} + $moduleCommands = InModuleScope IntuneScriptLab { Get-Command -Module IntuneScriptLab -All } + foreach ($moduleCommand in $moduleCommands) { + $hasWhatIf[$moduleCommand.Name] = $moduleCommand.Parameters.ContainsKey('WhatIf') + } $calls = foreach ($tree in $trees) { foreach ($command in $tree.FindAll({ param($node) $node -is $commandType }, $true)) { $name = $command.GetCommandName() @@ -254,7 +261,7 @@ Describe 'What -WhatIf does across the module' -Tag 'Unit', 'Contract' { @($calls | Where-Object { -not $_.Pinned } | ForEach-Object { $_.Call }) | Should-BeCollection @() } - It 'does not ask again inside a run the caller agreed to, in a session that cannot answer' { + It 'does not ask again in a run the caller agreed to, in a session that cannot answer' -Tag 'Integration' { # After a Yes to -Confirm the preference is still Low in the command's scope, and the # functions it calls see it. With only -WhatIf pinned, the run folder and the copy each # asked again; here, where nobody can answer, they failed, and the host was started on @@ -278,7 +285,7 @@ Describe 'What -WhatIf does across the module' -Tag 'Unit', 'Contract' { @($run.ErrorId | Where-Object { $_ -like '*ItemCommand' }) | Should-BeCollection @() } - It 'runs when the caller declines to be asked, whatever its confirm preference' { + It 'runs when the caller declines to be asked, whatever its confirm preference' -Tag 'Integration' { $probe = New-MarkerScript -Name 'ConfirmFalse' $run = Invoke-CallerScript -Statement @( "`$ConfirmPreference = 'Low'" diff --git a/Tests/Unit/Private/Get-IslCoreOnlyFeature.Tests.ps1 b/Tests/Unit/Private/Get-IslCoreOnlyFeature.Tests.ps1 index 472c36e..5d9705d 100644 --- a/Tests/Unit/Private/Get-IslCoreOnlyFeature.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslCoreOnlyFeature.Tests.ps1 @@ -68,7 +68,7 @@ BeforeAll { } $json = $flat | ConvertTo-Json -Depth 5 -Compress $command = "& { $($probe.ToString()) } '$($json.Replace("'", "''"))'" - $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) + $script:Encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) function script:Get-HostAnswer { <# .SYNOPSIS @@ -86,7 +86,7 @@ BeforeAll { The command to run, Base64 encoded from UTF-16 LE text as -EncodedCommand expects. .EXAMPLE - Get-HostAnswer 'pwsh.exe' $encoded + Get-HostAnswer 'pwsh.exe' $script:Encoded Runs the probe in PowerShell 7 and returns its answer. @@ -110,10 +110,6 @@ BeforeAll { # Discovery-time variables do not reach the run, so the lookup is repeated here $script:BothHosts = [bool](Get-Command powershell.exe -ErrorAction SilentlyContinue) -and [bool](Get-Command pwsh.exe -ErrorAction SilentlyContinue) - if ($script:BothHosts) { - $script:Desktop = Get-HostAnswer 'powershell.exe' $encoded - $script:Core = Get-HostAnswer 'pwsh.exe' $encoded - } } Describe 'Get-IslCoreOnlyFeature' -Tag 'Unit', 'Private' { @@ -125,7 +121,13 @@ Describe 'Get-IslCoreOnlyFeature' -Tag 'Unit', 'Private' { $script:Table.Values['Out-File'].Encoding | Should-ContainCollection 'utf8NoBOM' } - Context 'Against both hosts' -Skip:(-not $script:BothHosts) { + # Both hosts of this machine, started and asked: an integration test, and its setup with it + Context 'Against both hosts' -Tag 'Integration' -Skip:(-not $script:BothHosts) { + BeforeAll { + $script:Desktop = Get-HostAnswer 'powershell.exe' $script:Encoded + $script:Core = Get-HostAnswer 'pwsh.exe' $script:Encoded + } + It 'every listed command is missing from Windows PowerShell 5.1 and present in PowerShell 7' { $wrong = @(foreach ($name in $script:Table.Commands) { if ($script:Desktop.Commands.$name) { "$name exists in 5.1" } diff --git a/Tests/Unit/Private/Get-IslDeviceFact.Tests.ps1 b/Tests/Unit/Private/Get-IslDeviceFact.Tests.ps1 index a4c6f57..f26f21a 100644 --- a/Tests/Unit/Private/Get-IslDeviceFact.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslDeviceFact.Tests.ps1 @@ -16,7 +16,7 @@ BeforeAll { $script:Fact = InModuleScope IntuneScriptLab { Get-IslDeviceFact } } -Describe 'Get-IslDeviceFact' -Tag 'Unit', 'Private' { +Describe 'Get-IslDeviceFact' -Tag 'Integration', 'Private' { It 'names the architecture the way the requirements do' { @('x86', 'x64', 'arm64') | Should-ContainCollection $script:Fact.Architecture diff --git a/Tests/Unit/Private/Get-IslFilterDeviceFact.Tests.ps1 b/Tests/Unit/Private/Get-IslFilterDeviceFact.Tests.ps1 index a59143b..4769f8e 100644 --- a/Tests/Unit/Private/Get-IslFilterDeviceFact.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslFilterDeviceFact.Tests.ps1 @@ -60,7 +60,7 @@ BeforeAll { Describe 'Get-IslFilterDeviceFact' -Tag 'Unit', 'Private' -Skip:(-not $script:OnWindows) { - It 'reports every filter property, with the tenant-side ones empty' { + It 'reports every filter property, with the tenant-side ones empty' -Tag 'Integration' { $fact = InModuleScope IntuneScriptLab { Get-IslFilterDeviceFact } $expected = @('deviceName', 'manufacturer', 'model', 'osVersion', 'operatingSystemVersion', 'operatingSystemSKU', 'cpuArchitecture', 'deviceTrustType', 'deviceOwnership', @@ -72,18 +72,18 @@ Describe 'Get-IslFilterDeviceFact' -Tag 'Unit', 'Private' -Skip:(-not $script:On $fact.isTpmAttested | Should-BeNull } - It 'names the architecture the way the filter does (amd64, not x64)' { + It 'names the architecture the way the filter does (amd64, not x64)' -Tag 'Integration' { $fact = InModuleScope IntuneScriptLab { Get-IslFilterDeviceFact } @('amd64', 'x86', 'arm64') | Should-ContainCollection $fact.cpuArchitecture } - It 'reads a four-part version with the update build revision, the same for both version properties' { + It 'reads a four-part version with the update build revision for both properties' -Tag 'Integration' { $fact = InModuleScope IntuneScriptLab { Get-IslFilterDeviceFact } $fact.osVersion | Should-MatchString '^10\.0\.\d+\.\d+$' $fact.operatingSystemVersion | Should-Be $fact.osVersion } - It 'names the SKU from the filter reference table, or keeps the number where the table has no name' { + It 'names the SKU from the filter reference table, or keeps a number it has no name for' -Tag 'Integration' { $fact = InModuleScope IntuneScriptLab { Get-IslFilterDeviceFact } $fact.operatingSystemSKU | Should-NotBeWhiteSpaceString $operatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem diff --git a/Tests/Unit/Private/Get-IslInboxModule.Tests.ps1 b/Tests/Unit/Private/Get-IslInboxModule.Tests.ps1 index 97c46ed..aada904 100644 --- a/Tests/Unit/Private/Get-IslInboxModule.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslInboxModule.Tests.ps1 @@ -46,38 +46,6 @@ BeforeAll { # On a build after the table's 24H2: a Windows Insider Beta-channel build of 26H2 (26320) has it, # and 24H2 devices at build 26100.9974 with current updates do not (Validation/Findings.md) $script:LaterReleaseModules = 'UOPProviders' - - # Discovery-time variables do not reach the run, so the lookup is repeated here - $script:ClientHost = $false - if (Get-Command powershell.exe -ErrorAction SilentlyContinue) { - $os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue - $script:ClientHost = [int]$os.ProductType -eq 1 - } - if ($script:ClientHost) { - # What the host's Windows PowerShell has under the two system module paths, the ones a - # SYSTEM session under the agent reads (REM-PSMODULEPATH), kept apart: System32 is Windows' - # own, Program Files is where installed software and the Gallery's AllUsers scope land - $probe = { - $windows = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\Modules" - $programs = "$env:ProgramFiles\WindowsPowerShell\Modules" - $available = Get-Module -ListAvailable - $under = { - param($Root) - @($available | Where-Object { $_.ModuleBase.StartsWith($Root, 'OrdinalIgnoreCase') } | - Select-Object -ExpandProperty Name -Unique | Sort-Object -Unique) - } - # The engine module has no folder and Import-Module of it fails; its commands are there - $engine = (Get-Command -Name Get-Command).ModuleName - @{ Windows = & $under $windows; Programs = & $under $programs; Engine = $engine } | - ConvertTo-Json -Compress - } - $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($probe.ToString())) - $raw = & powershell.exe -NoProfile -NonInteractive -EncodedCommand $encoded 2>&1 - $answer = ($raw | Where-Object { "$_".StartsWith('{') } | Select-Object -Last 1) | ConvertFrom-Json - $script:WindowsModules = @($answer.Windows) - $script:HostModules = @($answer.Windows) + @($answer.Programs) - $script:HostEngineModule = "$($answer.Engine)" - } } Describe 'Get-IslInboxModule' -Tag 'Unit', 'Private' { @@ -96,7 +64,42 @@ Describe 'Get-IslInboxModule' -Tag 'Unit', 'Private' { ($returned -join ',') | Should-Be ($script:Table -join ',') } - Context 'Against this Windows client' -Skip:(-not $script:ClientHost) { + # A Windows PowerShell host of this machine, asked what it has: an integration test + Context 'Against this Windows client' -Tag 'Integration' -Skip:(-not $script:ClientHost) { + BeforeAll { + # Discovery-time variables do not reach the run, so the lookup is repeated here + $script:ClientHost = $false + if (Get-Command powershell.exe -ErrorAction SilentlyContinue) { + $os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue + $script:ClientHost = [int]$os.ProductType -eq 1 + } + if ($script:ClientHost) { + # What the host's Windows PowerShell has under the two system module paths, the ones a + # SYSTEM session under the agent reads (REM-PSMODULEPATH), kept apart: System32 is Windows' + # own, Program Files is where installed software and the Gallery's AllUsers scope land + $probe = { + $windows = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\Modules" + $programs = "$env:ProgramFiles\WindowsPowerShell\Modules" + $available = Get-Module -ListAvailable + $under = { + param($Root) + @($available | Where-Object { $_.ModuleBase.StartsWith($Root, 'OrdinalIgnoreCase') } | + Select-Object -ExpandProperty Name -Unique | Sort-Object -Unique) + } + # The engine module has no folder and Import-Module of it fails; its commands are there + $engine = (Get-Command -Name Get-Command).ModuleName + @{ Windows = & $under $windows; Programs = & $under $programs; Engine = $engine } | + ConvertTo-Json -Compress + } + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($probe.ToString())) + $raw = & powershell.exe -NoProfile -NonInteractive -EncodedCommand $encoded 2>&1 + $answer = ($raw | Where-Object { "$_".StartsWith('{') } | Select-Object -Last 1) | ConvertFrom-Json + $script:WindowsModules = @($answer.Windows) + $script:HostModules = @($answer.Windows) + @($answer.Programs) + $script:HostEngineModule = "$($answer.Engine)" + } + } + It 'has every listed module under the system module paths, or is a Home edition without the feature' { $script:HostModules.Count | Should-BeGreaterThan 50 $missing = @($script:Table | Where-Object { diff --git a/Tests/Unit/Private/Get-IslLogonSession.Tests.ps1 b/Tests/Unit/Private/Get-IslLogonSession.Tests.ps1 index 277d290..483bc71 100644 --- a/Tests/Unit/Private/Get-IslLogonSession.Tests.ps1 +++ b/Tests/Unit/Private/Get-IslLogonSession.Tests.ps1 @@ -147,7 +147,7 @@ Describe 'Get-IslLogonSession' -Tag 'Unit', 'Private' { @(Get-Session @()).Count | Should-Be 0 } - It 'reads the real machine without error and gives every session a SID and an id' { + It 'reads the real machine without error and gives every session a SID and an id' -Tag 'Integration' { # A CI runner has no desktop session; this machine has at least the one running the tests $real = @(InModuleScope IntuneScriptLab { Get-IslLogonSession }) foreach ($session in $real) { diff --git a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 index baed83b..e5c5303 100644 --- a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 @@ -53,7 +53,8 @@ BeforeAll { Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { - Context 'Current user' { + # Child processes for real: the module's own launch, a timeout, a process tree + Context 'Current user' -Tag 'Integration' { It 'captures the exit code, stdout and stderr of a child process' { $result = Invoke-Process @{ FilePath = $script:Cmd; Arguments = '/C echo out& echo err 1>&2& exit 3' @@ -165,6 +166,16 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { Context 'System' { BeforeEach { + # A clock of the test's own (TST-31): the task loop polls every 250 ms and gives up on a + # task that never starts after 5 seconds, which on the real clock made each test here + # wait that long. Start-Sleep moves the clock on instead of waiting + $script:Clock = [datetime]'2026-01-01T00:00:00' + Mock Get-Date -ModuleName IntuneScriptLab { $script:Clock } + Mock Start-Sleep -ModuleName IntuneScriptLab { + $milliseconds = [int]$PesterBoundParameters['Milliseconds'] + $seconds = [int]$PesterBoundParameters['Seconds'] + $script:Clock = $script:Clock.AddMilliseconds($milliseconds).AddSeconds($seconds) + } # The work folder's leaf is the run id the task name carries, so the fake task can find # the folder from the name alone, as the mocks see only their own parameters $script:WorkFolder = Join-Path ([IO.Path]::GetTempPath()) "IslTest-$([guid]::NewGuid().ToString('N'))" @@ -261,6 +272,16 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { Context 'Another account' { BeforeEach { + # A clock of the test's own (TST-31): the task loop polls every 250 ms and gives up on a + # task that never starts after 5 seconds, which on the real clock made each test here + # wait that long. Start-Sleep moves the clock on instead of waiting + $script:Clock = [datetime]'2026-01-01T00:00:00' + Mock Get-Date -ModuleName IntuneScriptLab { $script:Clock } + Mock Start-Sleep -ModuleName IntuneScriptLab { + $milliseconds = [int]$PesterBoundParameters['Milliseconds'] + $seconds = [int]$PesterBoundParameters['Seconds'] + $script:Clock = $script:Clock.AddMilliseconds($milliseconds).AddSeconds($seconds) + } $script:WorkFolder = Join-Path ([IO.Path]::GetTempPath()) "IslTest-$([guid]::NewGuid().ToString('N'))" $null = New-Item -ItemType Directory -Path $script:WorkFolder -Force Mock Register-ScheduledTask -ModuleName IntuneScriptLab { } @@ -426,9 +447,9 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { Mock Get-ScheduledTaskInfo -ModuleName IntuneScriptLab { [pscustomobject]@{ LastTaskResult = 2147943785 } } - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() $failure = { Invoke-Process $script:LaunchSplat } | Should-Throw - $stopwatch.Elapsed.TotalSeconds | Should-BeLessThan 10 + # By the module's clock: it read the refusal, not the 30-second timeout of the run + ($script:Clock - [datetime]'2026-01-01T00:00:00').TotalSeconds | Should-BeLessThan 10 $failure.Exception.Message | Should-BeLikeString '*LAB\isl-user did not start: 0x80070569*Log on as a batch job*' $failure.FullyQualifiedErrorId | Should-BeLikeString 'ScheduledTaskNotStarted,*' @@ -442,9 +463,12 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { Mock Get-ScheduledTaskInfo -ModuleName IntuneScriptLab { [pscustomobject]@{ LastTaskResult = 267011 } } - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() $failure = { Invoke-Process $script:LaunchSplat } | Should-Throw - $stopwatch.Elapsed.TotalSeconds | Should-BeLessThan 15 + # By the module's clock: about five seconds of a task sitting Ready, not the 30-second + # timeout of the run + $waited = ($script:Clock - [datetime]'2026-01-01T00:00:00').TotalSeconds + $waited | Should-BeGreaterThan 4 + $waited | Should-BeLessThan 15 $failure.Exception.Message | Should-BeLikeString '*LAB\isl-user did not start: 0x00041303*never launched*Log on as a batch job*' Should-Invoke Unregister-ScheduledTask -ModuleName IntuneScriptLab -Exactly -Times 1 diff --git a/Tests/Unit/Private/Stop-IslProcessTree.Tests.ps1 b/Tests/Unit/Private/Stop-IslProcessTree.Tests.ps1 index 09d6930..a8f5900 100644 --- a/Tests/Unit/Private/Stop-IslProcessTree.Tests.ps1 +++ b/Tests/Unit/Private/Stop-IslProcessTree.Tests.ps1 @@ -122,7 +122,7 @@ Describe 'Stop-IslProcessTree' -Tag 'Unit', 'Private' { } } - Context 'Core Functionality' { + Context 'Core Functionality' -Tag 'Integration' { It 'ends the process and the process it started' { $tree = @(Start-TestProcessTree) try { @@ -150,7 +150,7 @@ Describe 'Stop-IslProcessTree' -Tag 'Unit', 'Private' { } } - Context 'Error Handling' { + Context 'Error Handling' -Tag 'Integration' { It 'neither fails nor warns for a process that is already gone, under an error preference of Stop' { $tree = @(Start-TestProcessTree) Get-Process -Id $tree -ErrorAction SilentlyContinue | Stop-Process -Force diff --git a/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 b/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 index b467dbf..dbe6307 100644 --- a/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 +++ b/Tests/Unit/Public/Compare-IntuneDeployedScript.Tests.ps1 @@ -475,7 +475,7 @@ Describe 'Compare-IntuneDeployedScript' -Tag 'Unit', 'Public' { @($output | Where-Object { $_.Kind -ne 'Remediation' }) | Should-BeCollection @() } - It 'leaves a calling script one error and no result when Graph cannot be reached' { + It 'leaves a calling script one error and no result when Graph cannot be reached' -Tag 'Integration' { $run = Invoke-CallerScript -Statement @( $script:GraphDown "`$drift = @(Compare-IntuneDeployedScript -Path '$($script:Root)' -Kind Remediation)" diff --git a/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 b/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 index b9006c9..de8660b 100644 --- a/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 +++ b/Tests/Unit/Public/Export-IntuneAgentDiagnostic.Tests.ps1 @@ -382,7 +382,7 @@ Describe 'Export-IntuneAgentDiagnostic' -Tag 'Unit', 'Public' { Test-Path -LiteralPath $zip | Should-BeFalse } - It 'writes no package and returns nothing when a step fails, for a script without try' { + It 'writes no package and returns nothing when a step fails, for a script without try' -Tag 'Integration' { $existing = Join-Path $TestDrive 'existing.zip' [System.IO.File]::WriteAllText($existing, 'not a zip') # A zip cannot be created below a file diff --git a/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 b/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 index 7127274..dc838a4 100644 --- a/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1 @@ -355,7 +355,7 @@ Describe 'Get-IntuneAgentLog' -Tag 'Unit', 'Public' { Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' } - It 'ends on a bad argument and reports a bad log, for a script without try' { + It 'ends on a bad argument and reports a bad log, for a script without try' -Tag 'Integration' { # Should-Throw cannot show what such a caller sees: it calls inside a try, where every # error travels all the way up. The script here has none $logs = $script:Logs diff --git a/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 b/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 index 54e9ff5..437248a 100644 --- a/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneAgentTimeline.Tests.ps1 @@ -302,7 +302,7 @@ Describe 'Get-IntuneAgentTimeline' -Tag 'Unit', 'Public' { Should-Throw -FullyQualifiedErrorId 'PathNotFound,*' } - It 'reports what it could not read and goes on, for a script without try' { + It 'reports what it could not read and goes on, for a script without try' -Tag 'Integration' { $mixed = $script:Mixed $run = Invoke-CallerScript -Statement @( "`$missing = @(Get-IntuneAgentTimeline -Path '$TestDrive\nowhere')" diff --git a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 index 8dab0c9..945154b 100644 --- a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 @@ -373,7 +373,7 @@ Describe 'Get-IntuneScriptHealth' -Tag 'Unit', 'Public' { { Get-IntuneScriptHealth @healthSplat -ErrorAction Stop } | Should-Throw } - It 'leaves a calling script one error and no report when Graph cannot be reached' { + It 'leaves a calling script one error and no report when Graph cannot be reached' -Tag 'Integration' { $run = Invoke-CallerScript -Statement @( $script:GraphDown "`$reports = @(Get-IntuneScriptHealth -Kind Remediation -SkipRunState)" diff --git a/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 b/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 index 9eaf5ff..6a0dc58 100644 --- a/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 +++ b/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 @@ -479,7 +479,7 @@ Describe 'Test-IntuneDeployedScript' -Tag 'Unit', 'Public' { @(Get-ChildItem @listSplat).Count | Should-Be $before } - It 'leaves a calling script one error and no finding when Graph cannot be reached' { + It 'leaves a calling script one error and no finding when Graph cannot be reached' -Tag 'Integration' { $run = Invoke-CallerScript -Statement @( $script:GraphDown "`$findings = @(Test-IntuneDeployedScript -Kind Remediation)" diff --git a/Tests/Unit/Public/Test-IntuneScript.Tests.ps1 b/Tests/Unit/Public/Test-IntuneScript.Tests.ps1 index 0c9f055..db48146 100644 --- a/Tests/Unit/Public/Test-IntuneScript.Tests.ps1 +++ b/Tests/Unit/Public/Test-IntuneScript.Tests.ps1 @@ -107,7 +107,7 @@ Describe 'Test-IntuneScript' -Tag 'Unit', 'Public' { $errors[0].Exception.Message | Should-BeLikeString "$settingsFile*Severity must be a hashtable*" } - It 'leaves a calling script one error for a path that is not there, and the findings of the other' { + It 'leaves a calling script one error for a missing path and the other''s findings' -Tag 'Integration' { $good = New-TestScript 'caller\Detect-Good.ps1' 'exit 2' $missing = Join-Path $TestDrive 'caller\missing.ps1' @@ -301,7 +301,7 @@ Describe 'Test-IntuneScript' -Tag 'Unit', 'Public' { } } - Context 'The help example that gates a build' { + Context 'The help example that gates a build' -Tag 'Integration' { BeforeAll { # Example 3 of the help, as written there, run as a script in a new process $script:GateExample = @(