Skip to content

Commit 8b9f115

Browse files
Jos KoelewijnJos Koelewijn
Jos Koelewijn
authored and
Jos Koelewijn
committed
Add tests for AvoidUnInitializedVarsInNewRunspaces
1 parent 163d2c2 commit 8b9f115

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
2+
$testRootDirectory = Split-Path -Parent $directory
3+
4+
Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1")
5+
6+
$ruleName = "PSAvoidUnInitializedVarsInNewRunspaces"
7+
8+
$settings = @{
9+
IncludeRules = @($ruleName)
10+
}
11+
12+
Describe "AvoidUnInitializedVarsInNewRunspaces" {
13+
Context "Should detect something" {
14+
$testCases = @(
15+
@{
16+
Description = "Foreach-Object -Parallel with undeclared var"
17+
ScriptBlock = '{
18+
1..2 | ForEach-Object -Parallel { $var }
19+
}'
20+
}
21+
@{
22+
Description = "alias foreach -parallel with undeclared var"
23+
ScriptBlock = '{
24+
1..2 | ForEach -Parallel { $var }
25+
}'
26+
}
27+
@{
28+
Description = "alias % -parallel with undeclared var"
29+
ScriptBlock = '{
30+
1..2 | % -Parallel { $var }
31+
}'
32+
}
33+
@{
34+
Description = "abbreviated param Foreach-Object -pa with undeclared var"
35+
ScriptBlock = '{
36+
1..2 | foreach-object -pa { $var }
37+
}'
38+
}
39+
@{
40+
Description = "Nested Foreach-Object -Parallel with undeclared var"
41+
ScriptBlock = '{
42+
$myNestedScriptBlock = {
43+
1..2 | ForEach-Object -Parallel { $var }
44+
}
45+
}'
46+
}
47+
)
48+
49+
it "should emit for: <Description>" -TestCases $testCases {
50+
param($Description, $ScriptBlock)
51+
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition $ScriptBlock -Settings $settings
52+
$warnings.Count | Should -Be 1
53+
}
54+
}
55+
56+
Context "Should not detect anything" {
57+
$testCases = @(
58+
@{
59+
Description = "Foreach-Object with uninitialized var inside"
60+
ScriptBlock = '{
61+
1..2 | ForEach-Object { $var }
62+
}'
63+
}
64+
@{
65+
Description = "Foreach-Object -Parallel with uninitialized `$using: var"
66+
ScriptBlock = '{
67+
1..2 | foreach-object -Parallel { $using:var }
68+
}'
69+
}
70+
@{
71+
Description = "Foreach-Object -Parallel with var assigned locally"
72+
ScriptBlock = '{
73+
1..2 | ForEach-Object -Parallel { $var="somevalue" }
74+
}'
75+
}
76+
@{
77+
Description = "Foreach-Object -Parallel with built-in var '`$Args' inside"
78+
ScriptBlock = '{
79+
1..2 | ForEach-Object { $Args[0] } -ArgumentList "a" -Parallel
80+
}'
81+
}
82+
)
83+
84+
it "should not emit anything for: <Description>" -TestCases $testCases {
85+
param($Description, $ScriptBlock)
86+
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition $ScriptBlock -Settings $settings
87+
$warnings.Count | Should -Be 0
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)