Pester/RequiredTests.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
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
param($BuildVariables)

$ModuleRoot = $BuildVariables.BuildRoot
$ModuleName = $BuildVariables.ModuleName

Describe "Public commands are tested"  {
    BeforeAll {
        $commandNames = Get-Command -Module $ModuleName | Select-Object -ExpandProperty Name
        $commandResults = @{}
        $commandNames | ForEach-Object {$commandResults[$_] = 0}

        $testFiles = Get-ChildItem -Path "$ModuleRoot\Tests" -Include "*.Tests.ps1" -Recurse

        # search every test file for command calls
        foreach ($file in $testFiles)
        {
            $content = Get-Content -Path $file.FullName -Raw
            foreach ($command in $commandNames)
            {
                $pattern = '\b{0}\b' -f $command
                if ($content -match $pattern)
                {
                    $commandResults[$command] += 1
                }
            }
        }

        # create testcases from results of command search
        $testCases = foreach($key in $commandResults.Keys)
        {
            @{
                Name = $key
                Count = $commandResults[$key]
            }
        }
    }

    It "[<Name>] has a test" -TestCases $testCases -skip:(!$testCases) {
        param($Name, $Count)
        $Count | Should -BeGreaterThan 0
    }
}