Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ entries are carried over from the manifest's release notes.

### Changed

- 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
category, each with the control the module has (#132).
- The rule order, the table of in-box modules, the Windows release builds and the events of the
Expand Down
8 changes: 5 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,8 @@ under Windows PowerShell 5.1 as well before pushing:
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
and the validation kit are not written for strict mode yet. Remove that when they are. The module
does not depend on it: it sets its own strict mode in the root module.
The script sets strict mode, and the suites and the validation kit run under it, as the module
runs under its own. A mock body reads an argument the call may leave out from
`$PesterBoundParameters`: there is no variable for an argument that was not bound, and reading one
is a strict-mode error. Read `Mandatory` and `ValidValues` through `Test-ParameterMandatory` and
`Get-ParameterValidValue` in `Tests/TestHelpers`, not across a parameter's `Attributes`.
14 changes: 4 additions & 10 deletions Tests/Invoke-Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -212,16 +212,10 @@ if ($CodeCoverage) {
$manifestPath = Join-Path -Path $repositoryRoot -ChildPath 'IntuneScriptLab.psd1'
Import-Module -Name $manifestPath -Force -Global

# Pester runs the test files in scopes below this one, so they would inherit this script's strict
# mode. The module sets its own in its root module and does not depend on this one, but the
# suites and the validation kit are not yet written for strict mode (#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
}
# Pester runs the test files in scopes below this one, so they run under this script's strict mode
# (ERR-03), as the module runs under its own: a test that reads a variable it never set, or a
# property an object does not have, fails instead of comparing against $null.
$result = Invoke-Pester -Configuration $configuration

if ($null -eq $result) {
throw "Pester returned no result for '$TestType': it found no test files."
Expand Down
103 changes: 103 additions & 0 deletions Tests/TestHelpers/TestHelpers.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -439,3 +439,106 @@ function Invoke-CallerScript {
ExitCode = $process.ExitCode
}
}


function Test-ParameterMandatory {
Comment thread
fadwen-ai marked this conversation as resolved.
Resolved
<#
.SYNOPSIS
Tests whether a command's parameter is mandatory in any of its parameter sets.

.DESCRIPTION
Reads the parameter's Parameter attributes only. Reading Mandatory across all of a
parameter's attributes fails under strict mode, because a validation or alias attribute has
no such property. A parameter the command does not have is an error, so that a test that a
parameter is optional fails when the parameter is renamed or removed.

.PARAMETER Command
The command, as Get-Command returns it.

.PARAMETER Name
The name of the parameter.

.EXAMPLE
Test-ParameterMandatory -Command (Get-Command Invoke-IntuneDetectionTest) -Name 'Path'

Returns $true: -Path is mandatory.

.INPUTS
None.

.OUTPUTS
System.Boolean. Whether the parameter is mandatory in a parameter set.
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory)]
[System.Management.Automation.CommandInfo]$Command,

[Parameter(Mandatory)]
[string]$Name
)

if (-not $Command.Parameters.ContainsKey($Name)) {
$exception = [System.ArgumentException]::new("$($Command.Name) has no parameter -$Name.")
$category = [System.Management.Automation.ErrorCategory]::ObjectNotFound
$PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new(
$exception, 'ParameterNotFound', $category, $Name))
}
$mandatory = @($Command.Parameters[$Name].Attributes | Where-Object {
$_ -is [System.Management.Automation.ParameterAttribute] -and $_.Mandatory
})
$mandatory.Count -gt 0
}


function Get-ParameterValidValue {
<#
.SYNOPSIS
Gets the values a command's parameter accepts, from its ValidateSet attribute.

.DESCRIPTION
Reads the ValidateSet attribute of the parameter only. Reading ValidValues across all of a
parameter's attributes fails under strict mode, because the other attributes have no such
property. Returns nothing for a parameter without a ValidateSet, and a parameter the
command does not have is an error.

.PARAMETER Command
The command, as Get-Command returns it.

.PARAMETER Name
The name of the parameter.

.EXAMPLE
Get-ParameterValidValue -Command (Get-Command Invoke-IntuneDetectionTest) -Name 'Context'

Returns 'User' and 'System'.

.INPUTS
None.

.OUTPUTS
System.String. Each value the parameter accepts.
#>
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory)]
[System.Management.Automation.CommandInfo]$Command,

[Parameter(Mandatory)]
[string]$Name
)

if (-not $Command.Parameters.ContainsKey($Name)) {
$exception = [System.ArgumentException]::new("$($Command.Name) has no parameter -$Name.")
$category = [System.Management.Automation.ErrorCategory]::ObjectNotFound
$PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new(
$exception, 'ParameterNotFound', $category, $Name))
}
foreach ($attribute in $Command.Parameters[$Name].Attributes) {
Comment thread
fadwen-ai marked this conversation as resolved.
Resolved
if ($attribute -is [System.Management.Automation.ValidateSetAttribute]) {
$attribute.ValidValues
}
}
}
6 changes: 5 additions & 1 deletion Tests/Unit/Module.InputLength.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ BeforeAll {
if (-not $loaded -or $loaded.ModuleBase -ne $script:ModuleRoot) {
Import-Module -Name (Join-Path -Path $script:ModuleRoot -ChildPath 'IntuneScriptLab.psd1') -Force
}
$helpers = Join-Path -Path (Join-Path -Path $script:ModuleRoot -ChildPath 'Tests') -ChildPath 'TestHelpers'
. (Join-Path -Path $helpers -ChildPath 'TestHelpers.ps1')
}

Describe 'Length of text parameters' -Tag 'Unit', 'Contract', 'Security' {
Expand All @@ -42,7 +44,9 @@ Describe 'Length of text parameters' -Tag 'Unit', 'Contract', 'Security' {
It '<Command> -<Parameter> refuses 1,001 characters before it does anything' -ForEach $script:Limited {
$splat = @{ $Parameter = 'a' * 1001 }
# A mandatory -Path is given, so that the check, not the binding, answers
if ((Get-Command -Name $Command).Parameters['Path'].Attributes.Mandatory -contains $true) {
$commandInfo = Get-Command -Name $Command
if ($commandInfo.Parameters.ContainsKey('Path') -and
(Test-ParameterMandatory -Command $commandInfo -Name 'Path')) {
$splat['Path'] = $TestDrive
}

Expand Down
2 changes: 1 addition & 1 deletion Tests/Unit/Private/Get-IslExportReport.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Describe 'Get-IslExportReport' -Tag 'Unit', 'Private' {
It 'posts the job, polls it and returns the CSV rows of the download' {
$script:Polls = 0
Mock Invoke-IslGraphRequest -ModuleName IntuneScriptLab {
if ($Method -eq 'POST') { return @{ id = 'job-1'; status = 'notStarted' } }
if ($PesterBoundParameters['Method'] -eq 'POST') { return @{ id = 'job-1'; status = 'notStarted' } }
$script:Polls++
if ($script:Polls -lt 2) { return @{ id = 'job-1'; status = 'inProgress' } }
@{ id = 'job-1'; status = 'completed'; url = 'https://download.example/job-1.zip' }
Expand Down
2 changes: 1 addition & 1 deletion Tests/Unit/Private/Get-IslIntuneOutput.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Describe 'Get-IslIntuneOutput' -Tag 'Unit', 'Private' {
$result.OutputTruncated | Should-BeFalse
}

It 'keeps the last <Limit> characters of that line and flags the truncation' {
It 'keeps the last 2,048 characters of that line, or -Limit, and flags the truncation' {
$result = Get-IntuneOutput -StdOut ('a' * 10 + 'b' * 2048)
$result.Output.Length | Should-Be 2048
$result.Output | Should-BeLikeString 'bbbb*'
Expand Down
2 changes: 2 additions & 0 deletions Tests/Unit/Private/Invoke-IslGraphRequest.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ BeforeAll {
if (-not $loaded -or $loaded.ModuleBase -ne $script:ModuleRoot) {
Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force
}
# Set either way: AfterAll reads it, and a machine with Microsoft.Graph needs no stub
$script:StubCreated = $false
if (-not (Get-Command Invoke-MgGraphRequest -ErrorAction SilentlyContinue)) {
function global:Invoke-MgGraphRequest {
<#
Expand Down
2 changes: 2 additions & 0 deletions Tests/Unit/Private/Invoke-IslGraphRequestOnce.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ BeforeAll {
if (-not $loaded -or $loaded.ModuleBase -ne $script:ModuleRoot) {
Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force
}
# Set either way: AfterAll reads it, and a machine with Microsoft.Graph needs no stub
$script:StubCreated = $false
if (-not (Get-Command Invoke-MgGraphRequest -ErrorAction SilentlyContinue)) {
function global:Invoke-MgGraphRequest {
<#
Expand Down
3 changes: 2 additions & 1 deletion Tests/Unit/Private/Invoke-IslNativeCommand.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ BeforeAll {
if (-not $loaded -or $loaded.ModuleBase -ne $script:ModuleRoot) {
Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force
}
. (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1')
$script:Cmd = Join-Path ([System.Environment]::SystemDirectory) 'cmd.exe'

function Invoke-NativeCommand {
Expand Down Expand Up @@ -66,7 +67,7 @@ Describe 'Invoke-IslNativeCommand' -Tag 'Unit', 'Private' {
$command = InModuleScope IntuneScriptLab { Get-Command Invoke-IslNativeCommand }
$command | Should-HaveParameter -ParameterName FilePath -Type ([string]) -Mandatory
$command | Should-HaveParameter -ParameterName Arguments -Type ([string])
$command.Parameters['Arguments'].Attributes.Mandatory | Should-NotContainCollection $true
Test-ParameterMandatory -Command $command -Name 'Arguments' | Should-BeFalse
}
}

Expand Down
8 changes: 5 additions & 3 deletions Tests/Unit/Private/Invoke-IslWin32ContentCommand.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,13 @@ Describe 'Invoke-IslWin32ContentCommand' -Tag 'Unit', 'Private' {
Set-Content -LiteralPath (Join-Path $script:Content 'setup.exe') -Value 'binary' -Encoding ascii
$script:Warnings = [System.Collections.Generic.List[string]]::new()
$script:Seen = @{}
# Records the launch and whether the copy was there while it ran
# Records the launch and whether the copy was there while it ran. An argument the call left
# out is read from $PesterBoundParameters, where it is $null: there is no variable for it
Mock Invoke-IslProcess -ModuleName IntuneScriptLab {
$script:Seen['Arguments'] = $Arguments
$script:Seen['Bitness'] = $LauncherBitness
$script:Seen['WorkFolder'] = $WorkFolder
$script:Seen['Credential'] = $Credential
$script:Seen['Credential'] = $PesterBoundParameters['Credential']
$script:Seen['Copied'] = Test-Path -LiteralPath (Join-Path $WorkingDirectory 'setup.exe')
[pscustomobject]@{
ExitCode = 3010; TimedOut = $false; StdOut = 'done'; StdErr = ''; Duration = [timespan]::Zero
Expand Down Expand Up @@ -122,7 +123,8 @@ Describe 'Invoke-IslWin32ContentCommand' -Tag 'Unit', 'Private' {
$credential = [System.Management.Automation.PSCredential]::Empty
$null = Invoke-Content ($run + $script:Base + @{ Credential = $credential })

$script:Seen['Credential'].UserName | Should-BeNull
# The empty credential is not passed on: the run is the current user's own
$script:Seen['Credential'] | Should-BeNull
$script:Seen['WorkFolder'] | Should-BeLikeString "$([System.IO.Path]::GetTempPath())*"
Should-Invoke Grant-IslFolderAccess -ModuleName IntuneScriptLab -Times 0 -Exactly
}
Expand Down
7 changes: 5 additions & 2 deletions Tests/Unit/Private/Test-IslPolicyScript.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,14 @@ Describe 'Test-IslPolicyScript' -Tag 'Unit', 'Private' {

Context 'The run settings' {
BeforeAll {
# An argument the call left out is no variable in the mock; $PesterBoundParameters gives $null
Mock Test-IntuneScript -ModuleName IntuneScriptLab {
$script:Analyzed = @{
Context = $Context; Architecture = $Architecture; Signature = [bool]$EnforceSignatureCheck
Context = $PesterBoundParameters['Context']
Architecture = $PesterBoundParameters['Architecture']
Signature = [bool]$PesterBoundParameters['EnforceSignatureCheck']
}
$script:AnalyzedSettings = $null -ne $Settings
$script:AnalyzedSettings = $null -ne $PesterBoundParameters['Settings']
}
}

Expand Down
5 changes: 3 additions & 2 deletions Tests/Unit/Public/Assert-PassIntuneAnalysis.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,10 @@ Describe 'Assert-PassIntuneAnalysis' -Tag 'Unit', 'Public' {

It 'limits MinimumSeverity and ScriptType to the analyzer values' {
$command = Get-Command Assert-PassIntuneAnalysis
$command.Parameters['MinimumSeverity'].Attributes.ValidValues |
Get-ParameterValidValue -Command $command -Name 'MinimumSeverity' |
Should-BeCollection @('Information', 'Warning', 'Error')
$command.Parameters['ScriptType'].Attributes.ValidValues | Should-ContainCollection 'Win32Detection'
Get-ParameterValidValue -Command $command -Name 'ScriptType' |
Should-ContainCollection 'Win32Detection'
}
}

Expand Down
4 changes: 2 additions & 2 deletions Tests/Unit/Public/Get-IntuneAgentLog.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,9 @@ Describe 'Get-IntuneAgentLog' -Tag 'Unit', 'Public' {
Context 'Parameter Validation' {
It 'limits -Log and -Level to the known values and -Last to a positive count' {
$command = Get-Command Get-IntuneAgentLog
$command.Parameters['Log'].Attributes.ValidValues |
Get-ParameterValidValue -Command $command -Name 'Log' |
Should-BeCollection @('Agent', 'AppWorkload', 'HealthScripts', 'AgentExecutor', 'All')
$command.Parameters['Level'].Attributes.ValidValues |
Get-ParameterValidValue -Command $command -Name 'Level' |
Should-BeCollection @('Information', 'Warning', 'Error')
{ Get-IntuneAgentLog -Path $script:Logs -Last 0 } | Should-Throw
}
Expand Down
6 changes: 3 additions & 3 deletions Tests/Unit/Public/Invoke-IntuneDetectionTest.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ Describe 'Invoke-IntuneDetectionTest' -Tag 'Unit', 'Public' {
Context 'Parameter Validation' {
It 'declares Path as mandatory and limits the architecture and context' {
$command = Get-Command Invoke-IntuneDetectionTest
$command.Parameters['Path'].Attributes.Mandatory | Should-ContainCollection $true
$command.Parameters['Architecture'].Attributes.ValidValues |
Test-ParameterMandatory -Command $command -Name 'Path' | Should-BeTrue
Get-ParameterValidValue -Command $command -Name 'Architecture' |
Should-BeCollection @('x86', 'x64', 'arm64')
$command.Parameters['Context'].Attributes.ValidValues | Should-BeCollection @('User', 'System')
Get-ParameterValidValue -Command $command -Name 'Context' | Should-BeCollection @('User', 'System')
}

It 'takes script paths from the pipeline, as Get-ChildItem gives them' {
Expand Down
4 changes: 2 additions & 2 deletions Tests/Unit/Public/Invoke-IntuneRemediationTest.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ Describe 'Invoke-IntuneRemediationTest' -Tag 'Unit', 'Public' {
Context 'Parameter Validation' {
It 'declares DetectionPath as mandatory and RemediationPath as optional' {
$command = Get-Command Invoke-IntuneRemediationTest
$command.Parameters['DetectionPath'].Attributes.Mandatory | Should-ContainCollection $true
$command.Parameters['RemediationPath'].Attributes.Mandatory | Should-NotContainCollection $true
Test-ParameterMandatory -Command $command -Name 'DetectionPath' | Should-BeTrue
Test-ParameterMandatory -Command $command -Name 'RemediationPath' | Should-BeFalse
}

It 'defaults to the 32-bit host and the current user, as the portal does' {
Expand Down
6 changes: 3 additions & 3 deletions Tests/Unit/Public/Invoke-IntuneRequirementTest.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ Describe 'Invoke-IntuneRequirementTest' -Tag 'Unit', 'Public' {
It 'requires the path, the output type and the value; the operator defaults to Equal' {
$command = Get-Command Invoke-IntuneRequirementTest
foreach ($name in 'Path', 'OutputType', 'Value') {
$command.Parameters[$name].Attributes.Mandatory | Should-ContainCollection $true
Test-ParameterMandatory -Command $command -Name $name | Should-BeTrue
}
$command.Parameters['OutputType'].Attributes.ValidValues |
Get-ParameterValidValue -Command $command -Name 'OutputType' |
Should-BeCollection @('String', 'DateTime', 'Integer', 'Float', 'Version', 'Boolean')
$command.Parameters['Operator'].Attributes.ValidValues.Count | Should-Be 6
@(Get-ParameterValidValue -Command $command -Name 'Operator').Count | Should-Be 6
}

It 'takes script paths from the pipeline, with the rule given once' {
Expand Down
2 changes: 1 addition & 1 deletion Tests/Unit/Public/Invoke-IntuneWin32AppTest.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Describe 'Invoke-IntuneWin32AppTest' -Tag 'Unit', 'Public' {
Context 'Parameter Validation' {
It 'needs a detection script or detection rules, the content folder and the intent command' {
$command = Get-Command Invoke-IntuneWin32AppTest
$command.Parameters['ContentPath'].Attributes.Mandatory | Should-ContainCollection $true
Test-ParameterMandatory -Command $command -Name 'ContentPath' | Should-BeTrue
$missingDetection = @{
FullyQualifiedErrorId = 'DetectionMissing,*'
ExceptionMessage = '*-DetectionPath*-DetectionRule*'
Expand Down
Loading