Test-Module.ps1

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
function Test-Module
{
    <#
    .Synopsis
        Runs ScriptCop and module test cases
    .Description
        Runs ScriptCop static analysis on a module, and then runs test cases included with the module.
 
 
        Tests can be declared in many ways.
         
         
        ScriptCop will look for a file in each module:
            ModuleName.ScriptCop.psd1
 
        This file contains information about how the module will be tested.
 
        If this file is present, it will be used to declare test passes that can be run. For example:
 
 
            @{
                'BuildVerificationTests' = '/Tests/BVT*.test.ps1', 'Getting_Started', 'Test-Function:1'
                'ScriptCop' = 'Test-CommandNamingConvention', 'Test-ForCommonParameterMistake', 'Test-ForPipelineParameter',
                    'Test-ForParameterSetAmbiguity', 'Test-ParameterNamingConvention', 'Test-Help', 'Test-ProcessBlockImplemented'
            }
 
        The above file declares a test pass called BuildVerifiationTests, that runs any files in /Tests/BVT, the Getting_Started demo, and the first the function example of Test-Function.
 
         
        It also declares the static analysis of the module only uses the a subset of the available rules.
                
         
        If the ScriptCop.psd1 file is not present, several test passes will be automatically created:
 
        - A test pass will be generated from each demo file
        - A test pass will be generated from all examples in each function
 
 
        Unless the -TestPass parameter is provided, all test passes declared will be run.
         
 
    #>

    param(
    # The name of the module
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    [ValidateScript({
        if (-not (Get-Module "$_")) {
            $isavailable = Get-Module -ListAvailable "$_"
            if ($isavailable) {
                $isavailable | Import-Module -Global
            }
        }
    return $true
    })]    
    [string]
    $Name,

    # If provided, will run only the specific test passes.
    # If this is provided, and it does not include the term "ScriptCop", static analysis will not be run.
    [string[]]
    $TestPass,

    # A list of individual test cases. Each test case can be:
    # * The name of a demo file
    # * The relative path to a .test.ps1 within the module
    # * The name of a command, and the number of it's example
    [string[]]
    $TestCase,
    
    # If set, will collect script coverage information while running test cases
    [Switch]
    $GetScriptCoverage,

    # If set, will collect coverage information on commands and their parameters.
    [Switch]
    $GetCommandCoverage
    )


    process {
        #region Load Module and Test Pass Information
        $realModule= Get-Module $Name

        $progressId = Get-Random
        $moduleRoot =$realModule | Split-Path

        $scriptTestPass = @{}
        if (Test-Path "$moduleRoot\$name.ScriptCop.psd1") {
            $scriptTestPass += & ([ScriptBlock]::Create("
            data {
                $([IO.File]::ReadAllText("$moduleRoot\$name.ScriptCop.psd1"))
            }
            "
))



            if (-not $PSBoundParameters.TestPass) {
                $TestPass = $scriptTestPass.Keys | Sort-Object
            }
        }

        $rules = Get-ScriptCopRule | Select-Object -ExpandProperty Name
        if (-not $scriptTestPass.ScriptCop -or $scriptTestPass.ScriptCop -eq '*') {
            
            $scriptTestPass.ScriptCop = $rules
        }
        #endregion Load Module and Test Pass Information


        #region Load Demo files and examples
        $demos = Get-ChildItem "$moduleRoot" -Recurse |
            Where-Object {
                $_.Name -like "*.demo.ps1" -or $_.Name -like "*.walkthru.help.txt"
            } |
            ForEach-Object {
                $_.Name -ireplace "\.demo\.ps1", "" -ireplace "\.walkthru\.help\.txt", ""
            }

        if (-not $scriptTestPass.Demo) {
            $scriptTestPass.Demo = $demos
        }
        
        
        $exampleDict = @{}
        $moduleCommands = @(Get-Command -Module $name -CommandType Function, Cmdlet )
        
        $moduleCommands | 
            ForEach-Object -Begin {
                $counter = 0
            } -Process {
                $cmd = $_
                $help = $_ | Get-Help
                $counter++
                $perc = $counter * 100 / $moduleCommands.Count
                Write-Progress "Building Examples Dictionary" "$cmd" -PercentComplete $perc -id $progressId
                $count = 1
                $exampleTestCases = if ($help.Examples.Example) {
                    $help.examples.example | 
                        ForEach-Object {
                            "$($cmd):$count"
                            $exampleDict["$($cmd):$count"] = $_.Code + ([environment]::NewLine) + $($_.Remarks | Out-String)
                            $count++
                        }

                    
                }


                if (-not $scriptTestPass.($cmd.name)) {
                    $scriptTestPass.($cmd.name) = $exampleTestCases
                }
            }    
        #endregion Load Demo files and examples
        

        #region Extract Test Case Objects from walkthrus, ScriptCop rules, and walkthrus
        $extractTestCase = {
            $testPassInfo = $_
            $c = 0
            if ($TestPassInfo.Key -eq "ScriptCop") {
                New-Object PSObject -Property @{
                    TestPass = $TestPassInfo.Key
                    TestCase = "ScriptCop"
                    ScriptBlock = [ScriptBlock]::Create("Get-Module $Name | Test-Command -Rule '$($_.Value -join "','")'")
                    Data = @(@{})
                }
                return
            }  
            foreach ($v in $_.Value) {
                $C++
                if ($exampleDict["$v"]) {
                    New-Object PSObject -Property @{
                        TestPass = $TestPassInfo.Key
                        TestCase = "$v"
                        ScriptBlock = [ScriptBlock]::Create($exampleDict["$v"])
                        Data = @(@{})
                    }  
                } else {
                    Get-ChildItem -Recurse -Path $moduleRoot |
                        ForEach-Object {
                            $relativePath = $_.FullName.Replace($moduleRoot, "").TrimStart("\")
                            if ($_.Name -like "*.walkthru.help.txt" -and $_.Name -ireplace "\.walkthru\.help\.txt" -eq "$v".Replace(" ", "_")) {
                                New-Object PSObject -Property @{
                                    TestPass = $testPassInfo.Key
                                    TestCase = $_.Name -ireplace "\.walkthru\.help\.txt" -ireplace "_", " "            
                                    ScriptBlock = [ScriptBlock]::Create([IO.File]::ReadAllText($_.FullName))
                                    Data = @(@{})
                                }
                                
                            } elseif ($_.Name -like "*.demo.ps1" -and $_.Name -ireplace "\.demo\.ps1" -eq "$v".Replace(" ", "_")) {
                                New-Object PSObject -Property @{
                                    TestPass = $testPassInfo.Key
                                    TestCase = $_.Name -ireplace "\.demo\.ps1" -ireplace "_", " "            
                                    ScriptBlock = [ScriptBlock]::Create([IO.File]::ReadAllText($_.FullName))
                                    Data = @(@{})
                                }
                            } elseif ($_.Name -like "*.test.ps1" -and $relativePath -like "*$v*") {
                                
                                New-Object PSObject -Property @{
                                    TestPass = $testPassInfo.Key
                                    TestCase = $_.Name -ireplace "\.test\.ps1" -ireplace "_", " "            
                                    ScriptBlock = [ScriptBlock]::Create([IO.File]::ReadAllText($_.FullName))
                                    Data = @(@{})
                                }
                            }
                        }
                }
            }
            
        }
        #endregion Extract Test Case Objects from walkthrus, ScriptCop rules, and walkthrus

        #region Determine Test Cases
        $theTestCases = 
            @(if ($TestCase) {
                $scriptTestPass.GetEnumerator() |
                    Sort-Object Key|
                    Where-Object {
                        (-not $TestPass -or 
                        $TestPass -contains $_.Key) -and $TestPass -ne 'TestData'
                    } |
                    ForEach-Object $extractTestCase |
                    Where-Object {
                        $TestCase -contains $_.TestCase
                    }
            } else {
                $scriptTestPass.GetEnumerator() |
                    Sort-Object Key|
                    Where-Object {
                        (-not $TestPass -or 
                        $TestPass -contains $_.Key) -and $TestPass -ne 'TestData'
                    } | 
                    ForEach-Object $extractTestCase
            })
        #endregion Determine Test Cases
            

        $TestPassProgressId = Get-Random
        
        if ($GetCommandCoverage) {
            Enable-CommandCoverage -Module $Name            
        }


        #region Run the test pass
        $c = 0
        $testPasses = $theTestCases | Group-Object TestPass


        $totalTestCount = 0
        $totalTestPassCount = 0
        $passedTestCaseCount = 0
        $passedTestPassCount = 0
        foreach ($testPassInfo in $testPasses) {
            $c = 0
            $TestPassResults = foreach ($testCaseInfo in $testPassInfo.Group) {
                $perc = $c * 100 / $testPassInfo.Count
                Write-Progress "Running Tests - $($testCaseInfo.TestPass)" "$($TestCaseInfo.TestCase)" -PercentComplete $perc -Id $progressId 
                $c++
                $testOutput = @(try {
                    if ($GetScriptCoverage) {
                        $realModule | 
                            Split-Path |
                            Get-ChildItem -Filter *.ps1 -Recurse |
                                Show-ScriptCoverage -Command $testCaseInfo.ScriptBlock -DoNotDotSource
                    } else {
                        & $testCaseInfo.ScriptBlock 2>&1
                    }
                
                } catch {
                    $_
                })

                $errorList = @(if ($testCaseInfo.testPass -ne 'ScriptCop') {
                    if ($testOutput | ?{ $_ -is [Management.Automation.ErrorRecord]}) {
                        $testOutput | ? {$_ -is  [Management.Automation.ErrorRecord]}
                    } elseif ($testOutput | ?{ $_ -is [Exception]}) {
                        $testOutput | ? {$_ -is  [Exception]}
                    }

                } else {
                    $testOutput | ? {$_ -isnot [Management.Automation.ErrorRecord]}
                })

            
                $testCaseOutput = New-Object PSObject -Property @{
                    Passed = $errorList.Count -eq 0  
                    Errors = $errorList
                    Output = $testOutput
                    TestPass = $testCaseInfo.TestPass
                    TestCase= $testCaseInfo.TestCase
                }

                $totalTestCount++
                if ($testCaseOutput.Passed) {
                    $passedTestCaseCount++
                }
                $testCaseOutput.pstypenames.clear()
                $testCaseOutput.pstypenames.add('ScriptCop.Test.Output')
                $testCaseOutput
            }
            $totalTestPassCount++
            $testPassOutput = New-Object PSObject -Property @{
                TestPass = $testPassInfo.Name
                Results = $TestPassResults
                Passed = -not ($TestPassResults | ? { -not $_.Passed })
            }

            if ($testPassOutput.Passed) {
                $passedTestPassCount++
            }
            $testPassOutput.pstypenames.clear()
            $testPassOutput.pstypenames.add('ScriptCop.Test.Pass.Output')
            $testPassOutput
        }
        
        Write-Progress "Running Tests" "Completed" -Id $TestPassProgressId -Completed


        $testPassSummary = New-Object PSObject -Property @{
            TotalTestCases = $totalTestCount
            PassingTestCases = $passedTestCaseCount
            PercentPassingTestCases = $passedTestCaseCount * 100 / $totalTestCount
            TotalTestPasses = $totalTestPassCount
            PassingTestPasses = $totalTestPassCount
            PercentPassingTestPasses = $passedTestPassCount * 100 / $totalTestPassCount
            Module = $Name
        }


        $testPassSummary.pstypenames.clear()
        $testPassSummary.pstypenames.Add('ScriptCop.Test.Pass.Summary')
        $testPassSummary

        if ($GetCommandCoverage) {

            Get-CommandCoverage -Module $Name
            Disable-CommandCoverage -Module $name            
        }

        #endregion Run the test pass

    }
}