1+ Import-Module PSScriptAnalyzer
2+ $ruleName = " PSUseLiteralInitializerForHashtable"
3+
4+ Describe " UseLiteralInitlializerForHashtable" {
5+ Context " When new-object hashtable is used to create a hashtable" {
6+ It " has violation" {
7+ $violationScriptDef = @'
8+ $htable1 = new-object hashtable
9+ $htable2 = new-object system.collection.hashtable
10+ $htable3 = new-object -Typename hashtable -ArgumentList 10
11+ '@
12+ $violations = Invoke-ScriptAnalyzer - ScriptDefinition $violationScriptDef - IncludeRule $ruleName
13+ $violations.Count | Should Be 3
14+ }
15+
16+ It " does not detect violation if arguments given to new-object contain ignore case string comparer" {
17+ $violationScriptDef = @'
18+ $htable1 = new-object hashtable [system.stringcomparer]::ordinalignorecase
19+ $htable2 = new-object -Typename hashtable -ArgumentList [system.stringcomparer]::ordinalignorecase
20+ $htable3 = new-object hashtable -ArgumentList [system.stringcomparer]::ordinalignorecase
21+ $htable4 = new-object -Typename hashtable [system.stringcomparer]::ordinalignorecase
22+ '@
23+ $violations = Invoke-ScriptAnalyzer - ScriptDefinition $violationScriptDef - IncludeRule $ruleName
24+ $violations.Count | Should Be 0
25+ }
26+
27+ It " suggests correction" {
28+ $violationScriptDef = @'
29+ $htable1 = new-object hashtable
30+ '@
31+ $violations = Invoke-ScriptAnalyzer - ScriptDefinition $violationScriptDef - IncludeRule $ruleName
32+ $violations [0 ].SuggestedCorrections[0 ].Text | Should Be ' @{}'
33+ }
34+ }
35+
36+ Context " When [hashtable]::new is used to create a hashtable" {
37+ It " has violation" {
38+ $violationScriptDef = @'
39+ $htable1 = [hashtable]::new()
40+ $htable2 = [system.collection.hashtable]::new()
41+ $htable3 = [hashtable]::new(10)
42+ '@
43+ $violations = Invoke-ScriptAnalyzer - ScriptDefinition $violationScriptDef - IncludeRule $ruleName
44+ $violations.Count | Should Be 3
45+ }
46+
47+ It " does not detect violation if arguments given to [hashtable]::new contain ignore case string comparer" {
48+ $violationScriptDef = @'
49+ $htable1 = [hashtable]::new(10, [system.stringcomparer]::ordinalignorecase)
50+ $htable2 = [hashtable]::new(10, [system.stringcomparer]::ordinalignorecase)
51+ '@
52+ $violations = Invoke-ScriptAnalyzer - ScriptDefinition $violationScriptDef - IncludeRule $ruleName
53+ $violations.Count | Should Be 0
54+ }
55+
56+ It " suggests correction" {
57+ $violationScriptDef = @'
58+ $htable1 = [hashtable]::new()
59+ '@
60+ $violations = Invoke-ScriptAnalyzer - ScriptDefinition $violationScriptDef - IncludeRule $ruleName
61+ $violations [0 ].SuggestedCorrections[0 ].Text | Should Be ' @{}'
62+ }
63+
64+ }
65+ }
0 commit comments