forked from PowerShell/PSScriptAnalyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettings.tests.ps1
More file actions
410 lines (341 loc) · 16.9 KB
/
Settings.tests.ps1
File metadata and controls
410 lines (341 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
BeforeAll {
$settingsTestDirectory = [System.IO.Path]::Combine($PSScriptRoot, "SettingsTest")
$project1Root = [System.IO.Path]::Combine($settingsTestDirectory, "Project1")
$project2Root = [System.IO.Path]::Combine($settingsTestDirectory, "Project2")
$settingsTypeName = 'Microsoft.Windows.PowerShell.ScriptAnalyzer.Settings'
}
Describe "Settings Precedence" {
Context "settings object is explicit" {
It "runs rules from the explicit setting file" {
$settingsFilepath = [System.IO.Path]::Combine($project1Root, "ExplicitSettings.psd1")
$violations = Invoke-ScriptAnalyzer -Path $project1Root -Settings $settingsFilepath -Recurse
$violations.Count | Should -Be 2
}
}
Context "settings file is implicit" {
It "runs rules from the implicit setting file using the -Path parameter set" {
$violations = Invoke-ScriptAnalyzer -Path $project1Root -Recurse
$violations.Count | Should -Be 1
$violations[0].RuleName | Should -Be "PSAvoidUsingCmdletAliases"
}
It "runs rules from the implicit setting file using the -ScriptDefinition parameter set" {
Push-Location $project1Root
$violations = Invoke-ScriptAnalyzer -ScriptDefinition 'gci; Write-Host' -Recurse
Pop-Location
$violations.Count | Should -Be 1
$violations[0].RuleName | Should -Be "PSAvoidUsingCmdletAliases" `
-Because 'the implicit settings file should have run only the PSAvoidUsingCmdletAliases rule but not PSAvoidUsingWriteHost'
}
It "cannot find file if not named PSScriptAnalyzerSettings.psd1" {
$violations = Invoke-ScriptAnalyzer -Path $project2Root -Recurse
$violations.Count | Should -Be 2
}
}
}
$customRuleParameterTestCases = @('IncludeDefaultRules', 'RecurseCustomRulePath').ForEach{ @{ ParamName = $_ } }
Describe "Settings Class" {
Context "When an empty hashtable is provided" {
It "Should return empty <name> property" -TestCases @(
@{ Name = "IncludeRules" }
@{ Name = "ExcludeRules" }
@{ Name = "Severity" }
@{ Name = "RuleArguments" }
) {
Param($Name)
$settings = New-Object -TypeName $settingsTypeName -ArgumentList @{}
${settings}.${Name}.Count | Should -Be 0
}
It "Should be able to parse empty settings hashtable from settings file" {
$testPSSASettingsFilePath = "TestDrive:\PSSASettings.psd1"
Set-Content $testPSSASettingsFilePath -Value '@{ExcludeRules = @()}'
Invoke-ScriptAnalyzer -ScriptDefinition 'gci' -Settings $testPSSASettingsFilePath | Should -Not -BeNullOrEmpty
}
}
Context "When a string is provided for IncludeRules in a hashtable" {
BeforeAll {
$ruleName = "PSAvoidCmdletAliases"
$settings = New-Object -TypeName $settingsTypeName -ArgumentList @{ IncludeRules = $ruleName }
}
It "Should return an IncludeRules array with 1 element" {
$settings.IncludeRules.Count | Should -Be 1
}
It "Should return the rule in the IncludeRules array" {
$settings.IncludeRules[0] | Should -Be $ruleName
}
}
Context 'When rule arguments are provided in a hashtable' {
BeforeAll {
$settingsHashtable = @{
Rules = @{
PSAvoidUsingCmdletAliases = @{
AllowList = @('cd', 'cp')
}
}
}
$settings = New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable
}
It 'Should return the rule arguments' {
$settings.RuleArguments['PSAvoidUsingCmdletAliases']['AllowList'].Count | Should -Be 2
$settings.RuleArguments['PSAvoidUsingCmdletAliases']['AllowList'][0] | Should -Be 'cd'
$settings.RuleArguments['PSAvoidUsingCmdletAliases']['AllowList'][1] | Should -Be 'cp'
}
It 'Should Be case insensitive' {
$settings.RuleArguments['psAvoidUsingCmdletAliases']['AllowList'].Count | Should -Be 2
$settings.RuleArguments['psAvoidUsingCmdletAliases']['AllowList'][0] | Should -Be 'cd'
$settings.RuleArguments['psAvoidUsingCmdletAliases']['AllowList'][1] | Should -Be 'cp'
}
}
Context 'When rule arguments are provided in a hashtable (legacy argument name)' {
BeforeAll {
$settingsHashtable = @{
Rules = @{
PSAvoidUsingCmdletAliases = @{
allowlist = @("cd", "cp")
}
}
}
$settings = New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable
}
It "Should return the rule arguments" {
$settings.RuleArguments["PSAvoidUsingCmdletAliases"]["allowlist"].Count | Should -Be 2
$settings.RuleArguments["PSAvoidUsingCmdletAliases"]["allowlist"][0] | Should -Be "cd"
$settings.RuleArguments["PSAvoidUsingCmdletAliases"]["allowlist"][1] | Should -Be "cp"
}
It "Should Be case insensitive" {
$settings.RuleArguments["psAvoidUsingCmdletAliases"]["allowlist"].Count | Should -Be 2
$settings.RuleArguments["psAvoidUsingCmdletAliases"]["allowlist"][0] | Should -Be "cd"
$settings.RuleArguments["psAvoidUsingCmdletAliases"]["allowlist"][1] | Should -Be "cp"
}
}
Context "When a settings file path is provided" {
BeforeAll {
$settings = New-Object -TypeName $settingsTypeName `
-ArgumentList ([System.IO.Path]::Combine($project1Root, "ExplicitSettings.psd1"))
$expectedNumberOfIncludeRules = 3
}
It "Should return correct IncludeRules count" {
$settings.IncludeRules.Count | Should -Be 3
}
It "Should return correct ExcludeRules count" {
$settings.ExcludeRules.Count | Should -Be 3
}
It "Should return correct rule argument count" {
$settings.RuleArguments.Count | Should -Be 3
}
It "Should parse boolean type argument" {
$settings.RuleArguments["PSUseConsistentIndentation"]["Enable"] | Should -BeTrue
}
It "Should parse int type argument" {
$settings.RuleArguments["PSUseConsistentIndentation"]["IndentationSize"] | Should -Be 4
}
It "Should parse string literal" {
$settings.RuleArguments["PSProvideCommentHelp"]["Placement"] | Should -Be 'end'
}
}
Context "When CustomRulePath parameter is provided" {
It "Should return an array of 1 item when only 1 path is given in a hashtable" {
$rulePath = "C:\rules\module1"
$settingsHashtable = @{
CustomRulePath = $rulePath
}
$settings = New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable
$settings.CustomRulePath.Count | Should -Be 1
$settings.CustomRulePath[0] | Should -Be $rulePath
}
It "Should return an array of n items when n items are given in a hashtable" {
$rulePaths = @("C:\rules\module1", "C:\rules\module2")
$settingsHashtable = @{
CustomRulePath = $rulePaths
}
$settings = New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable
$settings.CustomRulePath.Count | Should -Be $rulePaths.Count
0..($rulePaths.Count - 1) | ForEach-Object { $settings.CustomRulePath[$_] | Should -Be $rulePaths[$_] }
}
It "Should detect the parameter in a settings file" {
$settings = New-Object -TypeName $settingsTypeName `
-ArgumentList ([System.IO.Path]::Combine($project1Root, "CustomRulePathSettings.psd1"))
$settings.CustomRulePath.Count | Should -Be 2
}
}
Context "When custom rule path relates parameters are provided" {
It "<ParamName>: Should correctly set the value if a boolean is given - true" -TestCases $customRuleParameterTestCases {
$settingsHashtable = @{}
$settingsHashtable.Add($ParamName, $true)
$settings = New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable
$settings."$ParamName" | Should -BeTrue
}
It "<ParamName>: Should correctly set the value if a boolean is given - false" -TestCases $customRuleParameterTestCases {
$settingsHashtable = @{}
$settingsHashtable.Add($ParamName, $false)
$settings = New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable
$settings."$ParamName" | Should -BeFalse
}
It "<ParamName>: Should throw if a non-boolean value is given" -TestCases $customRuleParameterTestCases {
$settingsHashtable = @{}
$settingsHashtable.Add($ParamName, "some random string")
{ New-Object -TypeName $settingsTypeName -ArgumentList $settingsHashtable } | Should -Throw
}
It "<ParamName>: Should detect the parameter in a settings file" -TestCases $customRuleParameterTestCases {
$settings = New-Object -TypeName $settingsTypeName `
-ArgumentList ([System.IO.Path]::Combine($project1Root, "CustomRulePathSettings.psd1"))
$settings."$ParamName" | Should -BeTrue
}
}
Context "Settings GetSafeValue API" {
BeforeAll {
function ShouldBeDeeplyEqual
{
param(
[Parameter(Position = 0)]
$To,
[Parameter(ValueFromPipeline)]
$InputObject
)
if ($null -eq $To)
{
$InputObject | Should -Be $null
return
}
if ($To -is [hashtable])
{
foreach ($toKey in $To.get_Keys())
{
$inputVal = $InputObject[$toKey]
if ($inputVal -is [array])
{
@(, $inputVal) | ShouldBeDeeplyEqual -To $To[$toKey]
continue
}
$inputVal | ShouldBeDeeplyEqual -To $To[$toKey]
}
return
}
if ($To -is [array])
{
$InputObject.Count | Should -Be $To.Count
for ($i = 0; $i -lt $To.Count; $i++)
{
$inputVal = $InputObject[$i]
if ($inputVal -is [array])
{
@(, $inputVal) | ShouldBeDeeplyEqual -To $To[$i]
continue
}
$inputVal | ShouldBeDeeplyEqual -To $To[$i]
}
return
}
$InputObject | Should -Be $To
}
}
It "Safely gets the simple value <Expr>" {
param([string]$Expr)
$pwshVal = Invoke-Expression $Expr
$exprAst = [System.Management.Automation.Language.Parser]::ParseInput($Expr, [ref]$null, [ref]$null)
$exprAst = $exprAst.Find( { $args[0] -is [System.Management.Automation.Language.ExpressionAst] }, $true)
$gsvVal = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::GetSafeValueFromExpressionAst($exprAst)
$gsvVal | Should -Be $pwshVal
} -TestCases @(
@{ Expr = '0' }
@{ Expr = '-2' }
@{ Expr = '-2.5' }
@{ Expr = '$true' }
@{ Expr = '$false' }
@{ Expr = '123124' }
@{ Expr = '0.142' }
@{ Expr = '"Hello"' }
@{ Expr = '"Well then"' }
@{ Expr = '$null' }
)
It "Safely gets the array value <Expr>" {
param([string]$Expr)
$pwshVal = Invoke-Expression $Expr
$exprAst = [System.Management.Automation.Language.Parser]::ParseInput($Expr, [ref]$null, [ref]$null)
$exprAst = $exprAst.Find( { $args[0] -is [System.Management.Automation.Language.ExpressionAst] }, $true)
$gsvVal = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::GetSafeValueFromExpressionAst($exprAst)
# Need to test the type like this so that the pipeline doesn't unwrap the type,
# but we also don't create the array ourselves
$gsvVal.GetType().IsArray | Should -BeTrue
@(, $gsvVal) | ShouldBeDeeplyEqual -To $pwshVal
} -TestCases @(
@{ Expr = '1, 2, 3'; Count = 3 }
@{ Expr = '"One","Two","Three"'; Count = 3 }
@{ Expr = '@(1,2,3,4)'; Count = 4 }
@{ Expr = '@("A","B","C")'; Count = 3 }
@{ Expr = '@()'; Count = 0 }
@{ Expr = '@(7)'; Count = 1 }
@{ Expr = "'1',`n'2',`n'3'"; Count = 3 }
@{ Expr = "@(1`n3`n5`n7)"; Count = 4 }
@{ Expr = "'1',`r`n'2',`r`n'3'"; Count = 3 }
@{ Expr = "@(1`r`n3`r`n5`r`n7)"; Count = 4 }
@{ Expr = "@(1,2,3`n7,8,9)"; Count = 6 }
)
It "Safely gets the hashtable value <Expr>" {
param([string]$Expr)
$pwshVal = Invoke-Expression $Expr
$exprAst = [System.Management.Automation.Language.Parser]::ParseInput($Expr, [ref]$null, [ref]$null)
$exprAst = $exprAst.Find( { $args[0] -is [System.Management.Automation.Language.ExpressionAst] }, $true)
$gsvVal = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::GetSafeValueFromExpressionAst($exprAst)
$gsvVal | Should -BeOfType [hashtable]
$gsvVal | ShouldBeDeeplyEqual -To $pwshVal
} -TestCases @(
@{ Expr = '@{}' }
@{ Expr = '@{ Key = "Value" }' }
@{ Expr = '@{ Item = @(1, 2, 3) }' }
@{ Expr = '@{ Rules = @{ MyRule = @{ Setting1 = "Hello"; Setting2 = 42 } } }' }
@{ Expr = '@{ Rules = @{ MyRule = @{ Setting1 = 7,4,6,1; Setting2 = 42 } } }' }
@{ Expr = '@{ Rules = @{ MyRule = @{ Setting1 = @(); Setting2 = 42 } } }' }
@{ Expr = '@{ Rules = @{ MyRule = @{ Setting1 = @(9, 2, 1, "Hello"); Setting2 = 42 } } }' }
@{ Expr = '@{ Rules = @{ MyRule = @{ Setting1 = @(9, @(3, 6), 1, "Hello"); Setting2 = 42 } } }' }
@{ Expr = '@{ Rules = @{ MyRule = @{ Setting1 = @(9, @{ x = 10; y = 11 }, 1, "Hello"); Setting2 = 42 } } }' }
)
It "Rejects the input <Expr>" {
param([string]$Expr)
$exprAst = [System.Management.Automation.Language.Parser]::ParseInput($Expr, [ref]$null, [ref]$null)
$exprAst = $exprAst.Find( { $args[0] -is [System.Management.Automation.Language.ExpressionAst] }, $true)
$expectedError = 'InvalidDataException'
if ($null -eq $exprAst)
{
$expectedError = 'ArgumentNullException'
}
{ $gsvVal = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::GetSafeValueFromExpressionAst($exprAst) } | Should -Throw -ErrorId $expectedError
} -TestCases @(
@{ Expr = '$var' }
@{ Expr = '' }
@{ Expr = '3+7' }
@{ Expr = '- 2.5' }
@{ Expr = '-not $true' }
@{ Expr = '@(1, Get-Thing)' }
@{ Expr = '@{ Key = Get-Thing }' }
@{ Expr = '@{ Thing = $true;7 ' }
@{ Expr = '@{ Thing = @(Asset-Thing;10) ' }
@{ Expr = ';)' }
)
}
Context "FindSettingsMode" {
BeforeAll {
$findSettingsMode = ($settingsTypeName -as [type]).GetMethod(
'FindSettingsMode',
[System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static)
$outputObject = [System.Object]::new()
}
It "Should detect hashtable" {
$settings = @{}
$findSettingsMode.Invoke($null, @($settings, $null, [ref]$outputObject)) | Should -Be "Hashtable"
}
It "Should detect hashtable wrapped by a PSObject" {
$settings = [PSObject]@{} # Force the settings hashtable to be wrapped
$findSettingsMode.Invoke($null, @($settings, $null, [ref]$outputObject)) | Should -Be "Hashtable"
}
It "Should detect string" {
$settings = ""
$findSettingsMode.Invoke($null, @($settings, $null, [ref]$outputObject)) | Should -Be "File"
}
It "Should detect string wrapped by a PSObject" {
$settings = [PSObject]"" # Force the settings string to be wrapped
$findSettingsMode.Invoke($null, @($settings, $null, [ref]$outputObject)) | Should -Be "File"
}
}
}