Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
Import-Counter.Tests.ps1469 linesDownload Raw Back to Microsoft.PowerShell.Diagnostics
1# Copyright (c) Microsoft Corporation.2# Licensed under the MIT License.3<############################################################################################4 # File: Import-Counter.Tests.ps15 # Provides Pester tests for the Import-Counter cmdlet.6 ############################################################################################>7 8 # Counter CmdLets are removed see issue #42729 # Tests are disabled10 return11 12$cmdletName = "Import-Counter"13 14. "$PSScriptRoot/CounterTestHelperFunctions.ps1"15 16$SkipTests = SkipCounterTests17 18if ( ! $SkipTests )19{20    $counterPaths = @(21        (TranslateCounterPath "\Memory\Available Bytes")22        (TranslateCounterPath "\processor(*)\% Processor time")23        (TranslateCounterPath "\Processor(_Total)\% Processor Time")24        (TranslateCounterPath "\PhysicalDisk(_Total)\Current Disk Queue Length")25        (TranslateCounterPath "\PhysicalDisk(_Total)\Disk Bytes/sec")26        (TranslateCounterPath "\PhysicalDisk(_Total)\Disk Read Bytes/sec")27        )28    $setNames = @{29        Memory = (TranslateCounterName "memory")30        PhysicalDisk = (TranslateCounterName "physicaldisk")31        Processor = (TranslateCounterName "processor")32        }33}34else35{36    $counterPaths = @()37    $setNames = @{}38}39 40$badSamplesBlgPath = Join-Path $PSScriptRoot "assets" "BadCounterSamples.blg"41$corruptBlgPath = Join-Path $PSScriptRoot "assets" "CorruptBlg.blg"42$notFoundPath = Join-Path $PSScriptRoot "DAD288C0-72F8-47D3-8C54-C69481B528DF.blg"43 44# Set script-scope variable values used by multiple Describes45function SetScriptVars([string]$rootPath, [int]$maxSamples, [bool]$export)46{47    $rootFilename = "exportedCounters"48 49    $script:blgPath = Join-Path $rootPath "$rootFilename.blg"50    $script:csvPath = Join-Path $rootPath "$rootFilename.csv"51    $script:tsvPath = Join-Path $rootPath "$rootFilename.tsv"52 53    $script:counterSamples = $null54    if ($maxSamples -and ! $SkipTests )55    {56        $script:counterSamples = Get-Counter -Counter $counterPaths -MaxSamples $maxSamples57    }58 59    if ($export -and ! $SkipTests )60    {61        Export-Counter -Force -FileFormat "blg" -Path $script:blgPath -InputObject $script:counterSamples62        Export-Counter -Force -FileFormat "csv" -Path $script:csvPath -InputObject $script:counterSamples63        Export-Counter -Force -FileFormat "tsv" -Path $script:tsvPath -InputObject $script:counterSamples64    }65}66 67# Build up a command to execute68function ConstructCommand($testCase)69{70    $filePath = ""71    $pathParam = ""72    $startTimeParam = ""73    $endTimeParam = ""74    if ($testCase.ContainsKey("Path"))75    {76        $filePath = $testCase.Path77    }78    else79    {80        $filePath = $script:blgPath81    }82 83    if ($testCase.NoDashPath)84    {85        $pathParam = $filePath86    }87    else88    {89        $pathParam = "-Path $filePath"90    }91 92    if ($testCase.ContainsKey("StartTime"))93    {94        $startTimeParam = "-StartTime `$testCase.StartTime"95    }96    if ($testCase.ContainsKey("EndTime"))97    {98        $endTimeParam = "-EndTime `$(`$testCase.EndTime)"99    }100 101    return "$cmdletName $pathParam $startTimeParam $endTimeParam $($testCase.Parameters)"102}103 104# Run a test that is expected to succeed105function RunTest($testCase)106{107    $skipTest = $testCase.SkipTest -or (SkipCounterTests)108 109    It "$($testCase.Name)" -Skip:$skipTest {110 111        if ($testCase.TimestampIndexes)112        {113            if ($testCase.TimestampIndexes.ContainsKey("First"))114            {115                $testCase.StartTime = $script:counterSamples[$testCase.TimestampIndexes.First].Timestamp116 117                # Exporting loses precision of DateTime objects, which results in almost always118                # missing the first expected item when importing with a controlling StartTime.119                # So, we'll adjust the precision of the timestamp we use for the StartTime value.120                $testCase.StartTime = New-Object System.DateTime ([Int64]([math]::floor($testCase.StartTime.Ticks / 10000)) * 10000)121            }122            if ($testCase.TimestampIndexes.ContainsKey("Last"))123            {124                $testCase.EndTime = $script:counterSamples[$testCase.TimestampIndexes.Last].Timestamp125            }126        }127 128        $cmd = ConstructCommand $testCase129        $cmd = $cmd + " -ErrorAction SilentlyContinue -ErrorVariable errVar"130 131        $errVar = $null132        $sb = [scriptblock]::Create($cmd)133        $result = &$sb134        $errVar | Should -BeNullOrEmpty135 136        if ($testCase.ContainsKey("Script"))137        {138            &$testCase.Script139        }140        else141        {142            if ($testCase.TimestampIndexes)143            {144                $start = 0145                $end = $script:counterSamples.Length - 1146                if ($testCase.TimestampIndexes.ContainsKey("First"))147                {148                    $start = $testCase.TimestampIndexes.First149                }150                if ($testCase.TimestampIndexes.ContainsKey("Last"))151                {152                    $end = $testCase.TimestampIndexes.Last153                }154 155                CompareCounterSets $result $script:counterSamples[$start..$end]156            }157            else158            {159                CompareCounterSets $result $script:counterSamples160            }161        }162    }163}164 165# Run a test for each file format166function RunPerFileTypeTests($testCase)167{168    if ($testCase.UseKnownSamples)169    {170        $basePath = Join-Path $PSScriptRoot "assets" "CounterSamples"171        $formats = @{172            "BLG" = "$basePath.blg"173            "CSV" = "$basePath.blg"174            "TSV" = "$basePath.blg"175        }176    }177    else178    {179        $formats = @{180            "BLG" = $script:blgPath181            "CSV" = $script:csvPath182            "TSV" = $script:tsvPath183        }184    }185 186    foreach ($f in $formats.GetEnumerator())187    {188        $newCase = $testCase.Clone();189        $newCase.Path = $f.Value190        $newCase.Name = "$($newCase.Name) ($($f.Name) format)"191 192        RunTest $newCase193    }194}195 196# Run a test case that is expected to fail197function RunExpectedFailureTest($testCase)198{199    It "$($testCase.Name)" -Skip:$(SkipCounterTests) {200        $cmd = ConstructCommand $testCase201        # Use $cmd to debug a test failure202        # Write-Host "Command to run: $cmd"203        $cmd = $cmd + " -ErrorAction Stop"204 205        if ($testCase.ContainsKey("Script"))206        {207            # Here we want to run the command then do our own post-run checks208            $sb = [ScriptBlock]::Create($cmd)209            &$sb210            &$testCase.Script211        }212        else213        {214            # Here we expect and want the command to fail215            $sb = [ScriptBlock]::Create($cmd)216            $e = { &$sb } | Should -Throw -ErrorId $testCase.ExpectedErrorId -PassThru217            if ($testCase.ExpectedErrorCategory)218            {219                $e.CategoryInfo.Category | Should -BeExactly $testCase.ExpectedErrorCategory220            }221        }222    }223}224 225Describe "CI tests for Import-Counter cmdlet" -Tags "CI" {226 227    BeforeAll {228        SetScriptVars $testDrive 0 $false229    }230 231    $performatTestCases = @(232        @{233            Name = "Can import all samples from known sample sets"234            UseKnownSamples = $true235            Script = {236                $result.Length | Should -Be 25237            }238        }239        @{240            Name = "Can acquire summary information"241            UseKnownSamples = $true242            Parameters = "-Summary"243            Script = {244                $result.SampleCount | Should -Be 25245                $result.OldestRecord | Should -Be (Get-Date -Year 2016 -Month 11 -Day 26 -Hour 13 -Minute 46 -Second 30 -Millisecond 874)246                $result.NewestRecord | Should -Be (Get-Date -Year 2016 -Month 11 -Day 26 -Hour 13 -Minute 47 -Second 42 -Millisecond 983)247            }248        }249    )250 251    foreach ($testCase in $performatTestCases)252    {253        RunPerFileTypeTests $testCase254    }255}256 257Describe "Feature tests for Import-Counter cmdlet" -Tags "Feature" {258 259    BeforeAll {260        SetScriptVars $testDrive 25 $true261    }262 263    AfterAll {264        Remove-Item $script:blgPath -Force -ErrorAction SilentlyContinue265        Remove-Item $script:csvPath -Force -ErrorAction SilentlyContinue266        Remove-Item $script:tsvPath -Force -ErrorAction SilentlyContinue267    }268 269    Context "Validate incorrect usage" {270        $testCases = @(271            @{272                Name = "Fails when given non-existent path"273                Path = $notFoundPath274                ExpectedErrorCategory = [System.Management.Automation.ErrorCategory]::ObjectNotFound275                ExpectedErrorId = "Microsoft.PowerShell.Commands.ImportCounterCommand"276            }277            @{278                Name = "Fails when given null path"279                Path = "`$null"280                ExpectedErrorId = "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ImportCounterCommand"281            }282            @{283                Name = "Fails when -Path specified but no path given"284                Path = ""285                ExpectedErrorId = "MissingArgument,Microsoft.PowerShell.Commands.ImportCounterCommand"286            }287            @{288                Name = "Fails when given -ListSet without set names"289                Parameters = "-ListSet"290                ExpectedErrorId = "MissingArgument,Microsoft.PowerShell.Commands.ImportCounterCommand"291            }292            @{293                Name = "Fails when given -StartTime without DateTime"294                Parameters = "-StartTime"295                ExpectedErrorId = "MissingArgument,Microsoft.PowerShell.Commands.ImportCounterCommand"296            }297            @{298                Name = "Fails when given -EndTime without DateTime"299                Parameters = "-EndTime"300                ExpectedErrorId = "MissingArgument,Microsoft.PowerShell.Commands.ImportCounterCommand"301            }302            @{303                Name = "Fails when given -ListSet and -Summary"304                Parameters = "-ListSet memory -Summary"305                ExpectedErrorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.ImportCounterCommand"306            }307            @{308                Name = "Fails when given -Summary and -Counter"309                Parameters = "-Summary -Counter `"\processor(*)\% processor time`""310                ExpectedErrorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.ImportCounterCommand"311            }312            @{313                Name = "Fails when given -ListSet and -Counter"314                Parameters = "-ListSet memory -Counter `"\processor(*)\% processor time`""315                ExpectedErrorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.ImportCounterCommand"316            }317            @{318                Name = "Fails when given -ListSet and -StartTime"319                StartTime = Get-Date320                Parameters = "-ListSet memory"321                ExpectedErrorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.ImportCounterCommand"322            }323            @{324                Name = "Fails when given -ListSet and -StartTime"325                StartTime = Get-Date326                Parameters = "-ListSet memory"327                ExpectedErrorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.ImportCounterCommand"328            }329            @{330                Name = "Fails when given -Summary and -EndTime"331                EndTime = Get-Date332                Parameters = "-Summary"333                ExpectedErrorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.ImportCounterCommand"334            }335            @{336                Name = "Fails when given -Summary and -EndTime"337                EndTime = Get-Date338                Parameters = "-Summary"339                ExpectedErrorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.ImportCounterCommand"340            }341            @{342                Name = "Fails when BLG file is corrupt"343                Path = $corruptBlgPath344                ExpectedErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult345                ExpectedErrorId = "CounterApiError,Microsoft.PowerShell.Commands.ImportCounterCommand"346            }347        )348 349        foreach ($testCase in $testCases)350        {351            RunExpectedFailureTest $testCase352        }353 354        It "Multiple errors when BLG file contains bad sample data" -Skip:$(SkipCounterTests) {355            $errVar = $null356            $result = Import-Counter $badSamplesBlgPath -ErrorVariable errVar -ErrorAction SilentlyContinue357            $result.Length | Should -Be 275358            $errVar.Count | Should -Be 5359            foreach ($err in $errVar)360            {361                $err.CategoryInfo.Category | Should -BeExactly "InvalidResult"362                $err.FullyQualifiedErrorId | Should -BeExactly "CounterApiError,Microsoft.PowerShell.Commands.ImportCounterCommand"363            }364        }365    }366 367    Context "Import tests" {368        $performatTestCases = @(369            @{370                Name = "Can import all samples"371            }372            @{373                Name = "Can import samples beginning at a given start time"374                TimestampIndexes = @{375                    First = 6376                }377            }378            @{379                Name = "Can import samples ending at a given end time"380                TimestampIndexes = @{381                    Last = 10382                }383            }384            @{385                Name = "Can import samples of a given timestamp range"386                TimestampIndexes = @{387                    First = 4388                    Last = 19389                }390            }391            @{392                Name = "Can acquire a named list set"393                UseKnownSamples = $true394                Parameters = "-ListSet $($setNames.Memory)"395                Script = {396                    $result.Length | Should -Be 1397                    $result[0].CounterSetName | Should -BeExactly $setNames.Memory398                }399            }400            @{401                Name = "Can acquire list set from an array of names"402                UseKnownSamples = $true403                Parameters = "-ListSet $(TranslateCounterName 'memory'), $(TranslateCounterName 'processor')"404                Script = {405                    $result.Length | Should -Be 2406                    $names = @()407                    foreach ($set in $result)408                    {409                        $names = $names + $set.CounterSetName410                    }411                    $names -Contains $setNames.Memory | Should -BeTrue412                    $names -Contains $setNames.Processor | Should -BeTrue413                }414            }415            @{416                # This test will be skipped for non-English languages, since417                # there is no reasonable way to construct a wild-card pattern418                # that will, for every language, result in a known set of values419                # or evan a set with a known minimum number of items.420                Name = "Can acquire list set via wild-card name"421                SkipTest = (-not (Get-Culture).Name.StartsWith("en-", [StringComparison]::InvariantCultureIgnoreCase))422                UseKnownSamples = $true423                Parameters = "-ListSet p*"424                Script = {425                    $result.Length | Should -BeGreaterThan 1426                    $names = @()427                    foreach ($set in $result)428                    {429                        $names = $names + $set.CounterSetName430                    }431                    $names -Contains "physicaldisk" | Should -BeTrue432                    $names -Contains "processor" | Should -BeTrue433                }434            }435            @{436                # This test will be skipped for non-English languages, since437                # there is no reasonable way to construct a wild-card pattern438                # that will, for every language, result in a known set of values439                # or evan a set with a known minimum number of items.440                Name = "Can acquire list set from an array of names including wild-card"441                SkipTest = (-not (Get-Culture).Name.StartsWith("en-", [StringComparison]::InvariantCultureIgnoreCase))442                UseKnownSamples = $true443                Parameters = "-ListSet memory, p*"444                Script = {445                    $result.Length | Should -BeGreaterThan 2446                    $names = @()447                    foreach ($set in $result) { $names = $names + $set.CounterSetName }448                    $names -Contains "memory" | Should -BeTrue449                    $names -Contains "processor" | Should -BeTrue450                    $names -Contains "physicaldisk" | Should -BeTrue451                }452            }453        )454 455        foreach ($testCase in $performatTestCases)456        {457            RunPerFileTypeTests $testCase458        }459    }460}461 462Describe "Import-Counter cmdlet does not run on IoT" -Tags "CI" {463 464    It "Import-Counter throws PlatformNotSupportedException" -Skip:$(-not [System.Management.Automation.Platform]::IsIoT)  {465        { Import-Counter -Path "$testDrive\ProcessorData.blg" } |466	    Should -Throw -ErrorId "System.PlatformNotSupportedException,Microsoft.PowerShell.Commands.ImportCounterCommand"467    }468}469