Wrap tests in pester blocks (#12700)

# PR Summary

Wrap tests in pester blocks to prepare for pesterv5

## PR Context

<!-- Provide a little reasoning as to why this Pull Request helps and why you have opened it. -->

## PR Checklist

- [x] [PR has a meaningful title](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission)
    - Use the present tense and imperative mood when describing your changes
- [x] [Summarized changes](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission)
- [x] [Make sure all `.h`, `.cpp`, `.cs`, `.ps1` and `.psm1` files have the correct copyright header](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission)
- [x] This PR is ready to merge and is not [Work in Progress](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---work-in-progress).
    - If the PR is work in progress, please add the prefix `WIP:` or `[ WIP ]` to the beginning of the title (the `WIP` bot will keep its status check at `Pending` while the prefix is present) and remove the prefix when the PR is ready.
- **[Breaking changes](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#making-breaking-changes)**
    - [x] None
    - **OR**
    - [ ] [Experimental feature(s) needed](https://github.com/MicrosoftDocs/PowerShell-Docs/blob/staging/reference/6/Microsoft.PowerShell.Core/About/about_Experimental_Features.md)
        - [ ] Experimental feature name(s): <!-- Experimental feature name(s) here -->
- **User-facing changes**
    - [x] Not Applicable
    - **OR**
    - [ ] [Documentation needed](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---submission)
        - [ ] Issue filed: <!-- Number/link of that issue here -->
- **Testing - New and feature**
    - [x] N/A or can only be tested interactively
    - **OR**
    - [ ] [Make sure you've added a new test if existing tests do not effectively test the code changed](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#before-submitting)
- **Tooling**
    - [x] I have considered the user experience from a tooling perspective and don't believe tooling will be impacted.
    - **OR**
    - [ ] I have considered the user experience from a tooling perspective and enumerated concerns in the summary. This may include:
        - Impact on [PowerShell Editor Services](https://github.com/PowerShell/PowerShellEditorServices) which is used in the [PowerShell extension](https://github.com/PowerShell/vscode-powershell) for VSCode (which runs in a different PS Host).
        - Impact on Completions (both in the console and in editors) - one of PowerShell's most powerful features.
        - Impact on [PSScriptAnalyzer](https://github.com/PowerShell/PSScriptAnalyzer) (which provides linting & formatting in the editor extensions).
        - Impact on [EditorSyntax](https://github.com/PowerShell/EditorSyntax) (which provides syntax highlighting with in VSCode, GitHub, and many other editors).
This commit is contained in:
xtqqczze
2020-05-23 13:24:53 +00:00
committed by GitHub
parent 12e0adc57a
commit 1f252f8bba
6 changed files with 340 additions and 348 deletions
+49 -49
View File
@@ -1,57 +1,57 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
function Test-Elevated {
[CmdletBinding()]
[OutputType([bool])]
Param()
# if the current Powershell session was called with administrator privileges,
# the Administrator Group's well-known SID will show up in the Groups for the current identity.
# Note that the SID won't show up unless the process is elevated.
return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544")
}
function Invoke-Msiexec {
param(
[Parameter(ParameterSetName = 'Install', Mandatory)]
[Switch]$Install,
[Parameter(ParameterSetName = 'Uninstall', Mandatory)]
[Switch]$Uninstall,
[Parameter(Mandatory)]
[ValidateScript({Test-Path -Path $_})]
[String]$MsiPath,
[Parameter(ParameterSetName = 'Install')]
[HashTable] $Properties
)
$action = "$($PSCmdlet.ParameterSetName)ing"
if ($Install.IsPresent) {
$switch = '/I'
} else {
$switch = '/x'
}
$additionalOptions = @()
if ($Properties) {
foreach ($key in $Properties.Keys) {
$additionalOptions += "$key=$($Properties.$key)"
}
}
$argumentList = "$switch $MsiPath /quiet /l*vx $msiLog $additionalOptions"
$msiExecProcess = Start-Process msiexec.exe -Wait -ArgumentList $argumentList -NoNewWindow -PassThru
if ($msiExecProcess.ExitCode -ne 0) {
$exitCode = $msiExecProcess.ExitCode
throw "$action MSI failed and returned error code $exitCode."
}
}
Describe -Name "Windows MSI" -Fixture {
BeforeAll {
function Test-Elevated {
[CmdletBinding()]
[OutputType([bool])]
Param()
# if the current Powershell session was called with administrator privileges,
# the Administrator Group's well-known SID will show up in the Groups for the current identity.
# Note that the SID won't show up unless the process is elevated.
return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544")
}
function Invoke-Msiexec {
param(
[Parameter(ParameterSetName = 'Install', Mandatory)]
[Switch]$Install,
[Parameter(ParameterSetName = 'Uninstall', Mandatory)]
[Switch]$Uninstall,
[Parameter(Mandatory)]
[ValidateScript({Test-Path -Path $_})]
[String]$MsiPath,
[Parameter(ParameterSetName = 'Install')]
[HashTable] $Properties
)
$action = "$($PSCmdlet.ParameterSetName)ing"
if ($Install.IsPresent) {
$switch = '/I'
} else {
$switch = '/x'
}
$additionalOptions = @()
if ($Properties) {
foreach ($key in $Properties.Keys) {
$additionalOptions += "$key=$($Properties.$key)"
}
}
$argumentList = "$switch $MsiPath /quiet /l*vx $msiLog $additionalOptions"
$msiExecProcess = Start-Process msiexec.exe -Wait -ArgumentList $argumentList -NoNewWindow -PassThru
if ($msiExecProcess.ExitCode -ne 0) {
$exitCode = $msiExecProcess.ExitCode
throw "$action MSI failed and returned error code $exitCode."
}
}
$msiX64Path = $env:PsMsiX64Path
# Get any existing powershell in the path
@@ -1,43 +1,42 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Describe 'NestedModules' -Tags "CI" {
BeforeAll {
function New-TestModule {
param(
[string]$Name,
[string]$Content,
[string[]]$NestedContents
)
function New-TestModule {
param(
[string]$Name,
[string]$Content,
[string[]]$NestedContents
)
New-Item -type directory -Force "TestDrive:\$Name" > $null
$manifestParams = @{
Path = "TestDrive:\$Name\$Name.psd1"
}
New-Item -type directory -Force "TestDrive:\$Name" > $null
$manifestParams = @{
Path = "TestDrive:\$Name\$Name.psd1"
}
if ($Content) {
Set-Content -Path "${TestDrive}\$Name\$Name.psm1" -Value $Content
$manifestParams['RootModule'] = "$Name.psm1"
}
if ($Content) {
Set-Content -Path "${TestDrive}\$Name\$Name.psm1" -Value $Content
$manifestParams['RootModule'] = "$Name.psm1"
}
if ($NestedContents) {
$manifestParams['NestedModules'] = 1..$NestedContents.Count | ForEach-Object {
$null = New-Item -type directory TestDrive:\$Name\Nested$_
$null = Set-Content -Path "${TestDrive}\$Name\Nested$_\Nested$_.psm1" -Value $NestedContents[$_ - 1]
"Nested$_"
}
}
if ($NestedContents) {
$manifestParams['NestedModules'] = 1..$NestedContents.Count | ForEach-Object {
$null = New-Item -type directory TestDrive:\$Name\Nested$_
$null = Set-Content -Path "${TestDrive}\$Name\Nested$_\Nested$_.psm1" -Value $NestedContents[$_ - 1]
"Nested$_"
New-ModuleManifest @manifestParams
$resolvedTestDrivePath = Split-Path ((Get-ChildItem TestDrive:\)[0].FullName)
if (-not ($env:PSModulePath -like "*$resolvedTestDrivePath*")) {
$env:PSModulePath += "$([System.IO.Path]::PathSeparator)$resolvedTestDrivePath"
}
}
New-ModuleManifest @manifestParams
$resolvedTestDrivePath = Split-Path ((Get-ChildItem TestDrive:\)[0].FullName)
if (-not ($env:PSModulePath -like "*$resolvedTestDrivePath*")) {
$env:PSModulePath += "$([System.IO.Path]::PathSeparator)$resolvedTestDrivePath"
}
}
$originalPSModulePath = $env:PSModulePath
try {
$originalPSModulePath = $env:PSModulePath
# Create modules in TestDrive:\
New-TestModule -Name NoRoot -NestedContents @(
@@ -54,72 +53,74 @@ Describe 'NestedModules' -Tags "CI" {
'class A { [string] foo() { return "A"} }',
'class B { [string] foo() { return "B"} }'
) -Content 'class C { [string] foo() { return "C"} }'
}
It 'Get-Module is able to find types' {
$module = Get-Module NoRoot -ListAvailable
$module.GetExportedTypeDefinitions().Count | Should -Be 1
AfterAll {
$env:PSModulePath = $originalPSModulePath
Get-Module @('ABC', 'NoRoot', 'WithRoot') | Remove-Module
}
$module = Get-Module WithRoot -ListAvailable
$module.GetExportedTypeDefinitions().Count | Should -Be 1
$module = Get-Module ABC -ListAvailable
$module.GetExportedTypeDefinitions().Count | Should -Be 3
}
It 'Get-Module is able to find types' {
$module = Get-Module NoRoot -ListAvailable
$module.GetExportedTypeDefinitions().Count | Should -Be 1
It 'Import-Module pick the right type' {
$module = Import-Module ABC -PassThru
$module.GetExportedTypeDefinitions().Count | Should -Be 3
$module = Import-Module ABC -PassThru -Force
$module.GetExportedTypeDefinitions().Count | Should -Be 3
$module = Get-Module WithRoot -ListAvailable
$module.GetExportedTypeDefinitions().Count | Should -Be 1
$module = Import-Module NoRoot -PassThru
$module.GetExportedTypeDefinitions().Count | Should -Be 1
$module = Import-Module NoRoot -PassThru -Force
$module.GetExportedTypeDefinitions().Count | Should -Be 1
[scriptblock]::Create(@'
$module = Get-Module ABC -ListAvailable
$module.GetExportedTypeDefinitions().Count | Should -Be 3
}
It 'Import-Module pick the right type' {
$module = Import-Module ABC -PassThru
$module.GetExportedTypeDefinitions().Count | Should -Be 3
$module = Import-Module ABC -PassThru -Force
$module.GetExportedTypeDefinitions().Count | Should -Be 3
$module = Import-Module NoRoot -PassThru
$module.GetExportedTypeDefinitions().Count | Should -Be 1
$module = Import-Module NoRoot -PassThru -Force
$module.GetExportedTypeDefinitions().Count | Should -Be 1
[scriptblock]::Create(@'
using module NoRoot
[A]::new().foo()
'@
).Invoke() | Should -Be A2
$module = Import-Module WithRoot -PassThru
$module.GetExportedTypeDefinitions().Count | Should -Be 1
$module = Import-Module WithRoot -PassThru -Force
$module.GetExportedTypeDefinitions().Count | Should -Be 1
[scriptblock]::Create(@'
$module = Import-Module WithRoot -PassThru
$module.GetExportedTypeDefinitions().Count | Should -Be 1
$module = Import-Module WithRoot -PassThru -Force
$module.GetExportedTypeDefinitions().Count | Should -Be 1
[scriptblock]::Create(@'
using module WithRoot
[A]::new().foo()
'@
).Invoke() | Should -Be A0
}
Context 'execute type creation in the module context' {
# let's define types to make it more fun
class A { [string] foo() { return "local"} }
class B { [string] foo() { return "local"} }
class C { [string] foo() { return "local"} }
# We need to think about it: should it work or not.
# Currently, types are resolved in compile-time to the 'local' versions
# So at runtime we don't call the module versions.
It 'Can execute type creation in the module context with new()' -Pending {
& (Get-Module ABC) { [C]::new().foo() } | Should -Be C
& (Get-Module NoRoot) { [A]::new().foo() } | Should -Be A2
& (Get-Module WithRoot) { [A]::new().foo() } | Should -Be A0
& (Get-Module ABC) { [A]::new().foo() } | Should -Be A
}
Context 'execute type creation in the module context' {
# let's define types to make it more fun
class A { [string] foo() { return "local"} }
class B { [string] foo() { return "local"} }
class C { [string] foo() { return "local"} }
# We need to think about it: should it work or not.
# Currently, types are resolved in compile-time to the 'local' versions
# So at runtime we don't call the module versions.
It 'Can execute type creation in the module context with new()' -Pending {
& (Get-Module ABC) { [C]::new().foo() } | Should -Be C
& (Get-Module NoRoot) { [A]::new().foo() } | Should -Be A2
& (Get-Module WithRoot) { [A]::new().foo() } | Should -Be A0
& (Get-Module ABC) { [A]::new().foo() } | Should -Be A
}
It 'Can execute type creation in the module context with New-Object' {
& (Get-Module ABC) { (New-Object C).foo() } | Should -Be C
& (Get-Module NoRoot) { (New-Object A).foo() } | Should -Be A2
& (Get-Module WithRoot) { (New-Object A).foo() } | Should -Be A0
& (Get-Module ABC) { (New-Object A).foo() } | Should -Be A
}
It 'Can execute type creation in the module context with New-Object' {
& (Get-Module ABC) { (New-Object C).foo() } | Should -Be C
& (Get-Module NoRoot) { (New-Object A).foo() } | Should -Be A2
& (Get-Module WithRoot) { (New-Object A).foo() } | Should -Be A0
& (Get-Module ABC) { (New-Object A).foo() } | Should -Be A
}
} finally {
$env:PSModulePath = $originalPSModulePath
Get-Module @('ABC', 'NoRoot', 'WithRoot') | Remove-Module
}
}
@@ -1,12 +1,11 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Describe "ConvertFrom-Csv" -Tags "CI" {
BeforeAll {
$testObject = "a", "1"
$testcsv = Join-Path -Path (Join-Path -Path $here -ChildPath assets) -ChildPath TestCsv2.csv
$testcsv = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath TestCsv2.csv
$testName = "Zaphod BeebleBrox"
$testColumns = @"
a,b,c
@@ -6,95 +6,92 @@
# Windows so that file IO can be verified using supported cmdlets.
#
try {
# Skip these tests when run against "InBox" PowerShell
$IsInbox = $PSHOME.EndsWith('\WindowsPowerShell\v1.0', [System.StringComparison]::OrdinalIgnoreCase)
$productName = "PowerShell"
Describe "User-Specific powershell.config.json Modifications" -Tags "CI" {
#skip all tests on non-windows platform
$originalDefaultParameterValues = $PSDefaultParameterValues.Clone()
$IsNotSkipped = ($IsWindows -and !$IsInbox) # Only execute for PowerShell on Windows
$PSDefaultParameterValues["it:skip"] = !$IsNotSkipped
BeforeAll {
# Skip these tests when run against "InBox" PowerShell
$IsInbox = $PSHOME.EndsWith('\WindowsPowerShell\v1.0', [System.StringComparison]::OrdinalIgnoreCase)
$productName = "PowerShell"
Describe "User-Specific powershell.config.json Modifications" -Tags "CI" {
#skip all tests on non-windows platform
$originalDefaultParameterValues = $PSDefaultParameterValues.Clone()
$IsNotSkipped = ($IsWindows -and !$IsInbox) # Only execute for PowerShell on Windows
$PSDefaultParameterValues["it:skip"] = !$IsNotSkipped
BeforeAll {
if ($IsNotSkipped) {
# Discover the user-specific powershell.config.json file
$userSettingsDir = [System.IO.Path]::Combine($env:USERPROFILE, "Documents", $productName)
$userPropertiesFile = Join-Path $userSettingsDir "powershell.config.json"
if ($IsNotSkipped) {
# Discover the user-specific powershell.config.json file
$userSettingsDir = [System.IO.Path]::Combine($env:USERPROFILE, "Documents", $productName)
$userPropertiesFile = Join-Path $userSettingsDir "powershell.config.json"
# Save the file for restoration after the tests are complete
$backupPropertiesFile = ""
if (Test-Path $userPropertiesFile) {
$backupPropertiesFile = Join-Path $userSettingsDir "ORIGINAL_powershell.config.json"
Copy-Item -Path $userPropertiesFile -Destination $backupPropertiesFile -Force -ErrorAction Continue
}
elseif (-not (Test-Path $userSettingsDir)) {
# create the directory if it does not already exist
$null = New-Item -Type Directory -Path $userSettingsDir -Force -ErrorAction SilentlyContinue
}
# Save the original Process ExecutionPolicy. The tests assume that it is Undefined
$processExecutionPolicy = Get-ExecutionPolicy -Scope Process
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Undefined
# Save the file for restoration after the tests are complete
$backupPropertiesFile = ""
if (Test-Path $userPropertiesFile) {
$backupPropertiesFile = Join-Path $userSettingsDir "ORIGINAL_powershell.config.json"
Copy-Item -Path $userPropertiesFile -Destination $backupPropertiesFile -Force -ErrorAction Continue
}
}
BeforeEach {
if ($IsNotSkipped) {
Set-Content -Path $userPropertiesFile -Value '{"Microsoft.PowerShell:ExecutionPolicy":"RemoteSigned"}'
elseif (-not (Test-Path $userSettingsDir)) {
# create the directory if it does not already exist
$null = New-Item -Type Directory -Path $userSettingsDir -Force -ErrorAction SilentlyContinue
}
}
AfterAll {
if ($IsNotSkipped) {
if (-not $backupPropertiesFile)
{
# Remove powershell.config.json if it did not exist before the tests
Remove-Item -Path $userPropertiesFile -Force -ErrorAction SilentlyContinue
}
else
{
# Restore the original powershell.config.json file if it existed before the test pass.
Move-Item -Path $backupPropertiesFile -Destination $userPropertiesFile -Force -ErrorAction Continue
}
# Restore the original Process ExecutionPolicy
Set-ExecutionPolicy -Scope Process -ExecutionPolicy $processExecutionPolicy
}
}
It "Verify Queries to Missing File Return Default Value" {
Remove-Item $userPropertiesFile -Force
Get-ExecutionPolicy -Scope CurrentUser | Should -Be "Undefined"
# Verify the file was not created during the test
{ $propFile = Get-Item $userPropertiesFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand"
}
It "Verify Queries for Non-Existant Properties Return Default Value" {
# Create a valid file with no values
Set-Content -Path $userPropertiesFile -Value "{}"
Get-ExecutionPolicy -Scope CurrentUser | Should -Be "Undefined"
}
It "Verify Writes Update Properties" {
Get-Content -Path $userPropertiesFile | Should -Be '{"Microsoft.PowerShell:ExecutionPolicy":"RemoteSigned"}'
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass
Get-Content -Path $userPropertiesFile | Should -Be '{"Microsoft.PowerShell:ExecutionPolicy":"Bypass"}'
}
It "Verify Writes Create the File if Not Present" {
Remove-Item $userPropertiesFile -Force
Test-Path $userPropertiesFile | Should -BeFalse
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass
Get-Content -Path $userPropertiesFile | Should -Be '{"Microsoft.PowerShell:ExecutionPolicy":"Bypass"}'
# Save the original Process ExecutionPolicy. The tests assume that it is Undefined
$processExecutionPolicy = Get-ExecutionPolicy -Scope Process
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Undefined
}
}
}
finally {
$global:PSDefaultParameterValues = $originalDefaultParameterValues
BeforeEach {
if ($IsNotSkipped) {
Set-Content -Path $userPropertiesFile -Value '{"Microsoft.PowerShell:ExecutionPolicy":"RemoteSigned"}'
}
}
AfterAll {
if ($IsNotSkipped) {
if (-not $backupPropertiesFile)
{
# Remove powershell.config.json if it did not exist before the tests
Remove-Item -Path $userPropertiesFile -Force -ErrorAction SilentlyContinue
}
else
{
# Restore the original powershell.config.json file if it existed before the test pass.
Move-Item -Path $backupPropertiesFile -Destination $userPropertiesFile -Force -ErrorAction Continue
}
# Restore the original Process ExecutionPolicy
Set-ExecutionPolicy -Scope Process -ExecutionPolicy $processExecutionPolicy
}
$global:PSDefaultParameterValues = $originalDefaultParameterValues
}
It "Verify Queries to Missing File Return Default Value" {
Remove-Item $userPropertiesFile -Force
Get-ExecutionPolicy -Scope CurrentUser | Should -Be "Undefined"
# Verify the file was not created during the test
{ $propFile = Get-Item $userPropertiesFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand"
}
It "Verify Queries for Non-Existant Properties Return Default Value" {
# Create a valid file with no values
Set-Content -Path $userPropertiesFile -Value "{}"
Get-ExecutionPolicy -Scope CurrentUser | Should -Be "Undefined"
}
It "Verify Writes Update Properties" {
Get-Content -Path $userPropertiesFile | Should -Be '{"Microsoft.PowerShell:ExecutionPolicy":"RemoteSigned"}'
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass
Get-Content -Path $userPropertiesFile | Should -Be '{"Microsoft.PowerShell:ExecutionPolicy":"Bypass"}'
}
It "Verify Writes Create the File if Not Present" {
Remove-Item $userPropertiesFile -Force
Test-Path $userPropertiesFile | Should -BeFalse
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass
Get-Content -Path $userPropertiesFile | Should -Be '{"Microsoft.PowerShell:ExecutionPolicy":"Bypass"}'
}
}
+66 -66
View File
@@ -1,71 +1,74 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
try {
$defaultParamValues = $PSDefaultParameterValues.Clone()
$PSDefaultParameterValues["it:skip"] = ![System.Management.Automation.Platform]::IsWindowsDesktop
Describe 'Basic COM Tests' -Tags "CI" {
BeforeAll {
$null = New-Item -Path $TESTDRIVE/file1 -ItemType File
$null = New-Item -Path $TESTDRIVE/file2 -ItemType File
$null = New-Item -Path $TESTDRIVE/file3 -ItemType File
}
It "Should enumerate files from a folder" {
$shell = New-Object -ComObject "Shell.Application"
$folder = $shell.Namespace("$TESTDRIVE")
$items = $folder.Items()
## $items is a collection of all items belong to the folder, and it should be enumerated.
$items.Count | Should -Be 3
$items | Measure-Object | ForEach-Object Count | Should -Be $items.Count
$names = $items | ForEach-Object { $_.Name }
$names -join "," | Should -Be "file1,file2,file3"
}
It "Should enumerate IEnumVariant interface object without exception" {
$shell = New-Object -ComObject "Shell.Application"
$folder = $shell.Namespace("$TESTDRIVE")
$items = $folder.Items()
## $enumVariant is an IEnumVariant interface of all items belong to the folder, and it should be enumerated.
$enumVariant = $items._NewEnum()
$items.Count | Should -Be 3
$enumVariant | Measure-Object | ForEach-Object Count | Should -Be $items.Count
}
It "Should enumerate drives" {
$fileSystem = New-Object -ComObject scripting.filesystemobject
$drives = $fileSystem.Drives
## $drives is a read-only collection of all available drives, and it should be enumerated.
$drives | Measure-Object | ForEach-Object Count | Should -Be $drives.Count
## $element should be the first drive from the enumeration. It shouldn't be the same as $drives,
## but it should be the same as '$drives.Item($element.DriveLetter)'
$element = $drives | Select-Object -First 1
[System.Object]::ReferenceEquals($element, $drives) | Should -BeFalse
$element | Should -Be $drives.Item($element.DriveLetter)
}
It "Should be able to enumerate 'IADsMembers' object" {
$group = [ADSI]"WinNT://./Users,Group"
$members = $group.Invoke('Members')
$names = $members | ForEach-Object { $_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null) }
$names | Should -Contain 'INTERACTIVE'
}
It "ToString() should return method paramter names" {
$shell = New-Object -ComObject "Shell.Application"
$fullSignature = $shell.AddToRecent.ToString()
$fullSignature | Should -BeExactly "void AddToRecent (Variant varFile, string bstrCategory)"
}
Describe 'Basic COM Tests' -Tags "CI" {
BeforeAll {
$defaultParamValues = $PSDefaultParameterValues.Clone()
$PSDefaultParameterValues["it:skip"] = ![System.Management.Automation.Platform]::IsWindowsDesktop
}
Describe 'GetMember/SetMember/InvokeMember binders should have more restricted rule for COM object' -Tags "CI" {
AfterAll {
$global:PSDefaultParameterValues = $defaultParamValues
}
BeforeAll {
$null = New-Item -Path $TESTDRIVE/file1 -ItemType File
$null = New-Item -Path $TESTDRIVE/file2 -ItemType File
$null = New-Item -Path $TESTDRIVE/file3 -ItemType File
}
It "Should enumerate files from a folder" {
$shell = New-Object -ComObject "Shell.Application"
$folder = $shell.Namespace("$TESTDRIVE")
$items = $folder.Items()
## $items is a collection of all items belong to the folder, and it should be enumerated.
$items.Count | Should -Be 3
$items | Measure-Object | ForEach-Object Count | Should -Be $items.Count
$names = $items | ForEach-Object { $_.Name }
$names -join "," | Should -Be "file1,file2,file3"
}
It "Should enumerate IEnumVariant interface object without exception" {
$shell = New-Object -ComObject "Shell.Application"
$folder = $shell.Namespace("$TESTDRIVE")
$items = $folder.Items()
## $enumVariant is an IEnumVariant interface of all items belong to the folder, and it should be enumerated.
$enumVariant = $items._NewEnum()
$items.Count | Should -Be 3
$enumVariant | Measure-Object | ForEach-Object Count | Should -Be $items.Count
}
It "Should enumerate drives" {
$fileSystem = New-Object -ComObject scripting.filesystemobject
$drives = $fileSystem.Drives
## $drives is a read-only collection of all available drives, and it should be enumerated.
$drives | Measure-Object | ForEach-Object Count | Should -Be $drives.Count
## $element should be the first drive from the enumeration. It shouldn't be the same as $drives,
## but it should be the same as '$drives.Item($element.DriveLetter)'
$element = $drives | Select-Object -First 1
[System.Object]::ReferenceEquals($element, $drives) | Should -BeFalse
$element | Should -Be $drives.Item($element.DriveLetter)
}
It "Should be able to enumerate 'IADsMembers' object" {
$group = [ADSI]"WinNT://./Users,Group"
$members = $group.Invoke('Members')
$names = $members | ForEach-Object { $_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null) }
$names | Should -Contain 'INTERACTIVE'
}
It "ToString() should return method paramter names" {
$shell = New-Object -ComObject "Shell.Application"
$fullSignature = $shell.AddToRecent.ToString()
$fullSignature | Should -BeExactly "void AddToRecent (Variant varFile, string bstrCategory)"
}
Context 'GetMember/SetMember/InvokeMember binders should have more restricted rule for COM object' {
BeforeAll {
if ([System.Management.Automation.Platform]::IsWindowsDesktop) {
$null = New-Item -Path $TESTDRIVE/bar -ItemType Directory -Force
@@ -110,7 +113,4 @@ try {
$str.Windows() | Should -Be "Windows"
}
}
} finally {
$global:PSdefaultParameterValues = $defaultParamValues
}
+64 -69
View File
@@ -1,25 +1,23 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
function getIndex
{
param([string[]]$strings,[string]$pattern)
for ($i = 0; $i -lt $strings.Count; $i++) {
if ($strings[$i] -like $pattern) {
return $i
}
}
return -1
}
try {
if ( ! $IsWindows ) {
$PSDefaultParameterValues["it:pending"] = $true
}
Describe "CIM Objects are adapted properly" -Tag @("CI") {
BeforeAll {
if ( ! $IsWindows ) {
return
Describe "CIM Objects are adapted properly" -Tag @("CI") {
BeforeAll {
function getIndex
{
param([string[]]$strings,[string]$pattern)
for ($i = 0; $i -lt $strings.Count; $i++) {
if ($strings[$i] -like $pattern) {
return $i
}
}
return -1
}
if ( ! $IsWindows ) {
$PSDefaultParameterValues["it:pending"] = $true
}
else {
$p = Get-CimInstance win32_process |Select-Object -First 1
$indexOf_namespaceQualified_Win32Process = getIndex $p.PSTypeNames "*root?cimv2?Win32_Process"
@@ -32,61 +30,58 @@ try {
$indexOf_className_CimLogicalElement = getIndex $p.PSTypeNames "*#CIM_LogicalElement"
$indexOf_className_CimManagedSystemElement = getIndex $p.PSTypeNames "*#CIM_ManagedSystemElement"
}
AfterAll {
$PSDefaultParameterValues.Remove("it:pending")
}
}
AfterAll {
$PSDefaultParameterValues.Remove("it:pending")
}
It "Namespace-qualified Win32_Process is present" -Skip:(!$IsWindows) {
$indexOf_namespaceQualified_Win32Process | Should -Not -Be (-1)
}
It "Namespace-qualified CIM_Process is present" {
$indexOf_namespaceQualified_CimProcess | Should -Not -Be (-1)
}
It "Namespace-qualified CIM_LogicalElement is present" {
$indexOf_namespaceQualified_CimLogicalElement | Should -Not -Be (-1)
}
It "Namespace-qualified CIM_ManagedSystemElement is present" {
$indexOf_namespaceQualified_CimManagedSystemElement | Should -Not -Be (-1)
}
It "Namespace-qualified Win32_Process is present" -Skip:(!$IsWindows) {
$indexOf_namespaceQualified_Win32Process | Should -Not -Be (-1)
}
It "Namespace-qualified CIM_Process is present" {
$indexOf_namespaceQualified_CimProcess | Should -Not -Be (-1)
}
It "Namespace-qualified CIM_LogicalElement is present" {
$indexOf_namespaceQualified_CimLogicalElement | Should -Not -Be (-1)
}
It "Namespace-qualified CIM_ManagedSystemElement is present" {
$indexOf_namespaceQualified_CimManagedSystemElement | Should -Not -Be (-1)
}
It "Classname of Win32_Process is present" -Skip:(!$IsWindows) {
$indexOf_className_Win32Process | Should -Not -Be (-1)
}
It "Classname of CIM_Process is present" {
$indexOf_className_CimProcess | Should -Not -Be (-1)
}
It "Classname of CIM_LogicalElement is present" {
$indexOf_className_CimLogicalElement | Should -Not -Be (-1)
}
It "Classname of CIM_ManagedSystemElement is present" {
$indexOf_className_CimManagedSystemElement | Should -Not -Be (-1)
}
It "Classname of Win32_Process is present" -Skip:(!$IsWindows) {
$indexOf_className_Win32Process | Should -Not -Be (-1)
}
It "Classname of CIM_Process is present" {
$indexOf_className_CimProcess | Should -Not -Be (-1)
}
It "Classname of CIM_LogicalElement is present" {
$indexOf_className_CimLogicalElement | Should -Not -Be (-1)
}
It "Classname of CIM_ManagedSystemElement is present" {
$indexOf_className_CimManagedSystemElement | Should -Not -Be (-1)
}
It "Win32_Process comes after CIM_Process (namespace qualified)" -Skip:(!$IsWindows) {
$indexOf_namespaceQualified_Win32Process | Should -BeLessThan $indexOf_namespaceQualified_CimProcess
}
It "CIM_Process comes after CIM_LogicalElement (namespace qualified)" {
$indexOf_namespaceQualified_CimProcess | Should -BeLessThan $indexOf_namespaceQualified_CimLogicalElement
}
It "CIM_LogicalElement comes after CIM_ManagedSystemElement (namespace qualified)" {
$indexOf_namespaceQualified_CimLogicalElement | Should -BeLessThan $indexOf_namespaceQualified_CimManagedSystemElement
}
It "Win32_Process comes after CIM_Process (namespace qualified)" -Skip:(!$IsWindows) {
$indexOf_namespaceQualified_Win32Process | Should -BeLessThan $indexOf_namespaceQualified_CimProcess
}
It "CIM_Process comes after CIM_LogicalElement (namespace qualified)" {
$indexOf_namespaceQualified_CimProcess | Should -BeLessThan $indexOf_namespaceQualified_CimLogicalElement
}
It "CIM_LogicalElement comes after CIM_ManagedSystemElement (namespace qualified)" {
$indexOf_namespaceQualified_CimLogicalElement | Should -BeLessThan $indexOf_namespaceQualified_CimManagedSystemElement
}
It "Win32_Process comes after CIM_Process (classname only)" -Skip:(!$IsWindows) {
$indexOf_className_Win32Process | Should -BeLessThan $indexOf_className_CimProcess
}
It "CIM_Process comes after CIM_LogicalElement (classname only)" {
$indexOf_className_CimProcess | Should -BeLessThan $indexOf_className_CimLogicalElement
}
It "CIM_LogicalElement comes after CIM_ManagedSystemElement (classname only)" {
$indexOf_className_CimLogicalElement | Should -BeLessThan $indexOf_className_CimManagedSystemElement
}
It "Win32_Process comes after CIM_Process (classname only)" -Skip:(!$IsWindows) {
$indexOf_className_Win32Process | Should -BeLessThan $indexOf_className_CimProcess
}
It "CIM_Process comes after CIM_LogicalElement (classname only)" {
$indexOf_className_CimProcess | Should -BeLessThan $indexOf_className_CimLogicalElement
}
It "CIM_LogicalElement comes after CIM_ManagedSystemElement (classname only)" {
$indexOf_className_CimLogicalElement | Should -BeLessThan $indexOf_className_CimManagedSystemElement
}
It "Namespace qualified PSTypenames comes after class-only PSTypeNames" -Skip:(!$IsWindows) {
$indexOf_namespaceQualified_CimManagedSystemElement | Should -BeLessThan $indexOf_className_Win32Process
}
It "Namespace qualified PSTypenames comes after class-only PSTypeNames" -Skip:(!$IsWindows) {
$indexOf_namespaceQualified_CimManagedSystemElement | Should -BeLessThan $indexOf_className_Win32Process
}
}
finally {
$PSDefaultParameterValues.Remove("it:pending")
}